如何在Py-cord中获取Discord消息对象作为斜杠命令参数?
问题:Py-cord机器人
/pin命令报错AttributeError: 'str' object has no attribute 'pin' 我在Python 3.9环境下使用Py-cord 2.3.2开发Discord机器人,期望实现/pin斜杠命令:当用户调用该命令时,机器人固定指定的消息。编写的代码如下:
@bot.slash_command(name="pin", description="Make a pinned message.") @default_permissions(manage_messages=True) async def pin(ctp, arg): message = arg await message.pin() print ('Used used the command ""/pin"')
运行时触发报错:
Ignoring exception in command pin: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/discord/commands/core.py", line 124, in wrapped ret = await coro(arg) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/discord/commands/core.py", line 980, in _invoke await self.callback(ctx, **kwargs) File "/Users/fk/Downloads/amiebot (no config)/tweescord.py", line 46, in pin await message.pin() AttributeError: 'str' object has no attribute 'pin' Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'str' object has no attribute 'pin'
报错原因
- 参数类型未声明:代码中
arg参数没有指定类型,Py-cord默认将其解析为字符串,但pin()是DiscordMessage对象的专属方法,字符串对象不具备该方法,因此触发AttributeError。 - 代码细节问题:上下文参数名
ctp不符合行业常规命名(通用名为ctx);打印语句存在拼写错误Used used;参数缺少描述,用户调用时无法明确参数用途。
修复方案
修正后的代码如下:
import discord from discord.ext import commands # 假设bot已完成正确初始化 @bot.slash_command(name="pin", description="固定指定的Discord消息") @commands.default_permissions(manage_messages=True) async def pin(ctx, message: discord.Message, reason: str = "用户请求固定消息"): await message.pin(reason=reason) print(f"用户使用了/pin命令,固定消息ID: {message.id}")
关键修改点
- 指定参数类型:将
arg改为message: discord.Message,Py-cord会自动识别并提供消息选择界面,传入真实的Message对象而非字符串。 - 规范上下文参数:将
ctp改为通用命名ctx,提升代码可读性与维护性。 - 添加可选备注参数:新增
reason参数用于记录固定消息的原因,也可根据需求移除。 - 修正日志输出:修复拼写错误,添加消息ID便于追踪操作记录。
- 完善权限装饰器:确保
default_permissions通过commands模块正确调用。
内容的提问来源于stack exchange,提问作者stellarstye
相关产品推荐
相关产品推荐

