discord.py bot重复消息
嗨,我正在尝试制作一个discord.py机器人,这样我就可以拥有一个gif聊天频道,但当有人在该频道中键入消息时,我的机器人就会开始重复他的消息,如果你知道,请帮助 我的代码:discord.py bot重复消息,discord,discord.py,Discord,Discord.py,嗨,我正在尝试制作一个discord.py机器人,这样我就可以拥有一个gif聊天频道,但当有人在该频道中键入消息时,我的机器人就会开始重复他的消息,如果你知道,请帮助 我的代码: @client.event async def on_message(message): with open("gif_chater.json", "r+") as file: data=json.load(file) if str(mes
@client.event
async def on_message(message):
with open("gif_chater.json", "r+") as file:
data=json.load(file)
if str(message.channel.id) in data:
if message.content.startswith("https://tenor.com/"):
print("wOw")
if not message.content.startswith("https://tenor.com/") and not message.author.id == "760083241133932544":
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
exit
事件
问题在于,bot不断地对自身做出响应,这是因为on_message
事件不仅在用户发送消息时触发,而且在bot发送消息时也会触发。因此,一旦它告诉用户他们必须只发布主题GIF,它就会对自己的消息做出反应,进入无限循环,发布和删除响应
阻止bot对自身做出响应
要防止bot响应其自己的消息,应在事件开始时添加检查:
还有,最后的ID检查
代码决定发送消息之前的最后一个条件是检查messenger的ID(而不是message.author.ID==“760083241133932544”
)。我不知道这是否是为了避免删除你或机器人的消息,但不管怎样,检查本身被窃听。返回一个整数,然后与字符串进行比较,由于类型冲突,将始终返回False
要修复此问题,请通过删除引号将ID更改为整数:not message.author.ID==760083241133932544
。同样,您应该使用notequals操作符=
而不是而不是以提高可读性:message.author.id!=760083241133932544
此外,由于您已经检查了邮件是否以网站链接开头,因此您可以使用elif
语句而不是重新检查条件,因为else/elif
保证先前的条件为假(即邮件不是以网站链接开头):
修复组合
通过这些新的更改,您的函数可以如下所示:
@client.event
async def on_message(message):
# Don't respond to the bot's own messages
if message.author == client.user:
return
with open("gif_chater.json") as file:
data = json.load(file)
if str(message.channel.id) in data:
if message.content.startswith("https://tenor.com/"):
print("wOw")
elif message.author.id != 760083241133932544:
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
重复是什么意思?它在用户发送消息时工作。
if message.content.startswith("https://tenor.com/"):
print("wOw")
elif message.author.id != 760083241133932544:
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
@client.event
async def on_message(message):
# Don't respond to the bot's own messages
if message.author == client.user:
return
with open("gif_chater.json") as file:
data = json.load(file)
if str(message.channel.id) in data:
if message.content.startswith("https://tenor.com/"):
print("wOw")
elif message.author.id != 760083241133932544:
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()