繁体   English   中英

每次具有特定角色的用户在任何频道发言时,如何让机器人发送消息 | Discord.py

[英]How to have the bot send a message every time a user with a specific role speaks in any channel | Discord.py

每当有欺负角色的人说话时,我都试图让机器人发送一条消息。 我还想让它在该响应消息中提及用户,但这当然是可选的。 我对 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'

正如您的错误所说, 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()的事件将不起作用。 您可以检查特定角色是否在成员角色中。 这是一个例子。

@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}')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM