繁体   English   中英

如何使用 python 让 Discord 机器人每天在特定时间运行 function?

[英]How to make Discord bot run a function every day at a specific time using python?

我一直试图让我的 Discord 机器人在每天的特定时间运行 function。 目前,机器人可以每 24 小时执行一次操作,所以我需要做的就是让它在特定时间启动。 但是,我无法弄清楚为什么我不能让它工作。 我尝试了多种解决方案,使用 schedule、aioscheduler 等。我已经尝试过其他时候提出这个问题的解决方案,但我无法让它们中的任何一个工作。

目前,机器人运行,它不会抛出任何错误,但 function 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))

我不熟悉 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'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM