You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Discord Passport Cog转换为带可选提及的slash命令?

解决方案:将discord.ext.commands的Passport命令转换为Slash命令

核心修改要点

  • 替换@commands.command()装饰器为@app_commands.command()
  • 使用Optional[discord.Member]定义可选成员参数,默认值设为None
  • 在命令逻辑中,若未指定成员则使用发起交互的用户(interaction.user)
  • 确保命令注册到Discord的命令树(CommandTree)

完整转换示例

假设你原来的Cog代码大致如下:

from discord.ext import commands
import discord

class Passport(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def passport(self, ctx, member: commands.MemberConverter = None):
        target = member or ctx.author
        # 生成嵌入式消息的逻辑(复用原有代码)
        embed = discord.Embed(title=f"{target.display_name}'s Passport", color=target.color)
        embed.add_field(name="ID", value=target.id, inline=False)
        embed.add_field(name="Joined Server", value=target.joined_at.strftime("%Y-%m-%d %H:%M:%S"), inline=False)
        embed.add_field(name="Created Account", value=target.created_at.strftime("%Y-%m-%d %H:%M:%S"), inline=False)
        embed.set_thumbnail(url=target.avatar.url)
        
        await ctx.send(embed=embed)

async def setup(bot):
    await bot.add_cog(Passport(bot))

转换为app_commands的版本:

from discord import app_commands
import discord
from discord.ext import commands
from typing import Optional

class Passport(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="passport", description="展示指定用户的信息护照")
    async def passport_slash(self, interaction: discord.Interaction, member: Optional[discord.Member] = None):
        target = member or interaction.user
        # 复用原有嵌入式消息生成逻辑
        embed = discord.Embed(title=f"{target.display_name}'s Passport", color=target.color)
        embed.add_field(name="用户ID", value=target.id, inline=False)
        embed.add_field(name="加入服务器时间", value=target.joined_at.strftime("%Y-%m-%d %H:%M:%S"), inline=False)
        embed.add_field(name="账号创建时间", value=target.created_at.strftime("%Y-%m-%d %H:%M:%S"), inline=False)
        embed.set_thumbnail(url=target.avatar.url if target.avatar else target.default_avatar.url)
        
        await interaction.response.send_message(embed=embed)

async def setup(bot):
    await bot.add_cog(Passport(bot))
    # 若需要全局同步命令(注意:全局同步可能需要1小时生效,开发阶段建议用guild参数指定测试服务器)
    # await bot.tree.sync()
    # 测试服务器同步示例:
    # test_guild = discord.Object(id=1234567890)
    # await bot.tree.sync(guild=test_guild)

关键注意事项

  • 命令同步:首次部署后需要同步命令到Discord,全局同步生效慢,开发时建议指定测试服务器同步
  • 交互响应:Slash命令必须使用interaction.response.send_message()(或其他响应方法),不能用原来的ctx.send()
  • 成员参数处理:Optional[discord.Member]会自动处理用户提及、ID和用户名搜索,无需手动用MemberConverter
  • 头像容错:新增了对用户无自定义头像时使用默认头像的处理,避免报错

内容的提问来源于stack exchange,提问作者whsqqq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:33:18