python - 当从电话应用程序中提及时,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")
解决方案
要记住的一件事是,如果您有多个同名的函数,它只会调用最后一个函数。在您的情况下,您有两个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
推荐阅读
- javascript - 具有给定 html 类 id 参数的动态 slideToggle 函数
- neural-network - 强化学习中的神经网络设置和监控
- html - Angular - 使用“setAttribute”动态设置 HTML 属性
- c# - 计算 Combox 值为 x 的 DataGridView 的行数
- python-requests - 使用 python 请求上传二进制文件
- c - 如何通过单个 fork() 调用使子进程保持活动状态?
- c++ - std::regex 对于用户定义的表达式是否安全?
- css - css 伪选择器中 :nth-child(1) 与 :first-child 之间有什么区别 选择一种方法而不是另一种方法有什么优点?
- java - 为什么发布请求会导致禁止错误?
- python - 如何将此代码写入单行命令