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

discord.py单词学习机器人自触发、指令失效及代码优化问题

Discord.py 单词学习机器人问题修复方案

1. 避免机器人自身触发反应监听

在反应的check校验函数中新增机器人身份过滤,排除所有机器人账号触发的反应事件:

async def check(reaction, user):
    # 新增 not user.bot 过滤机器人触发的反应
    return user == message.author and str(reaction.emoji) == '➡️' and not user.bot

2. 修复指令失效问题

原有代码将整个答题流程直接写在on_message主线程中,wait_for会阻塞事件循环,导致后续消息无法被处理。需要将答题逻辑封装为独立异步函数,通过asyncio.create_task丢入后台执行,不阻塞on_message的正常流程。

3. 精简多单词适配逻辑

将原有单词列表替换为单词-翻译映射字典,不需要逐单词写判断逻辑,新增单词时仅需在字典中新增键值对即可:

# 单词映射表,新增单词直接加键值对即可
VOCAB_DICT = {
    "suburb": "Vorort",
    "timer": "Timer",
}

随机抽题时直接获取单词和对应翻译:

random_word, correct_answer = random.choice(list(VOCAB_DICT.items()))

完整修改后代码

import asyncio
import random
import discord
from discord.ext import commands

# 注意要开启消息内容和成员相关意图
client = commands.Bot(command_prefix='-', intents=discord.Intents.all())

# 全局单词映射表,后续新增100+单词仅需修改这里即可
VOCAB_DICT = {
    "suburb": "Vorort",
    "timer": "Timer",
}

# 独立答题逻辑,后台运行不阻塞主事件循环
async def run_quiz(channel, author):
    # 随机抽取单词和对应答案
    random_word, correct_answer = random.choice(list(VOCAB_DICT.items()))
    await channel.send(random_word)

    # 监听用户回答
    def check_msg(m):
        return m.author == author and m.channel == channel
    
    msg = await client.wait_for('message', check=check_msg)

    if msg.content.strip() == correct_answer:
        await channel.send("richtig!")
    else:
        await channel.send(f"Leider falsch die Lösung wäre **{correct_answer}** gewesen")
    await msg.add_reaction("➡️")

    # 监听下一题触发反应
    def check_reaction(reaction, user):
        return user == author and str(reaction.emoji) == '➡️' and not user.bot

    await client.wait_for('reaction_add', check=check_reaction)
    # 触发下一题
    await run_quiz(channel, author)

@client.event
async def on_message(message):
    # 先过滤机器人自己的消息,避免额外逻辑执行
    if message.author.bot:
        return

    if message.content.startswith('-vokabeln'):
        # 创建后台任务执行答题,不阻塞主流程处理后续消息
        asyncio.create_task(run_quiz(message.channel, message.author))

    await client.process_commands(message)

client.run("你的机器人TOKEN")

内容的提问来源于stack exchange,提问作者QWERTY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:57:03