discord.py技术问询:如何用斜杠命令回复消息及实现临时响应
实现Discord机器人翻译功能方案
1. 斜杠命令实现(支持回复消息+临时响应)
利用Discord.py的app_commands模块实现斜杠命令,天然支持ephemeral临时响应,同时支持选择目标消息进行翻译:
import discord from discord import app_commands from discord.ext import commands # 示例翻译库,可替换为其他实现(如deep-translator) from googletrans import Translator translator = Translator() bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.tree.command(name="translate", description="回复消息进行翻译,结果仅你可见") async def translate(interaction: discord.Interaction, target_message: discord.Message): try: # 执行翻译(这里目标语言设为中文,可按需修改) result = translator.translate(target_message.content, dest="zh-cn") reply_content = f"**原内容**:\n{target_message.content}\n\n**翻译结果**:\n{result.text}" except Exception as e: reply_content = f"翻译失败:{str(e)}" # 发送临时响应,仅命令发起者可见 await interaction.response.send_message(reply_content, ephemeral=True) # 同步命令到Discord(测试时可指定服务器ID快速同步) @bot.event async def on_ready(): # 全局同步(生效慢):await bot.tree.sync() # 指定服务器同步(立即生效): # await bot.tree.sync(guild=discord.Object(id=你的服务器ID)) await bot.tree.sync() print(f"机器人已登录:{bot.user}") bot.run("你的机器人TOKEN")
说明
- 命令定义中的
target_message: discord.Message参数会让Discord客户端提供消息选择器,用户可直接选择要翻译的消息(包括回复操作选中的消息)。 ephemeral=True确保响应仅发起命令的用户可见,符合临时模式要求。
2. 前缀命令实现“临时消息”效果
前缀命令(@commands.command())不支持原生ephemeral模式,可通过发送私信模拟“仅用户可见”的效果:
@bot.command(name="t") async def translate_prefix(ctx: commands.Context, *, content: str=None): # 优先获取回复的消息内容 if ctx.message.reference and ctx.message.reference.resolved: content = ctx.message.reference.resolved.content if not content: await ctx.send("请提供翻译内容,或回复一条消息", delete_after=5) return try: result = translator.translate(content, dest="zh-cn") reply_content = f"**原内容**:\n{content}\n\n**翻译结果**:\n{result.text}" # 发送私信给用户,实现仅可见效果 await ctx.author.send(reply_content) await ctx.send("翻译结果已发送至你的私信", delete_after=3) except Exception as e: await ctx.author.send(f"翻译失败:{str(e)}")
说明
- 通过私信发送翻译结果,确保内容仅用户可见;频道内的提示消息会自动删除,避免干扰公共频道。
- 支持回复消息触发翻译,无需手动输入内容。
关键注意事项
- 确保机器人拥有读取消息、发送消息、发送私信的权限。
- 翻译库可按需替换:
googletrans适合快速测试,但存在访问限制;生产环境建议使用deep-translator或官方翻译API(如谷歌翻译API、百度翻译API)。 - 斜杠命令全局同步需约1小时生效,测试阶段建议指定服务器ID同步以快速验证功能。
内容的提问来源于stack exchange,提问作者Lursy7
相关产品推荐
相关产品推荐

