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

在discord.py中如何在命令上下文内获取消息内容(msg.content/ctx.content)?

在discord.py命令中获取完整消息内容的解决方案

嘿,我懂你的问题了——你想在@bot.command()装饰的命令里拿到用户发送的完整消息内容,就像在on_message事件里用msg.content那样,但直接用ctx.content却报错了对吧?

问题的核心在于:命令函数里的默认参数是Context(上下文)对象,而不是Message对象。Context本身没有content属性,但它自带了一个message属性,这个属性直接指向触发命令的原始Message实例,所以我们可以通过ctx.message.content来获取完整的消息内容。

修正后的命令代码

把你原来的命令代码改成这样就行:

@bot.command()
async def rps(ctx):
    target_channel_id = 797224597443051611
    if ctx.channel.id != target_channel_id:
        return
    message_content = str(ctx.message.content)
    await ctx.send(message_content)

执行效果

当用户发送!rps hello时,机器人会正确回复!rps hello,和你用on_message事件实现的效果完全一致。

额外小技巧

如果你只是需要获取命令前缀之后的内容(比如例子里的hello),其实可以直接给命令函数加参数,更方便:

@bot.command()
async def rps(ctx, *, content):
    # *号表示接收所有后续参数作为一个完整字符串
    await ctx.send(f"你输入的命令内容是:{content}")

这样用户发!rps hello world,机器人会回复你输入的命令内容是:hello world。不过要是你需要完整的消息文本,还是用ctx.message.content就够啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:22:38