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

Discord维基百科查询机器人在线无响应,请求代码排查

Discord维基百科机器人无响应的问题排查与修复

核心错误点

  • 死循环阻塞事件处理:on_message里的while True是致命问题。Discord.py的事件处理是单线程的,这个死循环会让机器人彻底卡在当前事件里,既无法处理这条消息,也没法响应后续任何指令,直接导致无响应。
  • 过早调用频道获取方法:channel = client.get_channel(#channel id)在客户端未连接Discord时执行,会返回None,而且这段代码后续也没用到,属于无效错误代码。
  • 搜索词格式错误:user_choice = str(parts[1:])把列表转成字符串会生成类似['Python']的带特殊符号的内容,维基百科根本识别不了这个搜索词,应该用' '.join(parts[1:])拼接成正常的关键词字符串。
  • 异常处理不全:只捕获了wikipedia.PageError,但维基百科还会抛出歧义页面错误、网络错误等,这些未处理的异常会让机器人静默失败,没有任何反馈。
  • 未过滤自身消息:如果机器人自己的消息触发了指令,会陷入无限回复循环,必须先判断if message.author == client.user: return来跳过自身消息。

修正后的代码

import discord
import wikipedia

client = discord.Client()

@client.event
async def on_ready():
    print("Ready")

@client.event
async def on_message(message):
    # 忽略机器人自己发送的消息
    if message.author == client.user:
        return
    
    try:
        # 这里建议用频道ID判断更可靠,比如替换成 if message.channel.id == 你的频道ID:
        if str(message.channel) == "genel" and message.content.startswith('!info'):
            parts = message.content.split()
            # 检查用户是否输入了关键词
            if len(parts) < 2:
                await message.channel.send("请输入查询词条,格式:!info 词条名称")
                return
            
            user_choice = ' '.join(parts[1:])
            summary = wikipedia.summary(user_choice, sentences=3)
            await message.channel.send(summary)
            print("查询成功")
    except wikipedia.PageError:
        print("词条不存在")
        await message.channel.send("该词条不存在,请尝试其他关键词。")
    except wikipedia.DisambiguationError as e:
        print("歧义词条")
        # 显示前5个歧义选项,避免消息过长
        await message.channel.send(f"该词条有多个结果,请更精确:{e.options[:5]}")
    except Exception as e:
        print(f"未知错误:{e}")
        await message.channel.send("查询时出现未知错误,请稍后再试。")

client.run("你的客户端令牌")

内容的提问来源于stack exchange,提问作者Turkey Once said

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:54:57