使用discord.py编辑消息

时间:2020-06-02 09:51:24

标签: python-3.x discord.py

我希望我的机器人编辑一条消息,但出现错误

@client.command()
async def edit(ctx):
    message = await ctx.send('testing')
    time.sleep(0.3)
    message.edit(content='v2')

错误:

 RuntimeWarning: coroutine 'Message.edit' was never awaited
  message.edit(content='v2')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

和顺便说一句,如果通过ID编辑消息,有什么办法吗?

1 个答案:

答案 0 :(得分:2)

time.sleep()是一个阻止调用,这意味着它几乎破坏了您的脚本。您将要使用的是await asyncio.sleep()

此外,edit()是一个协程,因此需要等待。这是您的命令应如下所示:

import asyncio # if you haven't already

@client.command()
async def edit(ctx):
    message = await ctx.send('testing')
    await asyncio.sleep(0.3)
    await message.edit(content='v2')

要通过ID编辑一条消息,您需要它来自的渠道:

@client.command()
async def edit(ctx, msg_id: int = None, channel: discord.TextChannel = None):
    if not msg_id:
        channel = client.get_channel(112233445566778899) # the message's channel
        msg_id = 998877665544332211 # the message's id
    elif not channel:
        channel = ctx.channel
    msg = await channel.fetch_message(msg_id)
    await msg.edit(content="Some content!")

假设前缀为!edit 112233445566778899 #message-channel-origin,此命令的用法为!,如果消息位于您要在其中执行命令的通道,则不要使用channel参数。


参考: