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

使用Pycord开发的Discord Bot无法响应命令求助

Discord Bot !ping命令无响应问题排查与修复

问题描述

我正在开发一款Discord Bot,希望实现简单的!ping命令,让Bot在用户输入该命令时回复“pong!”,但执行命令后无任何响应,尝试其他命令也会报错。我是Python新手,恳请帮忙排查代码问题并给出修复方案。

原代码:

import discord
import os
from discord.ext import commands
from discord.ext.commands import Bot

case_insensitive=True

client = discord.Client()
bot = commands.Bot(
  command_prefix="!",
  intents=discord.Intents(members=True, messages=True, guilds=True)
)

@client.event
async def on_ready():
    print('logged in as {0.user}!'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
      
@bot.command(name="ping", description= "Find out!")
async def ping(ctx):
  await ctx.send("Pong!")

client.run(os.getenv('TOKEN'))

问题分析

  1. 重复初始化客户端实例:同时创建了discord.Client()和commands.Bot()两个独立实例,commands.Bot本身是discord.Client的子类,自带客户端功能,无需重复创建。
  2. 命令与启动实例不匹配:命令注册在bot实例上,但最终用client.run()启动的是普通客户端,导致命令永远不会被触发。
  3. 消息事件拦截且未处理命令:绑定在client上的on_message事件会拦截消息,但没有调用命令处理逻辑,即使启动正确实例,命令也无法生效。
  4. 未启用大小写不敏感配置:定义的case_insensitive=True变量未传入commands.Bot,配置未生效。

修复方案

修复后的代码

import discord
import os
from discord.ext import commands

# 仅初始化一个Bot实例,整合客户端与命令功能
bot = commands.Bot(
    command_prefix="!",
    case_insensitive=True,  # 启用命令大小写不敏感
    intents=discord.Intents.default()  # 使用默认意图,需在Discord后台开启对应权限
)

# 绑定Bot实例的就绪事件
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}!')

# 自定义消息事件时,必须调用process_commands让Bot处理命令
@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    await bot.process_commands(message)

# 注册ping命令到Bot实例
@bot.command(name="ping", description="Find out!")
async def ping(ctx):
    await ctx.send("Pong!")

# 用Bot实例启动服务
bot.run(os.getenv('TOKEN'))

额外注意事项

  • 前往Discord开发者门户的Bot页面,开启Message Content Intent权限,否则Bot无法读取消息内容,命令无法触发。
  • 若无需自定义on_message逻辑,可直接删除该事件,commands.Bot会自动处理命令请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:05:24