如何使Discord bot每天在特定时间使用python运行功能?

时间:2020-08-03 03:42:54

标签: python discord discord.py

我一直试图让Discord机器人每天在特定时间运行某个功能。目前,该漫游器可以每24小时执行一次操作,因此,我需要做的就是让它在特定时间启动。但是,我无法弄清楚为什么我无法使它工作。我已经尝试过使用时间表,自动调度程序等多种解决方案。在其他情况下,我也尝试过使用该解决方案,但是我无法使用它们。

当前,该机器人正在运行,并且不会引发任何错误,但是似乎从未调用过函数roletask()。 ((出于测试目的,Roletask设置为每5秒运行一次)

编辑:通过将“ datetime.hour”和“ Datetime.minute”更改为“ now.hour”和“ now.minute”,我可以将其修复。此外,由于我导入事物的方式,需要将“ Datetime.datetime(...)”更改为仅“ datetime(...)”

希望这对将来遇到此问题的其他人有所帮助!

import discord
import random
import asyncio
import schedule
import threading
import time
from datetime import datetime, timedelta
from discord.ext import commands, tasks
from discord.utils import get

bot = commands.Bot(command_prefix='[]')
bot.remove_command("help")
guild = bot.get_guild(607452358544195588)
role_id = 738129548805275710
ROLE_NAME1 = "q-and-a"
ROLE_NAME2 = "tunes"


@tasks.loop(seconds=5)
async def roletask():
    print("ur bad")
    channel = bot.get_channel(681179611253571688)
    await channel.send('<@&738129548805275710> You are part of the test role!')


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

roletask.start()

@bot.event
async def on_ready():
    await bot.change_presence(status=discord.Status.online, activity=discord.Game('[]help'))
    print('We have logged in as {0.user}'.format(bot))

1 个答案:

答案 0 :(得分:2)

我对discordbots并不熟悉,但是您可以尝试apscheduler,它用于安排特定时间的作业。 您需要使用以下命令安装apscheduler:

pip install APScheduler

这是示例代码:

from datetime import datetime
from apscheduler.scheduler import Scheduler

# Create the scheduler and start it
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def job(text):
    print(text)

# The job will be executed on August 5th, 2020 at 16:30:05
exec_date =  datetime(2020, 5, 5, 16, 30, 5)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(job, exec_date, ['my_text'])