You need to enable JavaScript to run this app. 使用discord.py开发Discord随机回复机器人遇Client无send_message属性报错
优惠活动
大模型
产品
解决方案
定价
更多

使用discord.py开发Discord随机回复机器人遇Client无send_message属性报错

错误根因

send_message是discord.py 1.x及更早版本的遗留API,2.x版本中该方法已被完全移除,因此会抛出'Client' object has no attribute 'send_message'的属性不存在报错。

现有代码存在的其他问题
  • on_message函数中完成i = random.randint(0,30)赋值后直接衔接elif分支,无对应起始if判断,属于Python语法错误,无法正常运行
  • i == 26分支仅传入消息内容,未指定发送目标频道,即使修复API问题也会触发参数缺失报错
  • 导入commands模块却初始化基础discord.Client()实例,process_commands方法不适用于该实例
  • 未过滤机器人自身发送的消息,触发自动回复后会陷入无限循环
  • 重复编写数十次逻辑完全一致的消息发送代码,冗余度极高
修复方案
  1. 替换已废弃的发送消息API:将所有await client.send_message(message.channel, 消息内容)替换为2.x版本兼容写法await message.channel.send(消息内容)
  2. 初始化Bot实例替代基础客户端,适配命令处理逻辑
  3. 预设回复内容列表,随机抽取发送,删除冗余的多分支判断
  4. 增加机器人自身消息过滤逻辑,避免无限循环
  5. 显式开启discord.py 2.x要求的消息内容意图,否则无法读取消息触发逻辑
可直接运行的修复后代码
import discord
from discord.ext import commands
import random

# 开启必要的权限意图
intents = discord.Intents.default()
intents.message_content = True

# 初始化Bot实例,命令前缀可根据需求调整
bot = commands.Bot(command_prefix='!', intents=intents)

# 存放所有需要随机发送的回复内容,可自行增减条目
REPLY_CONTENT = [
    "随机回复1",
    "随机回复2",
    "随机回复3"
]

@bot.event
async def on_ready():
    print(f"Bot启动完成,账号ID:{bot.user.id}")

@bot.event
async def on_message(message):
    # 跳过机器人自身发送的消息,防止无限循环
    if message.author.bot:
        return
    # 按30%概率随机触发回复,概率值可自行调整
    if random.randint(0, 100) < 30:
        selected_reply = random.choice(REPLY_CONTENT)
        await message.channel.send(selected_reply)
    # 处理Bot内置命令逻辑
    await bot.process_commands(message)

# 替换为你自己的Discord Bot令牌
bot.run('你的Bot令牌')

补充说明:如果需要继续使用旧版send_messageAPI,可执行pip install discord.py==1.7.3安装对应旧版本,但该版本已停止维护,不推荐生产环境使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 00:15:04