Discord.py机器人命令无响应:'Client'类无'send_message'属性错误
解决Discord机器人的AttributeError问题:'Client'对象无'send_message'属性
你在开发Discord机器人时遇到的这个属性错误,我帮你拆解清楚问题根源,再给出具体的修复方案。
问题核心分析
从日志和代码来看,报错的关键原因有两个:
- discord.py版本迭代带来的方法变更:在discord.py v1.0及以后的版本中,旧的
send_message方法已经被移除,官方改用了更直观的频道对象send()方法。 - 错误创建新的Client实例:你代码里写了
await discord.Client().send_message(...),这相当于新建了一个未登录的空Client对象,完全没必要——你已经初始化了client实例,直接用现有对象或消息自带的频道对象操作即可。
另外还有个小细节:你用了dex.format(author),但author变量并没有定义;而且dex是readlines()返回的字符串列表,直接用format会报错,需要先把列表拼接成完整字符串。
修复步骤
1. 替换发送消息的核心代码
把出错的那行代码:
await discord.Client().send_message(message.channel, dex.format(author))
替换成:
# 拼接列表为字符串,同时@触发命令的用户 await message.channel.send(f"{message.author.mention}\n{''.join(dex)}")
这行代码既修复了发送方法的问题,又正确处理了文件读取的列表内容,还能@提问的用户提升交互性。
2. 完整优化后的代码
我帮你补上了文件存在判断、编码处理等细节,避免机器人因异常情况崩溃:
import discord import sys import os TOKEN = '你的机器人TOKEN' client = discord.Client() @client.event async def on_message(message): # 避免机器人回复自身 if message.author == client.user: return if message.content.startswith('bey!'): message_real = message.content.split("!") bey_name = message_real[1].strip() # 去除输入前后的空格 where = bey_name + ".txt" # 增加文件存在判断,防止找不到文件报错 if os.path.exists(where): with open(where,"r", encoding="utf-8") as f: dex = f.readlines() print(dex) await message.channel.send(f"{message.author.mention}\n{''.join(dex)}") else: await message.channel.send(f"{message.author.mention} 找不到对应陀螺的信息文件哦!") @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') client.run(TOKEN)
3. 确认discord.py版本
如果你的discord.py版本过旧,可能还会有其他兼容问题,建议升级到最新稳定版:
pip install --upgrade discord.py
内容的提问来源于stack exchange,提问作者Waaberi Ibrahim
相关产品推荐
相关产品推荐

