什么会导致discord.pytask.loop保持每秒运行一次,即使我指定它每2分钟运行一次?

2024-09-30 10:41:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在discord bot中添加了task.loop,以将数据备份到gdrive。在下面的代码中,您可以看到我在标志中指定它每2分钟运行一次。但当我运行它时,我会看到它每秒钟打印一次到控制台,然后在3-4个打印语句之后慢到4-5秒。我是否在代码中遗漏了导致此问题的任何步骤

import discord
import discord.utils
from discord.ext.commands import has_permissions
from discord.ext import commands, tasks
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import shutil
import os
from pathlib import Path
import time

gauth = GoogleAuth()
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    # Authenticate if they're not there
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    # Refresh them if expired
    gauth.Refresh()
else:
    # Initialize the saved creds
    gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")

drive = GoogleDrive(gauth)

intents = discord.Intents.default()
intents.members = True
intents.reactions = True
intents.messages = True
intents.emojis = True

with open("token.txt", 'r') as token_reader:
    TOKEN = token_reader.readlines()
    TOKEN = TOKEN[0]

client = commands.Bot(command_prefix='$', intents = intents)
client.remove_command('help')

class Main:
    def  __init__(self,TOKEN,client):
        self.token = TOKEN
        self.client  = client
        self.files = []

    def onStartup(self):
        self.backups.start()
        self.client.run(self.token)

    @tasks.loop(seconds=0, minutes=2.0, hours=0, count=None)
    async def backups(self):
        print('test')

        shutil.copy("scripts/battleplan.txt",Path().absolute())
        shutil.copy("scripts/rolesMSG.txt",Path().absolute())
        os.remove("scripts/battleplan.txt")
        os.remove("scripts/rolesMSG.txt")

        save = ["battleplan.txt", "discordBot","rolesMSG.txt"]
        self.files = sorted(self.files, key = lambda x: x['title'])
        for i, file in enumerate(self.files):
            print('uploading {} file from GDrive ({}/{})'.format(file['title'], i, len(self.files)-1))
            file.SetContentFile(save[i])
            file.Upload()
            #print("hit")

        shutil.copy("battleplan.txt","scripts")
        shutil.copy("rolesMSG.txt","scripts")
        os.remove("battleplan.txt")
        os.remove("rolesMSG.txt")

    @backups.before_loop
    async def before_backups(self):
        print('waiting...')
        await self.client.wait_until_ready()


main = Main(TOKEN,client)

@main.client.event  # event decorator/wrapper
async def on_ready():

    await main.client.change_presence(activity = discord.Game(name = 'Type ''$help'' for a list of commands!'))
    print(f"We have logged in as {main.client.user}")


    file_list = drive.ListFile({'q': "'{}' in parents and trashed=false".format('ID goes here')}).GetList()

    for i, file in enumerate(sorted(file_list, key = lambda x: x['title']), start=1):
        print('Downloading {} file from GDrive ({}/{})'.format(file['title'], i, len(file_list)))
        file.GetContentFile(file['title'])
    shutil.copy("battleplan.txt","scripts")
    shutil.copy("rolesMSG.txt","scripts")
    os.remove("battleplan.txt")
    os.remove("rolesMSG.txt")

    main.files = file_list

main.onStartup()


编辑:更新代码以反映我当前使用的内容。第60行使用save=[]并启动for循环是问题所在,我独立验证了这是导致循环再次运行的原因

编辑2:行“file.SetContentFile(save[i])”是问题所在。是因为我通过全局范围访问变量吗

编辑3:这不是因为全局范围,只是将其更改为保存类中的文件(编辑此答案中的代码以反映这一点),并验证排序方法也不是原因。问题仍然是“file.SetContentFile(save[i])”


Tags: fromimportselftxtclientosscriptsremove

热门问题