我有一个名为wednesday
的cog,它从images
文件夹中打印某个图像,顾名思义,每周三。然而,出于测试目的,我将循环设置为每30秒运行一次,并且我将其设置为在今天(周一)而不是周三运行。我已经尝试在我的计算机上本地运行此代码,它的工作没有问题。然而,在部署到Heroku之后,循环根本不起作用。请记住,我还有另一个齿轮,它也有tasks.loop
,它每隔几秒钟就会改变我的bot的状态。然而,这个齿轮在Heroku上没有任何问题。如前所述,这个wednesday
齿轮在我的机器上本地工作,这意味着我正在为我的bot正确地添加和加载齿轮,并执行代码运行所需的其他操作。那么,为什么我的代码不能在Heroku上工作呢?
import discord, datetime
from discord.ext import commands, tasks
import json
with open('config.json') as f:
config = json.load(f)
class wednesday(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(seconds=30)
async def time_checker(self):
self.time = datetime.datetime.now
if self.time().hour == 19:
if datetime.datetime.today().weekday() == 0: # 0 because I'm testing today which is a Monday
self.channel = await self.bot.fetch_channel(config['id'])
await self.channel.send(file=discord.File('images/wednesday_pic.png'))
@commands.Cog.listener()
async def on_ready(self):
await self.bot.wait_until_ready()
self.time_checker.start()
def setup(bot):
bot.add_cog(wednesday(bot))
我不确定为什么会发生这种情况:我想这可能与循环有关。我在images
文件夹中还有其他图像,这些图像适用于我拥有的其他命令,因为当我调用该命令时,bot会发送它们。如有任何帮助,不胜感激。
我们需要更多的调试细节。你可以在调试时发现错误所在。
- 检查
requirements.txt
,确保版本被锁定。(如果您通过pip freeze
生成它,可能就是这种情况。如果没有:请确保本地开发环境中的版本与Heroku上的版本相同。 - 添加更多日志。加载
cog
时的日志。重复执行任务时的日志以及变量的值。输出当前工作目录的日志(import os; print(os.getcwd())
) - 检查你的机器人到达了多远。它一开始就失败了,没有上线吗?齿轮没有装好吗?是例行任务吗?是路径分辨率吗?
- 提供日志。不要砍掉圆木。提供完整的东西。他们可能看起来与你无关,但其他读者可能会发现一些东西。
- 您提供了图像的相对路径。提供项目文件夹结构的信息。用于执行项目的命令是什么(
Procfile
,也可以在日志中看到)
我已经找出了导致错误的原因。Heroku服务器在UTC时区运行,而我在PST/PDT时区。因此,我使用UTC到PDT转换器来获得我正在寻找循环以打印出图像的适当时间。下面是最后的代码:
import discord, datetime
from discord.ext import commands, tasks
import json
with open('config.json') as f:
config = json.load(f)
class wednesday(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(hours=1)
async def time_checker(self):
self.channel = await self.bot.fetch_channel(config['channel'])
self.time = datetime.datetime.now
if self.time().hour == 12:
if datetime.datetime.today().weekday() == 3:
await self.channel.send(file=discord.File('images/wednesday_pic.png'))
@commands.Cog.listener()
async def on_ready(self):
await self.bot.wait_until_ready()
self.time_checker.start()
def setup(bot):
bot.add_cog(wednesday(bot))