Discord.py onmessage角色分配问题

Discord.py onmessage角色分配问题,discord.py,Discord.py,我一直在努力解决这个问题,但无法找出我做错了什么,删除和显示消息的方法很好,但当我试图让它分配角色的同时,我打破了它 @bot.event async def on_message(msg): for badword in file: if badword in msg.content.lower(): role = discord.utils.get(msg.guild.roles, name="Muted") await msg.aut

我一直在努力解决这个问题,但无法找出我做错了什么,删除和显示消息的方法很好,但当我试图让它分配角色的同时,我打破了它

@bot.event
async def on_message(msg):
  for badword in file:
    if badword in msg.content.lower():
      role = discord.utils.get(msg.guild.roles, name="Muted")
      await msg.author.add_roles(role)
      await msg.delete()
      await msg.channel.send(f'{msg.author.mention}! That was a bad word! You have been muted!')
    await bot.process_commands(msg)
我想我错过了一些简单的事情

这就是我得到的错误:

Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 283, in on_message
    await msg.author.add_roles(role)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 676, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
此外,上面的操作会使我的其他bot.commands无限期重复。所以现在,当我使用“随机引用”命令时,它永远不会停止,直到我关闭机器人:

#wisdom function
@bot.command(help="Wisdom function",
             brief="Get a random wise quote")
async def wisdom(ctx):
  responses = open('quotes.txt').read().splitlines()
  random.seed(a=None)
  response = random.choice(responses)
  await ctx.send(f'Hey {ctx.message.author.mention} here is your wisdom:')
  await ctx.send(response)
这里的问题是
discord.utils.get
找不到名为Muted的角色,因此它返回一个NoneType。当您试图分配角色时,实际上是在执行
msg.author.add\u roles(None)
。也许可以尝试确保角色存在,或者通过ID而不是名称引用它

编辑:您还应该(在报价功能中)以与第一条相同的消息发送报价。(使用
\n
作为换行符)

编辑2:您应该使用
with
块来读取文件中的行,因为您现在拥有的,文件永远不会关闭。另外,
read()
返回一个字符串,您不能对该字符串执行
readlines()
操作。而是从文件对象中执行
readlines()


编辑3:您正在处理文件中每个坏字的命令(为什么它永远运行)

请参阅@Frederick Reynolds post,了解您在读取文本文件时的错误。不过,我也可以指出一些事情。对于您的
on_message
功能,您从不检查消息是否来自您自己的bot本身,这会触发该功能的重复。要避免这种情况,请在此函数开头添加
if msg.author==bot.user:return
。其次,
role=discord.utils.get(msg.guild.roles,name=“Muted”)
由于某种原因无法找到
Muted
角色,这就是为什么它将
role
的值设置为
None
。这就是为什么当您调用
wait msg.author.add_roles(role)
时,您基本上是在执行
wait msg.author.add_roles(None)
。最后,您的缩进是错误的,因为您正在等待
文件中每个坏字的
bot.process\u comands(msg)
。这是函数的固定代码

@bot.event
异步def on_消息(消息):
如果msg.author==bot.user:
回来
对于文件中的坏字:
如果msg.content.lower()中有坏字:
role=discord.utils.get(msg.guild.roles,name=“Muted”)
wait msg.author.add_角色(角色)
等待消息。删除()
wait msg.channel.send(f'{msg.author.antify}!那是个坏词!你被静音了!')
等待bot.process_命令(msg)

你收到错误消息了吗?嗨-这个问题可以通过解释更多关于“我弄坏了它”的含义来改进-你有成功和“我弄坏了它”的输入/输出数据示例吗?用错误消息更新帖子,这也是我要无限期重复的其他命令。这很有魅力!非常感谢!没问题,祝你好运!
await req(guild_id, user_id, role.id, reason=reason)
                             ^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'