将时区设置为Asyncioscheduler

发布于 2025-01-29 12:32:49 字数 2068 浏览 3 评论 0原文

我在太平洋时区,并且正在创建一个Discord机器人,以在中央时间上午8点发送消息。

import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
from rich import print
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger


load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.members = True


bot = commands.Bot(command_prefix = '!', intents=intents)

# Will become the good morning message
async def gm():
    c = bot.get_channel(channel_id_removed) 
    await c.send("This will be the good morning message.")

@bot.event
async def on_ready():
    for guild in bot.guilds:
        print(
            f'{bot.user} is connected to the following guild:\n'
            f'\t{guild.name} (id: {guild.id})'
        )

    #initializing scheduler for time of day sending
    scheduler = AsyncIOScheduler()
    # Attempts to set the timezone
    # scheduler = AsyncIOScheduler(timezone='America/Chicago')
    # scheduler = AsyncIOScheduler({'apscheduler.timezone': 'America/Chicago'})
    # scheduler.configure(timezone='America/Chicago')

    # Set the time for sending
    scheduler.add_job(gm, CronTrigger(hour="6", minute="0", second="0")) 

    #starting the scheduler
    scheduler.start()


@bot.event
async def on_member_join(member):
    general_channel = None
    guild_joined = member.guild
    print(guild_joined)
    general_channel = discord.utils.get(guild_joined.channels, name='general')

    print(f'General Channel ID: {general_channel}')
    if general_channel:
        embed=discord.Embed(title="Welcome!",description=f"Welcome to The Dungeon {member.mention}!!")
        await general_channel.send(embed=embed)

bot.run(TOKEN)

环境:

Windows 10
Python 3.10.4

APScheduler           3.9.1
pytz                  2022.1
pytz-deprecation-shim 0.1.0.post0
tzdata                2022.1
tzlocal               4.2

我只是想知道我是否做错了什么?或者,如果我想做的事情根本不支持?如果我使用当地时间,它可以工作,所以我知道功能还可以。

I'm in the Pacific timezone and I'm creating a discord bot to send a message at 8am in CENTRAL time.

import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
from rich import print
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger


load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.members = True


bot = commands.Bot(command_prefix = '!', intents=intents)

# Will become the good morning message
async def gm():
    c = bot.get_channel(channel_id_removed) 
    await c.send("This will be the good morning message.")

@bot.event
async def on_ready():
    for guild in bot.guilds:
        print(
            f'{bot.user} is connected to the following guild:\n'
            f'\t{guild.name} (id: {guild.id})'
        )

    #initializing scheduler for time of day sending
    scheduler = AsyncIOScheduler()
    # Attempts to set the timezone
    # scheduler = AsyncIOScheduler(timezone='America/Chicago')
    # scheduler = AsyncIOScheduler({'apscheduler.timezone': 'America/Chicago'})
    # scheduler.configure(timezone='America/Chicago')

    # Set the time for sending
    scheduler.add_job(gm, CronTrigger(hour="6", minute="0", second="0")) 

    #starting the scheduler
    scheduler.start()


@bot.event
async def on_member_join(member):
    general_channel = None
    guild_joined = member.guild
    print(guild_joined)
    general_channel = discord.utils.get(guild_joined.channels, name='general')

    print(f'General Channel ID: {general_channel}')
    if general_channel:
        embed=discord.Embed(title="Welcome!",description=f"Welcome to The Dungeon {member.mention}!!")
        await general_channel.send(embed=embed)

bot.run(TOKEN)

Environment:

Windows 10
Python 3.10.4

APScheduler           3.9.1
pytz                  2022.1
pytz-deprecation-shim 0.1.0.post0
tzdata                2022.1
tzlocal               4.2

I'm just wondering if I'm doing something wrong? Or if what I'm trying to do simply isn't supported? It works if I use my local time so I know the function is ok.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2025-02-05 12:32:49

您正在使用Asyncio调度程序,但您没有运行异步事件循环,因此无法使用它。复制/粘贴从提供了示例

from datetime import datetime
import asyncio
import os

from apscheduler.schedulers.asyncio import AsyncIOScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = AsyncIOScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        pass

之所以无法正常工作,是因为,而scheduler.start()实例化事件循环作为副作用,它希望循环在其他地方运行,以便调度程序可以完成其工作。

You are using the asyncio scheduler but you're not running an asyncio event loop, so there is no way this could work. Copy/paste from the provided example:

from datetime import datetime
import asyncio
import os

from apscheduler.schedulers.asyncio import AsyncIOScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = AsyncIOScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        pass

The reason it is not working is because, while scheduler.start() instantiates an event loop as a side effect, it expects the loop to be run elsewhere so that the scheduler can do its work.

看春风乍起 2025-02-05 12:32:49

为了设置时区,只需使用OS模块设置ENV变量即可。

@app.on_event('startup')
def init_data():
    os.environ['TZ'] = 'America/New_York'

In order to set the timezone just set the ENV variable using the os module.

@app.on_event('startup')
def init_data():
    os.environ['TZ'] = 'America/New_York'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文