Discord机器人无限发送消息问题求助(附代码)
Discord机器人无限发送GIF问题修复
问题根源
- 条件判断逻辑错误:原代码的
if message.content == "Lmao" or "Lol" or "lmao" or "lol" and message.author.id != bot_id:存在两个致命问题:or连接的独立字符串(如"Lol")本身是真值,导致条件永远成立,无论用户输入什么都会触发回复- 逻辑运算符优先级混乱,
and比or优先级高,实际判断逻辑完全不符合预期
- 未排除机器人自身消息:机器人发送GIF后会触发自身的
on_message事件,进而重复发送,形成无限循环 - bot_id变量未定义:代码中使用了未赋值的
bot_id,运行时会直接报错 - 匹配方式不符合需求:原代码用
==判断消息完全等于关键词,但需求是消息包含笑料类语句
修正后的代码
import os import discord import random from discord.ext import commands import keep_alive Bot_Token = os.environ['Bot_Token'] bot = discord.Client() @bot.event async def on_ready(): guild_count = 0 for guild in bot.guilds: print(f"- {guild.id} (name: {guild.name})") guild_count += 1 print(f"AGOP_Bot is in {guild_count} guilds.") @bot.event async def on_message(message): # 跳过机器人自身发送的消息,避免无限循环 if message.author == bot.user: return if message.content == "AGOP~hello": await message.channel.send("https://c.tenor.com/tTXwGpHrqUcAAAAC/summoned.gif") # 检查消息是否包含任意笑料关键词 funny_keywords = {"Lmao", "Lol", "lmao", "lol"} if any(keyword in message.content for keyword in funny_keywords): response_funny = [ "https://c.tenor.com/mUAgLfICUC0AAAAC/i-didnt-get-the-joke-abish-mathew.gif", "https://c.tenor.com/zdoxFdx2wZQAAAAd/not-funny-joke.gif", "https://i.pinimg.com/originals/f5/53/97/f55397a7de1c82b37d6d62e655a0e915.gif", "https://jutsume.com/images2/2022/04/16/is-this-some-peasant-joke-meme.png", "https://c.tenor.com/FnASqUdvJH4AAAAC/whats-so-funny-john.gif" ] await message.channel.send(random.choice(response_funny)) bot.run(Bot_Token)
关键修正点
- 新增
if message.author == bot.user: return,直接过滤机器人自身消息,彻底解决无限循环问题 - 用集合存储关键词,通过
any()函数判断消息是否包含任意目标关键词,符合需求逻辑 - 移除未定义的
bot_id,改用message.author == bot.user更直观可靠 - 调整代码格式,提升可读性
内容的提问来源于stack exchange,提问作者destructer77
相关产品推荐
相关产品推荐

