简体   繁体   English

Discord.py Bot 每天特定时间运行功能

[英]Discord.py Bot run function at specific time every day

I'm using discord.py to create a discord bot, and I need to execute certain actions every day at a specific time.我正在使用 discord.py 创建一个不和谐机器人,我需要每天在特定时间执行某些操作。 I saw this answer: How to make a loop in discord.py rewrite?我看到了这个答案: How to make a loop in discord.py rewrite? and I've been using it so far.到目前为止我一直在使用它。

The problem started when I hosted my bot on the heroku free plan.当我在 heroku 免费计划上托管我的机器人时,问题就开始了。 The server on Heroku resets at least once a day, which messes up the timer as shown in that post. Heroku 上的服务器每天至少重置一次,这会弄乱计时器,如该帖子所示。

I also saw the schedule library.我还看到了日程表库。 The problem with this is that it seems like it uses an infinite loop.问题在于它似乎使用了无限循环。 Wouldn't that prevent me from running anything else during the 24 hours?这不会阻止我在 24 小时内运行其他任何东西吗? The bot needs to be able to respond to commands at all times, in addition to sending out the message every 24 hours.除了每 24 小时发送一次消息之外,机器人还需要能够始终响应命令。

How can I execute an action every day at a specific time even if the server resets?即使服务器重置,我如何每天在特定时间执行操作? Thank you in advance!先感谢您!

You can write a function to run periodically on a different thread and check if it's the right time to send your message like this example:您可以编写一个函数在不同的线程上定期运行,并检查是否是发送消息的正确时间,如下例所示:

from datetime import datetime
import threading


def checkTime():
    # This function runs periodically every 1 second
    threading.Timer(1, checkTime).start()

    now = datetime.now()

    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time)

    if(current_time == '02:11:00'):  # check if matches with the desired time
        print('sending message')


checkTime()

The heroku free plan is Linux. heroku 免费计划是 Linux。 Therefore cron will let you run things at a specific time and /etc/init.d/ will let you run things at start up.因此, cron将让您在特定时间运行,而/etc/init.d/将让您在启动时运行。 It's a good thing to know your OS.了解您的操作系统是一件好事。

Have you considered using multithreading to run your program?您是否考虑过使用多线程来运行您的程序? You could have one thread waiting for the time of day you want, and another that is running the rest of your program.您可以让一个线程等待您想要的时间,另一个线程正在运行程序的其余部分。 Here's some documentation to help you get started: Intro to Python Threading , Threading Documentation以下是一些帮助您入门的文档: Python 线程简介线程文档

I know I am late, but this may be helpful for future users.我知道我迟到了,但这可能对未来的用户有帮助。
There is a library called APScheduler which can be used to run functions by setting a cron job (there are other ways too instead of cron. Read more ).有一个名为APScheduler的库,可用于通过设置 cron 作业来运行函数(还有其他方法代替 cron。阅读更多)。

A small example will be like:一个小例子将是这样的:

import discord
from discord.ext import commands

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger

class Scheduler(commands.Cog):
    """Schedule commands."""
    def __init__(self, bot):
        self.bot = bot

        # Initialize session
        self.session = aiohttp.ClientSession()
    
    # Scheduled events
    async def schedule_func(self):

    def schedule(self):
        # Initialize scheduler
        schedule_log = logging.getLogger("apscheduler")
        schedule_log.setLevel(logging.WARNING)

        job_defaults = {
            "coalesce": True,
            "max_instances": 5,
            "misfire_grace_time": 15,
            "replace_existing": True,
        }

        scheduler = AsyncIOScheduler(job_defaults = job_defaults, 
                          logger = schedule_log)

        # Add jobs to scheduler
        scheduler.add_job(self.schedule_func, CronTrigger.from_crontab("0 * * * *")) 
        # Every hour

And in our main.py file add this (after importing the schedule_jobs.py file obviously):在我们的main.py文件中添加这个(显然是在导入schedule_jobs.py文件之后):

# Start scheduled commands
scheduler = schedule_jobs.Scheduler(bot).schedule()
scheduler.start()

You can have an infinite loop and use the asyncio.sleep() function.您可以无限循环并使用 asyncio.sleep() 函数。 This allows you to process commands from anywhere in the script and still wait the time.这允许您从脚本中的任何位置处理命令并仍然等待时间。 Here's a little example:这是一个小例子:

import asyncio

while True:
    await asyncio.sleep(60)
    print(1)

@client.command()
async def command(ctx):
    pass

Every minute the script will print 1 and anytime somebody does the command it will execute.脚本每分钟都会打印 1 并且任何时候有人执行它都会执行的命令。

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

相关问题 如何让机器人每天在特定时间在 discord.py 中运行定义的函数? - How to make the bot run a defined function at a specific time everyday in discord.py? Discord.py 在特定时间在类中运行函数 - Discord.py run function in class at specific time 如何使用 python 让 Discord 机器人每天在特定时间运行 function? - How to make Discord bot run a function every day at a specific time using python? 每次具有特定角色的用户在任何频道发言时,如何让机器人发送消息 | Discord.py - How to have the bot send a message every time a user with a specific role speaks in any channel | Discord.py discord.py 我试图从我的服务器发出一个 afk 命令,每次我运行我的机器人时它都会出错 - discord.py I'm trying to make an afk command from my server, and every time i run my bot it gives an error Discord.py 在脚本中运行 2 个机器人实例 - Discord.py run 2 instances of a bot in a script 如何安排一个函数在discord.py中的特定时间每天运行? - How do I schedule a function to run everyday at a specific time in discord.py? 在提到机器人时触发 function - discord.py - Trigger function on bot mention - discord.py discord.py 如何让机器人在特定日期自动发送消息? - discord.py How to make bot automatically send message on a specific day? discord.py:函数等待特定日期和时间 - discord.py: function wait until a specific date and time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM