【问题标题】:Trying to make discord.py bot say something when its gets mentioned, doesnt respond试图让 discord.py 机器人在被提及时说些什么,但没有回应
【发布时间】:2021-08-03 04:13:30
【问题描述】:

当有人提到机器人时,我希望它回应说:“嘿!我被提及了。我的前缀是 >。你可以输入 >help 来查看我的命令。”我已经写出了代码,但是当提到它时,机器人根本没有响应。当我运行它或提及机器人时,我没有收到任何错误。我怎样才能让它工作?我的代码如下。提前致谢。

@bot.event
async def on_message(message):
  if message.author.id == bot.user.id:
       return
  msg_content = message.content.lower()

  mention = ['@830599839623675925', '@Ultimate Bot']
 
  if any(word in msg_content for word in mention):
    await message.channel.send("Hey! I've been mentioned. My prefix is `>`. You can type `>help` to see my commands.")
  else:
    await bot.process_commands(message)

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    您可以使用mentioned_in() 方法。

    所以在这种情况下是这样的;

    @bot.event
    async def on_message(message):
      if message.author.id == bot.user.id: return
     
      if bot.user.mentioned_in(message):
        await message.channel.send("Hey! I've been mentioned.")
      
      await bot.process_commands(message)
    

    注意事项:

    • 在诸如mention 变量中的值中进行硬编码是不好的做法。它使维护您的代码变得更加困难,并且当您的项目变得更大时,您可能会质疑这些看似随机的字符串所指的目的是什么。例如,如果您要更改机器人的名称,或者将您的代码转移到一个新的机器人,那么遍历您的整个代码库并挑选并更改这些值将远非理想。

    • 我不知道您的应用程序的其余部分,但您可能不希望 process_commands() 出现在 else 语句中。例如,如果用户在消息中提到了机器人,但正在使用命令,则该命令将被阻止,因为您没有触发 process_commands()

    希望这能回答你的问题

    【讨论】:

      【解决方案2】:

      您可以改为检查 bot.user 是否在消息提及中。

      您还可以检查是否使用了机器人显示名称。

      if bot.user in message.mentions or (message.guild and message.guild.me in message.mentions):
          print("bot was mentioned")
      elif message.guild and message.guild.me.display_name in message.content:
          print("bot name was used")
      

      【讨论】:

        猜你喜欢
        • 2021-08-02
        • 1970-01-01
        • 2021-03-29
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 2020-09-01
        • 2021-04-02
        • 2021-08-18
        相关资源
        最近更新 更多