Python Bot按顺序发送消息
在Discord中,发送消息的长度限制为2000个字符,因此我们需要拆分并发送多条消息。我使用下面的代码,它可以工作,但是消息没有按照指定的顺序发送,所以我在每条消息之后使用Python Bot按顺序发送消息,python,python-3.x,discord,discord.py,Python,Python 3.x,Discord,Discord.py,在Discord中,发送消息的长度限制为2000个字符,因此我们需要拆分并发送多条消息。我使用下面的代码,它可以工作,但是消息没有按照指定的顺序发送,所以我在每条消息之后使用sleep()。现在它工作了,但消息有时仍然不符合顺序。由于顺序不一,在阅读长消息时会感到困惑 @bot.command(pass_context=True) async def ping(ctx): msg = "Message 1".format(ctx.message) await bot.say(ms
sleep()
。现在它工作了,但消息有时仍然不符合顺序。由于顺序不一,在阅读长消息时会感到困惑
@bot.command(pass_context=True)
async def ping(ctx):
msg = "Message 1".format(ctx.message)
await bot.say(msg)
await sleep(.5)
msg = "Message 2".format(ctx.message)
await bot.say(msg)
await sleep(.5)
msg = "Message 3".format(ctx.message)
await bot.say(msg)
await sleep(.5)
msg = "Message 4 {0.author.mention}".format(ctx.message)
await bot.say(msg)
我需要在每条消息之后,它应该检查发送的消息,然后它应该在最后一条消息之后发送第二条消息。或者是否有其他解决方案来解决此问题?只需在消息之间添加一点延迟:
from asyncio import sleep
@bot.command(pass_context=True)
async def ping(ctx):
msg = "Message 1 {0.author.mention}".format(ctx.message)
await bot.say(msg)
await sleep(.5)
msg = "Message 2 {0.author.mention}".format(ctx.message)
await bot.say(msg)
await sleep(.5)
msg = "Message 3 {0.author.mention}".format(ctx.message)
await bot.say(msg)
await sleep(.5)
msg = "Message 4 {0.author.mention}".format(ctx.message)
await bot.say(msg)
这似乎是一项简单的任务,但实际上相当复杂。还有人可能建议使用
bot.wait_for_message(…)
,但这种逻辑存在漏洞(bot发送的消息wait_for_message
已准备就绪),因为它不是用来执行任务的
我现在能想到的最好的方法是制作一个自定义的未来事件,并在发送消息后添加一个wait_for
。future应该注册一个on_message
事件,检查bot的消息是否已发送
import asyncio
def wait(check):
f = asyncio.Future(loop=bot.loop)
async def _wait(future, check):
@bot.listen()
async def on_message(msg):
if check(msg):
bot.remove_listener(on_message)
future.set_result(msg)
asyncio.ensure_future(_wait(f, check), loop=bot.loop)
return f
def ping_check(content):
def check(msg):
if msg.content == content and msg.author == bot.user:
return True
return False
return check
@bot.command(pass_context=True)
async def ping(ctx):
msg = "Message 1 {0.author.mention}".format(ctx.message)
f = wait(ping_check(msg))
await bot.say(msg)
await asyncio.wait_for(f, None, loop=bot.loop)
msg = "Message 2 {0.author.mention}".format(ctx.message)
f = wait(ping_check(msg))
await bot.say(msg)
await asyncio.wait_for(f, None, loop=bot.loop)
msg = "Message 3 {0.author.mention}".format(ctx.message)
f = wait(ping_check(msg))
await bot.say(msg)
await asyncio.wait_for(f, None, loop=bot.loop)
msg = "Message 4 {0.author.mention}".format(ctx.message)
f = wait(ping_check(msg))
await bot.say(msg)
await asyncio.wait_for(f, None, loop=bot.loop)
我进一步编辑了这个解决方案,添加了一个
check()
,这使得等待()
功能更加灵活,删除了以前的硬编码检查。@demory在您的on_command_error
coroutine.hi@Patrick i更新了on_command_error
,这是我为上面的commands.CommandInvokeError
添加的。您可能应该问一个单独的问题。当您这样做时,请包括什么是异常
以及它从何而来什么是异常。暂停
?如果你取消注册你的on_command_error
,(只需注释掉@bot.event
)这将如何改变你得到的错误?刚才删除了所有on_command_error
,现在当我使用wait sleep(.5)
运行命令时,它给出了我在上面添加的一个错误。是的,现在它按顺序发送消息。如果这个问题有什么我需要的,我会给你留言。谢谢你,兄弟。。。