python - 无法使用其名称作为名称的变量删除不和谐频道导致非类型错误
问题描述
我有一个命令,该命令接受输入,然后根据该输入为票务系统删除一个频道。该命令现在可以删除通道,但删除方法无法识别“输出”变量。
我是不和谐的新手,提前抱歉。
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'
解决方案
这是使用频道提及的工作代码。聊天中的提及如下所示:频道名称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
我没有包括这个,因为你的函数可以在没有它的情况下编写。
推荐阅读
- node.js - 如何等到 URL 更改/或直到连接脱机
- wordpress - 如何修复 Chrome 将我的网站标记为危险
- flutter - 当用户按下或从芯片小部件列表中选择时,我如何获得芯片的值
- javascript - 如何按给定字段重新组合对象数组
- react-native - React Native 内联函数理解
- r - 将堆叠条形图的宽度更改为样本大小
- excel - 无法使用 Officegen 通过 Word 文档中的插入选项将 excel 作为对象嵌入
- php - Laravel Raw 语句我可以根据列数据是否等于另一个表从不同的表中进行选择
- c# - profile.User.Identity.IsAuthenticated 返回 false 没有人帮助我
- python - ValueError:层顺序需要 1 个输入,但它接收到 239 个输入张量