[英]Problem with discord.py background task looping
多年来,我一直在尝试修复此错误。 所以基本上我现在正在尝试用 3 种不同的方式循环任务,这是我得到的最接近的方式,但无法弄清楚为什么会发生这个错误
回溯(最后一次调用):文件“/home/jupe/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py”,第 607 行,在 _load_from_module_spec spec.loader.exec_module( lib) 文件"",第 779 行,在 exec_module 文件中"",第 916 行,在 get_code 文件中"",第 846 行,在 source_to_code 文件中"",第 219 行,在 _call_with_frames_removed 文件中"/home/jupe/bot/modules/task .py”,第 25 行 def setup(bot): ^ SyntaxError: invalid syntax 上述异常是以下异常的直接原因: Traceback(最近一次调用最后一次):文件“main.py”,第 12 行,在 bot 中。 load_extension(f'modules.{filename[:-3]}') 文件“/home/jupe/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py”,第 664 行,在 load_extension self._load_from_module_spec(spec, name) 文件“/home/jupe/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py”中,第 610 行,在 _load_from_module_spec 中引发错误。ExtensionFailed (key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'm odules.task' 引发错误:SyntaxError: invalid syntax (task.py, line 25)
此错误出现在此代码中,应该可以正常工作
import discord
from discord.ext import commands
import asyncio
import os
class CogBackground(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def scan(path):
for file in os.listdir(path):
x=os.stat(file)
Result=(time.time()-x.st_mtime)
print("The age of the given file is: ",Result)
async def task(self, ctx):
self.scan("imgs/")
await asyncio.sleep(15)
@commands.Cog.listener()
async def on_ready(self, ctx):
self.bot.loop.create_task(self.task(ctx)
def setup(bot):
bot.add_cog(CogBackground(bot))
您在on_ready
事件的第一行代码中有语法错误, scan
function 是一个协程,因此您必须等待它。
await self.scan('./imgs')
一个更好的选择是使用内置的discord.ext.tasks
扩展,它只是一个更好的选择
from discord.ext import tasks
# In the cog
@tasks.loop(seconds=15.0)
async def task(self):
await self.scan('./imgs')
@commands.Cog.listener()
async def on_ready(self):
self.task.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.