首页 > 解决方案 > 无法使用其名称作为名称的变量删除不和谐频道导致非类型错误

问题描述

我有一个命令,该命令接受输入,然后根据该输入为票务系统删除一个频道。该命令现在可以删除通道,但删除方法无法识别“输出”变量。

我是不和谐的新手,提前抱歉。

if message.content.startswith(".close"):
        verify_channel = client.get_channel(756238816511131773)
        if not message.channel.id == verify_channel.id:
            await message.delete()
        else:
            msg = message.content.split()
            output = ""
            for word in msg[1:]:
                output += word
                output += " "
        
       guild = message.guild
            channel = discord.utils.get(guild.text_channels, name=output)
            await channel.delete()

运行命令时产生错误:

AttributeError: 'NoneType' object has no attribute 'delete'

标签: pythondiscorddiscord.pydiscord.py-rewrite

解决方案


这是使用频道提及的工作代码。聊天中的提及如下所示:频道名称I'm mentioning a channel: #ghi在哪里。ghi如果您将其打印出来,它会将 #ghi 转换为<#622194268139683870>. 您可以使用正则表达式或其他方法提取它,但您也可以在消息上调用函数:

channel = message.channel_mentions[0] #Only use the first channel mentioned
await channel.delete()

这是一个转换为命令的工作示例,我建议使用它来启动每个函数if startswith(command_name)

bot = commands.Bot(command_prefix=".")

@bot.command()
async def close(ctx):
    channel = ctx.message.channel_mentions[0]
    await channel.delete()
    print("Success")

然后,您可以从聊天中调用.close #ghi

如果您打算保留它,请确保将其添加到您的 ON_MESSAGE 事件的顶部

async def on_message(message):
    await bot.process_commands(message)

我已经测试过了,它可以工作。


PS:命令还具有轻松获取参数而不是用空格分割字符串的优点,我现在无法解释,但我推荐文档:https://discordpy.readthedocs.io/en/latest/ext/commands/commands .html

我没有包括这个,因为你的函数可以在没有它的情况下编写。


推荐阅读