【问题标题】:async functions as callback for threading.Timer异步函数作为 threading.Timer 的回调
【发布时间】:2021-11-23 03:09:11
【问题描述】:

我在 Python 中使用线程包时遇到问题。我想创建一段时间后发送消息的不和谐机器人。以前我使用time.sleep(),但它使我的机器人在给定的时间段内无用。我发现我可以使用threading.Timer(),但我不能让它工作。 示例代码:

async def send_sth(channel):
    await channel.send("some message")


client = discord.Client()


@client.event
async def on_message(message):
    if message.content == 'send sth':
        timer = threading.Timer(10.0, send_sth, [message.channel])
        timer.start()

10 秒后我有错误提示 RuntimeWarning: coroutine 'send_sth' was never awaited。是否可以使用 Timer 回调运行异步函数?

【问题讨论】:

标签: python multithreading discord.py


【解决方案1】:

这比我想象的要容易

client = discord.Client()


@client.event
async def on_message(message):
    if message.content == 'send sth':
        await asyncio.sleep(10)
        await message.channel.send("some message")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2017-11-27
    • 2015-01-22
    相关资源
    最近更新 更多