使用Pycord开发Timeout命令时遭遇TypeError错误求助
问题解决:Pycord Timeout命令自动补全报错
错误原因
你直接将静态列表list_time传给了autocomplete参数,但Pycord要求该参数必须是可调用的异步函数,用来生成自动补全的选项列表,而非直接传入静态列表,这才触发了TypeError: (300, 600, 900, 1200) is not a callable object错误。
修正后的代码
from datetime import datetime list_time = [300, 600, 900, 1200] # 定义自动补全的异步回调函数 async def time_autocomplete(ctx: discord.AutocompleteContext): # 返回所有时间选项,也可根据用户输入过滤匹配内容 return [str(t) for t in list_time] @commands.slash_command(name="timeout", description="Times out the member that you specify from the server.", guild_ids=[1049465353245306951]) @commands.has_guild_permissions(mute_members=True) async def timeout(self, ctx, member: discord.SlashCommandOptionType.user, time: discord.Option(int, "Select a time", autocomplete=time_autocomplete, required=False), reason: discord.SlashCommandOptionType.string): # 处理可选的time参数,设置默认值 if not time: time = 300 # 默认5分钟(300秒) today = datetime.now().strftime("%Y-%m-%d %H:%M:%S") embed = discord.Embed(title="Successfully Timed Out.", description="Successfully Timed Out the user from the server.", color=discord.Color.green()) embed.add_field(name="Member Timed Out", value=f"{member.mention}", inline=False) embed.add_field(name="Reason", value=f"{reason}", inline=False) embed.add_field(name="Time", value=f"{time} seconds", inline=False) await ctx.respond(embed=embed) embed = discord.Embed(title="Timed Out From Server", description=f"You have been timed out from {ctx.guild.name}", color=discord.Color.red()) embed.add_field(name="Staff Member", value=f"{ctx.author.mention}", inline=False) embed.add_field(name="Reason", value=f"{reason}", inline=False) embed.add_field(name="Time", value=f"{time} seconds", inline=False) embed.add_field(name="Date", value=f"{today}", inline=False) # 尝试给被禁言用户发送通知,处理无法私信的情况 try: await member.send(embed=embed) except discord.Forbidden: pass
关键修改点
- 新增
time_autocomplete异步函数:作为自动补全的回调逻辑,返回转换为字符串的时间选项(Discord自动补全要求返回字符串列表)。 - 修正
autocomplete参数:传入定义好的异步函数time_autocomplete,而非静态列表。 - 设置
time为可选参数:添加required=False,并在函数内处理默认值逻辑。 - 修复代码笔误:将
coolor改为正确的color,补充today变量的定义。 - 补充异常处理:处理无法给用户发送私信的情况,避免程序报错。
内容的提问来源于stack exchange,提问作者Bob Dylan
相关产品推荐
相关产品推荐

