如何使用调度库运行异步函数? [英] How can I run an async function using the schedule library?

查看:27
本文介绍了如何使用调度库运行异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 discord.py rewrite 编写一个 discord bot,我想每天在特定时间运行一个函数.我完全没有使用异步函数的经验,我不知道如何在不使用await"的情况下运行一个.这只是我的一段代码,这就是为什么有些东西可能没有定义.

I'm writing a discord bot using discord.py rewrite, and I want to run a function every day at a certain time. I'm not experienced with async functions at all and I can't figure out how to run one without using "await." This is only a piece of my code which is why some things may not be defined.

async def send_channel():
    try:
        await active_channel.send('daily text here')
    except Exception:
        active_channel_id = None
        active_channel = None

async def timer():
    while True:
        schedule.run_pending()
        await asyncio.sleep(3)
        schedule.every().day.at("21:57").do(await send_channel())

@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print(bot.user.id)
    print("------")

    bot.loop.create_task(timer())

使用 schedule.every().day.at("00:00").do() 函数,当我输入 await send_channel() 时出现此错误.do() 参数中的code>:

Using the schedule.every().day.at("00:00").do() function, I get this error when I put await send_channel() in the paramaters of .do():

self.job_func = functools.partial(job_func, *args, **kwargs)类型错误:第一个参数必须是可调用的

self.job_func = functools.partial(job_func, *args, **kwargs) TypeError: the first argument must be callable

但是当我不使用 await 并且我只有 send_channel() 作为参数时,我会收到此错误:

But when I don't use await, and I just have send_channel() as parameters, I get this error:

运行时警告:协程'send_channel'从未被等待

RuntimeWarning: coroutine 'send_channel' was never awaited

我不是很擅长编程,所以如果有人可以尝试为我简化它,那就太棒了.

I'm not super good at programming so if someone could try to dumb it down for me that would be awesome.

谢谢

推荐答案

是使用 discord.ext.tasks 扩展.这使您可以注册要以特定时间间隔重复调用的任务.当机器人启动时,我们将循环的开始延迟到目标时间,然后每 24 小时运行一次任务:

The built-in solution to this in discord.py is to use the discord.ext.tasks extension. This lets you register a task to be called repeatedly at a specific interval. When the bots start, we'll delay the start of the loop until the target time, then run the task every 24 hours:

import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta

bot = commands.Bot("!")

@tasks.loop(hours=24)
async def my_task():
    ...

@my_task.before_loop
async def before_my_task():
    hour = 21
    minute = 57
    await bot.wait_until_ready()
    now = datetime.now()
    future = datetime.datetime(now.year, now.month, now.day, hour, minute)
    if now.hour >= hour and now.minute > minute:
        future += timedelta(days=1)
    await asyncio.sleep((future-now).seconds)

my_task.start()

这篇关于如何使用调度库运行异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆