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

Python开发Discord机器人发送$hello指令无响应,求排查解决方法

问题排查与修复方案

核心问题汇总

  • 缩进错误导致事件注册、指令判断逻辑完全不生效
  • 缺少discord.py要求的消息内容权限配置
  • 同步sleep阻塞异步事件循环影响响应

具体问题说明

1. on_message 事件定义位置错误

你将on_message事件的整个定义写在了on_ready函数内部,属于函数局部逻辑,全局事件监听不会注册该回调,机器人收不到消息事件触发。

2. 指令判断逻辑缩进错误

$hello的匹配代码缩进在了if message.author == client.user:的代码块内部,触发该判断后会直接return,后续逻辑永远不会执行。

3. 缺少消息内容权限

discord.py v2.x及以上版本要求必须在Discord开发者后台开启Message Content Intent权限,否则机器人无法读取用户发送的消息明文,无法匹配指令。

4. 同步sleep阻塞事件循环

异步函数中使用同步的time.sleep()会阻塞整个机器人的事件循环,导致所有其他事件无法正常响应,需要替换为异步休眠方法。


修复后代码

import discord
import os
import asyncio

# 开启所需权限
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

@client.event 
async def on_ready():
  print('We have broken into american server farms as {0.user}'.format(client))
  await asyncio.sleep(1)
  print("Accessing private data...")
  await asyncio.sleep(2)
  print("Installing malware...")
  await asyncio.sleep(2)
  print("Extracting stolen files...")
  await asyncio.sleep(2)
  print("Finishing up..")
  await asyncio.sleep(1)
  print("All objectives completed, State Messenger Bot is now online.")

# 移到on_ready外层,全局注册事件
@client.event
async def on_message(message):
  if message.author == client.user:
    return 
  # 修正缩进,放到return判断的外面
  if message.content.startswith('$hello'):
    await message.channel.send('Commander')

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

额外配置检查

  1. 打开Discord开发者平台的机器人管理页,找到「Privileged Gateway Intents」分区,开启Message Content Intent开关
  2. 检查机器人在对应服务器的权限,确保已开启查看频道、发送消息、读取消息历史权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:27:01