Python开发Discord机器人:$hello命令无法触发问题求助
Discord机器人$hello命令无法触发的解决方案
问题描述
使用Python开发Discord机器人时,$hello命令无法触发对应逻辑,即使发送$hello也不会执行消息回复和打印操作。相关代码片段如下:
if message.content.startswith("$hello"): # <<<<<< 此命令出现问题! print("Command detected: $hello") await message.channel.send('Hello there! I am a bot. Thats it.')
完整代码:
import discord import os client = discord.Client(intents=discord.Intents(messages=True)) @client.event async def on_ready(): print('Logged in as {0.user}'.format(client)) @client.event async def on_message(message): print("Message detected.") if message.author == client.user: print("Returning...") return print("User message confirmed to not be a bot.") if message.content.startswith("$hello"): #<<< 此处出现问题! print("Command detected: $hello") await message.channel.send('Hello there! I am a bot. Thats it.') # 机器人运行命令已省略
问题原因
Discord.py v2.0及以上版本中,消息内容需要单独开启权限,仅设置messages=True无法让机器人读取消息的具体内容,导致message.content为空或无法获取,自然无法匹配startswith("$hello")的判断条件。
解决步骤
修改代码中的Intents配置
将客户端初始化代码替换为:intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents)或合并为一行写法:
client = discord.Client(intents=discord.Intents(default=True, message_content=True))在Discord开发者后台开启消息内容意图
登录Discord开发者门户,找到你的机器人应用,进入「Bot」页面,在「Privileged Gateway Intents」区域,开启「Message Content Intent」选项。重启机器人并测试
修改代码后重启机器人,发送$hello即可触发对应逻辑。
验证说明
修改完成后,机器人将能正常读取消息内容,message.content.startswith("$hello")的判断会生效,控制台会打印Command detected: $hello,同时在聊天频道回复指定消息。
内容的提问来源于stack exchange,提问作者donut28
相关产品推荐
相关产品推荐

