【问题标题】:ctx.content in command and event difference (discord.py)ctx.content 命令和事件的区别 (discord.py)
【发布时间】:2026-01-13 11:00:02
【问题描述】:

在 discord.py 中是否有一些选项我可以在命令下访问 msg.content(或 ctx.content 每个人如何使用它)?下面你可以看到我的意思的两个例子。第一个是事件,我只需复制消息并让机器人将其发回。第二个是命令,但 msg.content 不起作用。我的问题是我不想过多地使用事件并将一切都置于命令之下。

@bot.event  
async def on_message(msg):
    chat = bot.get_channel(797224597443051611)
    if msg.channel.id != channel:
        return
    if msg.content.startswith("!rps"):
        message = str(msg.content)
        await chat.send(message)

有人输入 !rps hello。不和谐的输出是 !rps hello

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

有人输入 !rps hello(我的前缀是 !)。控制台输出错误:

discord.ext.commands.errors.CommandInvokeError: 命令引发异常:AttributeError: 'Context' object has no attribute 'content'

【问题讨论】:

    标签: python pycharm discord.py


    【解决方案1】:

    命令总是以commands.Context作为第一个参数,你也应该叫它ctx而不是msg,来访问你可以使用ctx.message.content的消息内容

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

    看看commands introduction

    【讨论】:

      【解决方案2】:

      为了获取命令的其余消息,您需要传递另一个参数。此参数将包括在!rps 之后发送的所有消息。此外,在命令中使用ctx 而不是msg 效果更好。

      @bot.command()
      async def rps(ctx, *, args):
          if ctx.channel.id != channel:
              return
          await ctx.send(args)
      

      在此代码中,args 参数包括!rps 之后的所有消息。

      【讨论】: