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

Discord.py 实现简单计算器命令无响应问题求助

问题排查及修复方案
  • 问题1:命令装饰器写法错误

discord.py的命令注册装饰器@bot.command必须带括号才能完成正确的装饰逻辑,你当前漏写了(),导致calc命令根本没有被注册到机器人的命令列表中,自然无法通过前缀触发。

  • 问题2:实例变量混用

代码中同时出现了bot和client两个实例变量,装饰器用的是bot,但消息等待、判断机器人自身账号用的是client,如果二者是不同实例会直接导致逻辑异常,需要统一实例变量名。

  • 问题3:消息意图未开启(潜在必现问题)

目前Discord API要求机器人必须显式开启message_content意图才能读取普通消息的内容,否则无法识别前缀命令:

  1. 先前往Discord开发者后台的机器人设置页,开启Message Content Intent开关
  2. 代码初始化机器人的时候需要显式声明启用该意图

以下是修复后的完整代码:

import discord
from discord.ext import commands

# 声明消息意图
intents = discord.Intents.default()
intents.message_content = True
# 统一使用bot实例,不要混用client变量
bot = commands.Bot(command_prefix='_', intents=intents)

# 补全装饰器的括号
@bot.command()
async def calc(ctx):
    def check(m):
        # 额外增加消息发送者判断,避免其他用户的消息干扰当前计算流程
        return len(m.content) >= 1 and m.author == ctx.author and m.author != bot.user

    await ctx.send("Number 1: ")
    number_1 = await bot.wait_for("message", check=check)
    await ctx.send("Operator: ")
    operator = await bot.wait_for("message", check=check)
    await ctx.send("Number 2: ")
    number_2 = await bot.wait_for("message", check=check)
    try:
        number_1 = float(number_1.content)
        operator = operator.content
        number_2 = float(number_2.content)
    except:
        await ctx.send("Invalid input")
        return
    if operator == "+":
        output = number_1 + number_2
    elif operator == "-":
        output = number_1 - number_2
    elif operator == "/":
        output = number_1 / number_2
    elif operator == "*":
        output = number_1 * number_2
    else:
        await ctx.send("invalid input")
        return
    await ctx.send("Answer: " + str(output))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:27:02