Python编写Discord Bot无法发送消息问题求助
Discord Bot无法发送消息的问题修复
你的代码存在两处关键问题,导致Bot无法响应消息:
on_message函数缺少@client.event装饰器,Discord客户端无法识别这是消息事件的处理函数,自然不会触发它。client.send_message是discord.py旧版本的写法,新版已弃用该API。
另外补充一个必要的优化:添加判断避免Bot响应自己发送的消息,防止无限循环。
修复后的完整代码
import os import discord from dotenv import load_dotenv load_dotenv() TOKEN = 'token' client = discord.Client(intents=discord.Intents.all()) @client.event async def on_ready(): print(f'{client.user} has connected to Discord!') @client.event # 新增事件装饰器 async def on_message(message): # 忽略Bot自身发送的消息 if message.author == client.user: return channel = message.channel content = message.content if content == "hello": await channel.send("rude response") # 改用新版消息发送方法 client.run(TOKEN)
额外注意事项
如果使用的是discord.py v2.x及以上版本,还需要登录Discord开发者门户,在你的Bot页面开启消息内容意图(Message Content Intent),否则Bot无法读取用户发送的消息内容。
内容的提问来源于stack exchange,提问作者kubusza
相关产品推荐
相关产品推荐

