【问题标题】:Discord.py trying to get the message author in my embedDiscord.py 试图在我的嵌入中获取消息作者
【发布时间】:2020-08-22 06:45:09
【问题描述】:

我一直在使用 Python 3.7.6 版在 Thonny 中使用 Discord.py 编写我自己的不和谐机器人。我想在输入某个命令(!提交)时嵌入,以将用户名作为标题,将消息内容作为描述。我很高兴在我的嵌入中包含 !submit ' ',但如果有任何方法可以将其取出,并且只有消息的内容减去 !submit,我将不胜感激。现在我的代码出现两个错误,一个是 client.user.name 是机器人的名称(提交机器人)而不是作者(旧代码),我收到这条消息'命令引发异常: TypeError: Object of type Member is not JSON serializable' 使用我的新代码(如下),如果有人可以提供见解,请回复适当的修复!

client = commands.Bot(command_prefix = '!')
channel = client.get_channel(707110628254285835)

@client.event
async def on_ready():
 print ("bot online")


@client.command()
async def submit(message):
 embed = discord.Embed(
    title = message.message.author,
    description = message.message.content,
    colour = discord.Colour.dark_purple()
 )
 channel = client.get_channel(707110628254285835)
 await channel.send(embed=embed)





client.run('TOKEN')

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:
    client = commands.Bot(command_prefix = '!')
    #got rid of the old channel variable here
    @client.event
    async def on_ready():
     print ("bot online")
    
    @client.command()
    async def submit(ctx, *, message): #the `*` makes it so that the message can include spaces
     embed = discord.Embed(        
        title = ctx.author, #author is an instance of the context class
        description = message, #No need to get the content of a message object
        colour = discord.Colour.dark_purple()
     )
     channel = client.get_channel(707110628254285835)
     await channel.send(embed=embed)
    
    client.run('TOKEN')
    

    问题: 1.channel被定义了两次, 2. discord.py 中的函数命令带有一个隐含的 context 参数,通常称为ctx。 总体而言,您似乎不了解 discord.py 必须提供的底层 OOP 概念。通过在线课程或文章刷新您的记忆可能会有所帮助。

    【讨论】:

      【解决方案2】:

      你已经很接近了……

      以下项目应该会有所帮助:

      1. 使用命令时,您通常将命令的上下文定义为“ctx”,这是第一个参数,有时也是唯一的参数。 “消息”通常用于消息事件,如async def on_message(message):
      2. 要从命令本身中分离出消息,您需要在函数定义中添加参数。
      3. 要获取用户名,您需要将其转换为字符串以避免 TypeError。
      4. 要在输入 !submit 的同一频道中发回消息,您可以使用 await ctx.send(embed=embed)

      试试:

      @client.command()
      async def submit(ctx, *, extra=None):
          embed = discord.Embed(
              title=str(ctx.author.display_name),
              description=extra,
              colour=discord.Colour.dark_purple()
          )
          await ctx.send(embed=embed)
      

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-23
        • 1970-01-01
        • 2016-12-10
        • 2021-02-13
        相关资源
        最近更新 更多