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

discord.py中.strength命令触发‘无法发送空消息’错误求助

Discord Bot .strength命令空消息错误修复方案

问题描述

原本能正常返回随机百分比的.strength命令,整合到已有Discord Bot主脚本后,终端显示Bot成功登录并接收到.strength命令,但触发错误:

400 Bad Request (error code: 50006): Cannot send an empty message

错误原因

  1. 同时初始化了commands.Bot和discord.Client两个实例,两者功能重叠且冲突——Bot是Client的子类,无需同时使用
  2. .strength命令绑定在未启动的bot实例上,实际运行的是client实例,导致命令无法被识别,反而被on_message事件捕获,传入send_message函数后responses.get_response返回空值,触发空消息错误
  3. strength命令内部错误调用了bot.run(""),无有效token且会引发重复登录逻辑

修复步骤

  • 移除多余的discord.Client实例,仅使用commands.Bot
  • 将原client的事件处理器绑定到bot实例
  • 在on_message事件中先调用await bot.process_commands(message),确保命令优先被处理
  • 删除strength命令内的bot.run(""),统一在脚本末尾用有效token启动Bot

修复后完整代码

import discord
from discord.ext import commands 
import responses
import random


async def send_message(message, user_message):
    try:
        response = responses.get_response(user_message)
        if response:  # 确保响应非空再发送
            await message.channel.send(response)
    except Exception as e:
        print(e)


def run_discord_bot():
    TOKEN = '你的Bot Token'
    intents = discord.Intents.all()
    intents.message_content = True
    # 只初始化一个Bot实例
    bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)

    @bot.event
    async def on_ready():
        print(f'{bot.user} is now running!')

    @bot.event
    async def on_message(message):
        if message.author == bot.user:
            return
        
        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)

        print(f'{username} said: "{user_message}" ({channel})')

        # 先让Bot处理命令,避免命令被普通消息逻辑拦截
        await bot.process_commands(message)

        # 处理非命令消息
        if not user_message.startswith('.'):  # 排除Bot命令前缀的消息
            if user_message.startswith('?'):
                user_message = user_message[1:]
            await send_message(message, user_message)

    @bot.command()
    async def strength(ctx):
        await ctx.send(f"Your strength is at {random.randint(1, 99)} %")

    bot.run(TOKEN)

run_discord_bot()

额外优化说明

  • 用random.randint(1,99)替代random.choice(range(1,100)),实现相同功能且更简洁
  • 在send_message中增加非空判断,避免因responses.get_response返回空值触发错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:57:38