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

如何让Discord Bot响应特定用户消息?discord.py代码故障排查

问题修复方案

代码存在的核心问题

  • on_message事件参数错误:该事件仅接收一个message参数,你错误地写了ctx, message,混淆了命令上下文(ctx)和消息事件的参数逻辑
  • 错误覆盖message对象:你执行message = ctx.content.lower(),把原本的消息对象替换成了字符串,导致后续message.author.id调用失败
  • 缺少消息内容权限:默认的Intents.default()不包含读取消息内容的权限,Bot无法接收消息触发逻辑
  • 未排除机器人自身消息:若不过滤Bot自己发送的消息,会导致无限循环回复

修正后的代码

import discord

# 开启必要的意图,添加消息内容读取权限
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    # 排除机器人自身消息,避免循环回复
    if message.author == client.user:
        return
    
    # 匹配目标用户ID并发送预设语句
    if message.author.id == INSERT_ID:  # 替换为你的目标用户ID
        await message.channel.send(INSERT_PHRASE)  # 替换为你的预设回复内容

client.run(INSERT_TOKEN)  # 替换为你的Bot令牌

关键修改说明

  1. 初始化Intents时手动开启message_content,确保Bot能正常读取消息内容
  2. 修正on_message的参数为标准的message对象,使用正确的属性调用逻辑
  3. 添加机器人自消息过滤,避免触发无限循环
  4. 移除错误的变量覆盖操作,直接通过message.author.id判断目标用户

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:07:09