You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人无限发送消息问题求助(附代码)

Discord机器人无限发送GIF问题修复

问题根源

  1. 条件判断逻辑错误:原代码的if message.content == "Lmao" or "Lol" or "lmao" or "lol" and message.author.id != bot_id:存在两个致命问题:
    • or连接的独立字符串(如"Lol")本身是真值,导致条件永远成立,无论用户输入什么都会触发回复
    • 逻辑运算符优先级混乱,and比or优先级高,实际判断逻辑完全不符合预期
  2. 未排除机器人自身消息:机器人发送GIF后会触发自身的on_message事件,进而重复发送,形成无限循环
  3. bot_id变量未定义:代码中使用了未赋值的bot_id,运行时会直接报错
  4. 匹配方式不符合需求:原代码用==判断消息完全等于关键词,但需求是消息包含笑料类语句

修正后的代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:03:22