Python开发Discord机器人_throw指令带ping用户无响应如何解决
问题原因
- 核心匹配逻辑错误:你使用
message.content == "_throw"做全等匹配,但发送_throw指令时需要附带@用户内容,实际消息内容永远不可能完全等于"_throw",因此该分支从未被触发。 - 潜在运行异常:当前逻辑未校验是否存在被@的用户,若有人仅发送
_throw不ping用户,访问message.mentions[0]会直接抛出索引越界异常。 - 若其他指令也无法触发,额外检查Discord Message Content Intent权限是否开启。
解决方法
- 修改指令匹配规则,改为校验消息开头为
_throw - 增加@用户存在性校验,避免运行异常
- 若使用discord.py v2.x及以上版本,确认已开启Message Content Intent权限并正确配置初始化参数
修正后的完整on_message代码
@client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('_hi'): await message.channel.send(f'Hello, {message.author.mention}!') if message.content.startswith("_throw"): if not message.mentions: await message.channel.send("使用格式:_throw @目标用户") return user = message.mentions[0] await message.channel.send(f"You threw a hamster to {user}!") if message.content.startswith("_userinfo"): user = message.mentions[0] emb14 = discord.Embed( title=f"@{user} info:", colour=discord.Colour.dark_blue() ) emb14.set_image(url=user.avatar_url) emb14.add_field(name=f"Name", value=f"{user}", inline=True) emb14.add_field(name=f"Discord Joined date", value=f"{user.created_at}", inline=False) emb14.add_field(name=f"Server Joined date", value=f"{user.joined_at}", inline=False) emb14.add_field(name="Profile Picture", value=":arrow_down: :arrow_down: ", inline=False) await message.channel.send(embed=emb14)
Intent配置示例(discord.py v2.x+ 必需)
import discord intents = discord.Intents.default() intents.message_content = True # 开启消息内容读取权限 client = discord.Client(intents=intents)
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

