首页 > 解决方案 > 当从电话应用程序中提及时,discord.py bot 没有回答

问题描述

我最近和朋友一起为小型服务器制作了一个不和谐机器人。它旨在根据用户的要求进行回答。但问题是,当有人从手机应用程序中提及机器人时,机器人只是没有响应。可能是什么问题呢?代码:

import discord
from discord.ext    import commands
from discord.ext.commands   import Bot
import asyncio

bot = commands.Bot(command_prefix = '=')
reaction = ""

@bot.event
async def on_ready():
    print('Bot is ready.')

@bot.listen()
async def on_message(message): 
    if str(message.author) in ["USER#ID"]:
        await message.add_reaction(emoji=reaction)

@bot.listen()
async def on_message(message):
    mention = f'<@!{BOT-DEV-ID}>'
    if mention in message.content:
        if str(message.author) in ["user1#id"]:
            await message.channel.send("Answer1")
        else:
            await message.channel.send("Answer2")

bot.run("TOKEN")

标签: pythondiscord.py

解决方案


要记住的一件事是,如果您有多个同名的函数,它只会调用最后一个函数。在您的情况下,您有两个on_message功能。监听器的使用是对的,你只需要告诉它要监听什么,然后调用其他的函数。正如您现在的代码一样,它永远不会添加“”,因为该函数是首先定义的,并在 bot 到达第二个on_message函数时被覆盖。

message对象包含很多我们可以使用的信息。链接到文档

message.mentions给出消息中提到的所有用户的列表。


@bot.listen("on_message")   # Call the function something else, but make it listen to "on_message" events
async def function1(message): 
    reaction = ""
    if str(message.author.id) in ["user_id"]:
        await message.add_reaction(emoji=reaction)


@bot.listen("on_message")
async def function2(message):
    if bot.user in message.mentions: # Checks if bot is in list of mentioned users
        if str(message.author.id) in ["user_id"]: # message.author != message.author.id
            await message.channel.send("Answer1")
        else:
            await message.channel.send("Answer2")

如果您不希望机器人在提到多个用户时做出反应,您可以先添加:

if len(message.mentions)==1:

调试期间的一个很好的技巧是使用print()这样你就可以在终端中看到你的机器人实际在使用什么。如果你print(message.author)username#discriminator看到user_id


推荐阅读