如何在discord.py中实现机器人以临时消息响应/help指令?
解决discord.py机器人发送临时消息(Ephemeral Message)的问题
问题根源
你用的是传统前缀命令(基于commands.Bot和@bot.command()),这种命令模式依赖Discord的普通消息系统,只能拿到Context对象,根本没法获取Interaction——而且临时消息(ephemeral)是Discord**斜杠命令(应用命令)**独有的特性,普通消息命令不支持发送这种仅用户可见的临时消息。
另外你代码里的interaction: discord.Interaction参数完全无效,Discord.py不会给前缀命令自动注入这个对象,所以运行时这个参数要么是None,要么直接导致参数不匹配,最终触发AttributeError。
正确解决方案:改用斜杠命令
要发送临时消息,必须用Discord的应用命令体系(斜杠命令),下面是修正后的完整代码:
import discord from discord.ext import commands from discord import app_commands TOKEN = '你的机器人令牌' intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='/', intents=intents) help_text = 'This is a help text' @bot.event async def on_ready(): print(f"{bot.user} is now up and running.") # 同步斜杠命令到指定服务器(测试用,生效更快) # 替换成你的服务器ID(整数类型) guild = discord.Object(id=123456789012345678) bot.tree.copy_global_to(guild=guild) await bot.tree.sync(guild=guild) # 使用斜杠命令装饰器替代传统命令装饰器 @bot.tree.command(name="help", description="Show help text (only visible to you)") async def help(interaction: discord.Interaction): # 斜杠命令不会在频道显示用户的输入消息,无需purge操作 # 发送临时消息,ephemeral=True 表示仅触发命令的用户可见 await interaction.response.send_message(content=help_text, ephemeral=True) bot.run(TOKEN)
关键说明
- 斜杠命令需要先同步到服务器:代码里的
guild部分是快速同步到指定服务器,适合测试;如果要全局同步,去掉copy_global_to和guild参数,直接await bot.tree.sync()(全局同步可能需要1小时左右生效)。 - 斜杠命令触发时,Discord会自动处理交互界面,不会在频道留下公开的用户命令消息,所以不需要
ctx.channel.purge()。 interaction.response.send_message()是斜杠命令发送响应的标准方式,ephemeral=True是实现临时消息的核心参数。
如果一定要用传统消息命令实现类似效果(注意:这不是原生临时消息,而是私信):
@bot.command() async def help(ctx): await ctx.message.delete() # 删除用户发送的/help消息 await ctx.author.send(help_text) # 给用户发私信
这种方式是给用户发私信,和Discord原生临时消息的体验不同,用户需要打开私信才能看到内容。
内容的提问来源于stack exchange,提问作者ImTheBeemoPlush
相关产品推荐
相关产品推荐

