【问题标题】:How to make Discord bot run a function every day at a specific time using python?如何使用 python 让 Discord bot 每天在特定时间运行一个函数?
【发布时间】:2020-11-23 03:57:20
【问题描述】:

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

目前,机器人运行,并且没有抛出任何错误,但函数 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))

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 2020-01-13
      • 2020-12-16
      • 2021-05-17
      • 2018-02-17
      • 2019-04-01
      • 1970-01-01
      • 2019-05-23
      • 2015-08-18
      相关资源
      最近更新 更多