Discord机器人DM系统正常但其他命令失效,求代码排查
问题排查:Discord机器人命令失效,仅DM系统正常运行
错误原因
自定义on_message事件时,必须手动调用bot.process_commands(message)才能让命令系统正常工作。你的代码里只在处理dm-system-test频道的特定消息时调用了这个方法,其他场景(比如用户在普通频道发送;info、;quote命令)完全没触发命令处理逻辑,导致这些命令失效。
另外还有两个不影响功能的小问题:
on_ready里的print("{bot.user.name} is up and runing!")应该改为f-string语法print(f"{bot.user.name} is up and running!"),否则无法正确输出机器人名称,同时runing拼写错误应为running。- 命令描述里的
dose是拼写错误,正确应为does。
修复后的完整代码
import discord, os, time, random, string, asyncio, datetime, typing import config from discord.ext import commands from discord import DMChannel intents = discord.Intents.all() bot = commands.Bot(command_prefix=';', intents=intents) @bot.event async def on_ready(): await bot.change_presence(activity=discord.Game('Start with ;info !')) print(f"{bot.user.name} is up and running!") print(f"_________________________________") #Info command @bot.command() async def info(ctx): embed = discord.Embed( colour=discord.Colour.purple(), description="Welcome to Infinity.\n\n**What is Infinity?**\n Infinity is a bot that supports mental health!\n\n**How does it help?**\n Infinity helps by being there to cheer you up, and there will always be a support person there to talk to.\n\n**How does someone talk to you through the bot?**\n The bot uses a DM system where you can DM the bot and it will go to one of our support team members. \n\n **How do I report a bug or someone misusing the bot?**\n You may use our support server to report bugs or users misusing the bot.", title="Hello, I am Infinity!" ) embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1142857962172457102/1142891040781635634/Infinity.png") await ctx.reply(embed=embed) #More commands @bot.command() async def quote(ctx): embed = discord.Embed( colour=discord.Colour.purple(), description="You're braver than you believe, and stronger than you seem, and smarter than you think", title="Quote of the Day!" ) embed.set_footer(text="20/08/23") await ctx.reply(embed=embed) #DM System @bot.event async def on_message(message): if message.author == bot.user: return # 处理DM消息转发 if str(message.channel.type) == "private": dm_channel = discord.utils.get(bot.get_all_channels(), name="dm-system-test") await dm_channel.send(f"[{message.author.display_name}] {message.content}") # 处理客服频道回复用户 elif str(message.channel) == "dm-system-test" and message.content.startswith("<"): member_object = message.mentions[0] index = message.content.index(" ") mod_message = message.content[index:] await member_object.send(f"[{message.author.display_name}] {mod_message}") # 关键:无论什么消息,都要处理命令(必须放在所有逻辑之后) await bot.process_commands(message) bot.run(config.TOKEN)
核心修改点
- 将
await bot.process_commands(message)移到on_message事件的最后,确保所有非机器人发送的消息都会触发命令处理。 - 修正了字符串拼接为更简洁的f-string语法。
- 修正了拼写错误(
dose→does、runing→running等)。
内容的提问来源于stack exchange,提问作者Morgan
相关产品推荐
相关产品推荐

