![](/img/trans.png)
[英]How to make the bot run a defined function at a specific time everyday in discord.py?
[英]Discord.py Bot run function at specific time every day
我正在使用 discord.py 創建一個不和諧機器人,我需要每天在特定時間執行某些操作。 我看到了這個答案: How to make a loop in discord.py rewrite? 到目前為止我一直在使用它。
當我在 heroku 免費計划上托管我的機器人時,問題就開始了。 Heroku 上的服務器每天至少重置一次,這會弄亂計時器,如該帖子所示。
我還看到了日程表庫。 問題在於它似乎使用了無限循環。 這不會阻止我在 24 小時內運行其他任何東西嗎? 除了每 24 小時發送一次消息之外,機器人還需要能夠始終響應命令。
即使服務器重置,我如何每天在特定時間執行操作? 先感謝您!
您可以編寫一個函數在不同的線程上定期運行,並檢查是否是發送消息的正確時間,如下例所示:
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()
heroku 免費計划是 Linux。 因此, cron將讓您在特定時間運行,而/etc/init.d/將讓您在啟動時運行。 了解您的操作系統是一件好事。
您是否考慮過使用多線程來運行您的程序? 您可以讓一個線程等待您想要的時間,另一個線程正在運行程序的其余部分。 以下是一些幫助您入門的文檔: Python 線程簡介、線程文檔
我知道我遲到了,但這可能對未來的用戶有幫助。
有一個名為APScheduler
的庫,可用於通過設置 cron 作業來運行函數(還有其他方法代替 cron。閱讀更多)。
一個小例子將是這樣的:
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
在我們的main.py
文件中添加這個(顯然是在導入schedule_jobs.py
文件之后):
# Start scheduled commands
scheduler = schedule_jobs.Scheduler(bot).schedule()
scheduler.start()
您可以無限循環並使用 asyncio.sleep() 函數。 這允許您從腳本中的任何位置處理命令並仍然等待時間。 這是一個小例子:
import asyncio
while True:
await asyncio.sleep(60)
print(1)
@client.command()
async def command(ctx):
pass
腳本每分鍾都會打印 1 並且任何時候有人執行它都會執行的命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.