python-3.x - 使用 discord.py 编辑消息

标签 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 来编辑消息?

最佳答案

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 编辑消息,您需要它来自的 channel :

@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 中。


引用资料:

关于python-3.x - 使用 discord.py 编辑消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62149285/

相关文章:

python - WSGI (python) 如何从 HTML 表单获取 POST 数据?

python - 将 Sublime 3 的 Python Build 更改为使用 py 而不是 python 作为命令

不和谐.ext.commands.errors.CommandNotFound : Command "balance" is not found error even though its there

python - 在循环中的内联 if 语句中使用 break 会导致语法错误

python - python程序中的.pyw文件

python - 将变量从另一个 .py 文件检索到 cog 文件。 (不和谐.py)

python - 对此 Discord.py 重写 + react 灯代码感到困惑 - 需要解释

python - 阻止机器人创建同名的重复 channel |不和谐.py

python - 使用 Sublime Text 3 设置 Python 3 构建系统

python - 如何检查邀请是否无效?