【问题标题】:How to have the bot send a message every time a user with a specific role speaks in any channel | Discord.py每次具有特定角色的用户在任何频道发言时,如何让机器人发送消息 |不和谐.py
【发布时间】:2021-05-22 03:18:11
【问题描述】:

我正试图让机器人在每次有欺负角色的人说话时发送一条消息。我还想让它在该响应消息中提及用户,但这当然是可选的。我对 discord.py 有点陌生,但仍然知道很多事情。

这是我的代码:

@client.event
@commands.has_role('Bullied')
async def on_message(ctx, message):
  if message.content != "":
    if y == 0 or y2 == 0 or y3 == 0:
      await ctx.send("hi")

这是每次有人在服务器上讲话时我收到的错误消息:

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)
TypeError: on_message() missing 1 required positional argument: 'message'

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    由于这是一个使用@commands.has_role() 的事件,因此将不起作用。您可以检查特定角色是否在成员角色中。这是一个例子。

    @bot.event
    async def on_message(message):
        if message.author.bot:  # skip bot messages
            return
    
        role = discord.utils.get(message.guild.roles, name='Bullied') # get the role using name
        member = message.guild.get_member(message.author.id) # get the member in the guild
        if role in member.roles:
            #code here
            channel = bot.get_channel(123) # wanted channel to notify
            await channel.send(f'Hey there {message.author.name}')
    

    【讨论】:

    • guild = bot.get_guild(message.guild.id) 确实是不必要的一行,因为guild = message.guild 足以获取discord.Guild 对象
    【解决方案2】:

    正如您的错误所说,on_message 仅接受 message 作为位置参数,您为其提供了两个,即 messagectx

    这里ctx 不是context,而是message,然后您提供了一个额外的参数message,它不知道[因为ctx 充当discord.Message 对象]

    @client.event
    @commands.has_role('Bullied')
    async def on_message(message):
      if message.author.bot:
           return
      if message.content != "":
        if y == 0 or y2 == 0 or y3 == 0: #what is this? I am not sure what y, y2, and y3 are (if not defined, would raise UnboundLocalError, local variable 'y' referenced before assignment) 
          await message.channel.send(f"{message.author.mention} hi")
    

    【讨论】:

    • 这行得通,尽管 @commands.has_role('Bullied') 没有按预期工作。它似乎忽略了用户是否有角色,你会碰巧有一个修复吗?
    • 角色名称需要与您输入的名称完全相同(区分大小写)否则将不起作用
    • commands.has_role 仅适用于命令而非事件
    • 啊啊啊完全忘记了,没错
    猜你喜欢
    • 2021-06-17
    • 2021-01-04
    • 2021-10-09
    • 2021-08-14
    • 2021-06-22
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多