task.loop计时器在discord.py中重复执行

时间:2020-06-24 14:54:16

标签: discord atom-editor discord.py

因此,我正在制作一个机器人,该机器人将在每个星期三发布Wednesday Frog模因。为此,我使用discord.py的task.loop函数,该函数理论上应在完成版本中每24小时运行一次。不管我将其设置为多少小时,几分钟或几秒钟,事情几乎都是每秒都与模因或“不是星期三”而成为我的聊天内容。

代码:

import discord
import datetime
from discord.ext import tasks, commands
client = commands.Bot(command_prefix = ')')

@client.event
async def on_ready():
    wednesdayCheck.start()
    print("Lets see if it's wednesday.")

@tasks.loop(hours=2)
async def wednesdayCheck():
    if datetime.datetime.today().weekday() == 2:
        for guild in client.guilds:
            for channel in guild.text_channels:
                await channel.send(file=discord.File('Meme.jpg'))
    elif datetime.datetime.today().weekday() != 2:
        for guild in client.guilds:
            for channel in guild.text_channels:
                await channel.send("It's not Wednesday")

任何使该功能按预期的时间遵循计时器的帮助都将非常重要。

2 个答案:

答案 0 :(得分:0)

尝试将.start()放在on_ready()函数外部,正好位于bot.run()上方。 不能保证on_ready()函数只能运行一次。

https://discordpy.readthedocs.io/en/latest/api.html?highlight=on_ready#discord.on_ready

答案 1 :(得分:0)

以下是您问题的可能解决方案:

创建一个全局布尔变量,确保块只在 on_ready 中运行一次

ON_READY_FIRST_RUN = True

@client.event
async def on_ready():
    global ON_READY_FIRST_RUN
    if ON_READY_FIRST_RUN:
        wednesdayCheck.start()
        print("Lets see if it's Wednesday.")
        ON_READY_FIRST_RUN = False

我一直在尝试设置一个机器人来在每个工作日早上发送一条消息,但由于某种原因无法执行 @tasks.loop。希望这对您有所帮助!

编辑:我试图使用@tasks.before_loop,但我只是将该代码放入我的@tasks.loop 中,现在效果很好!