discord.py报错TypeError:不支持<class 'discord.interactions.Interaction'>类型注解
问题
我正在开发Discord机器人,希望用户执行/hitokoto斜杠命令时可通过下拉菜单选择所需分类,编写的代码片段如下:
@app_commands.command(name="hitokoto") @app_commands.choices(choices=[ app_commands.Choice(name="動畫", value="a"), app_commands.Choice(name="漫畫", value="b"), app_commands.Choice(name="遊戲", value="c"), app_commands.Choice(name="文學", value="d"), ....... ]) async def hitokoto(self,interaction: discord.Interaction, choices: app_commands.Choice): url = f"https://v1.hitokoto.cn/?c={choices.value}&encode=json" header = {"User-Agent":'Mozilla/5.0'} response = requests.get(url, headers = header) response.raise_for_status() json_hitokoto = response.json() if (choices.value == 'a'): embed=discord.Embed(title="一言 - 動漫分類", description = json_hitokoto["hitokoto"], color=0x05c5eb) embed.add_field(name="上傳者", value=json_hitokoto["creator"] , inline=False) embed.add_field(name="來自", value=json_hitokoto["from"], inline=True) embed.add_field(name="角色", value=json_hitokoto["from_who"], inline=True) await interaction.response.send(embed=embed) elif (choices.value == 'b'): ...... elif (choices.value == 'c'): ...... ...... else: return
运行时出现如下错误:
Traceback (most recent call last): File "c:\Users\huang\Desktop\Project\Python\Discord Bot -Lycoris Recoil\main.py", line 69, in <module> async def hitokoto(self,interaction: discord.Interaction, choices: app_commands.Choice): File "C:\Users\huang\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 2019, in decorator return Command( File "C:\Users\huang\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 685, in __init__ self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__) File "C:\Users\huang\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 393, in _extract_parameters_from_callback param = annotation_to_parameter(resolved, parameter) File "C:\Users\huang\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\transformers.py", line 832, in annotation_to_parameter (inner, default, validate_default) = get_supported_annotation(annotation) File "C:\Users\huang\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\transformers.py", line 791, in get_supported_annotation raise TypeError(f'unsupported type annotation {annotation!r}') TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
修复方案
1. 修正核心错误:参数类型注解
错误根源是**choices参数的类型注解错误**:
- 使用
@app_commands.choices时,函数参数的类型注解需对应Choice选项的value类型(此处所有选项value为字符串,因此注解为str),而非app_commands.Choice类。 - 同时注意
interaction.response.send不是正确方法名,需改为interaction.response.send_message。
2. 修复语法错误:代码缩进
原代码中if块内的embed行未缩进,会触发语法错误,需调整缩进层级匹配if块。
3. 优化冗余代码(可选)
原代码中多个elif块逻辑重复,可通过字典映射分类名称,动态生成Embed标题,减少冗余。
修改后的完整代码示例
import discord from discord import app_commands import requests class HitokotoCog(discord.Cog): def __init__(self, bot: discord.Bot): self.bot = bot @app_commands.command(name="hitokoto") @app_commands.choices(category=[ app_commands.Choice(name="動畫", value="a"), app_commands.Choice(name="漫畫", value="b"), app_commands.Choice(name="遊戲", value="c"), app_commands.Choice(name="文學", value="d"), ]) async def hitokoto(self, interaction: discord.Interaction, category: str): # 映射分类值到中文名称 category_names = { "a": "動漫分類", "b": "漫畫分類", "c": "遊戲分類", "d": "文學分類" } url = f"https://v1.hitokoto.cn/?c={category}&encode=json" headers = {"User-Agent": "Mozilla/5.0"} try: response = requests.get(url, headers=headers) response.raise_for_status() json_hitokoto = response.json() except Exception as e: await interaction.response.send_message(f"获取一言失败:{str(e)}", ephemeral=True) return # 动态生成Embed标题 embed_title = f"一言 - {category_names.get(category, '未知分類')}" embed = discord.Embed(title=embed_title, description=json_hitokoto["hitokoto"], color=0x05c5eb) embed.add_field(name="上傳者", value=json_hitokoto.get("creator", "未知"), inline=False) embed.add_field(name="來自", value=json_hitokoto.get("from", "未知"), inline=True) embed.add_field(name="角色", value=json_hitokoto.get("from_who", "未知"), inline=True) await interaction.response.send_message(embed=embed) # 注册Cog示例 async def setup(bot: discord.Bot): await bot.add_cog(HitokotoCog(bot))
关键说明
- 将参数名从
choices改为category(更语义化,可选),确保@app_commands.choices的参数名与函数参数名一致。 - 使用
json_hitokoto.get()避免KeyError,API返回字段缺失时显示默认值。 - 添加异常处理,捕获请求失败情况,给用户友好提示。
内容的提问来源于stack exchange,提问作者whitebear13579
相关产品推荐
相关产品推荐

