电报机器人 python 特定日期的自动消息

telegram bot python specific day automated messages

上下文: 我想在我用 python 做的电报机器人中添加一条自动消息,每次特定假期符合条件时都会发送一条消息。例如,国际男人节、独立日等。 这可能不使用 json 文件吗?最好使用一个简单的 if 函数,它将当前日期与列表中的指定日期进行比较,并根据日期 return 一条消息?我是 Python 的新手,如果您能通过示例指导我阅读一些文档,我将不胜感激:)

您可以为每个日期创建多个 cron 作业。每个 cron 作业都会 运行 您的脚本并发送您的消息。可能有更好的方法来做到这一点。但我个人对所有不按计划执行的脚本都使用 cron。

看看这个在特定日期使用 cron: Cron expression for particular date

您还可以使用它来轻松配置 cron 计划: https://crontab.guru/

如果特殊假期的数量不是太多,您可以将日期和消息内嵌在脚本中,如下所示:

from datetime import date

messages = {
    "03-20": "A message for March Equinox here",
    "09-22": "A message for September Equinox here"
}


def get_message():
    mm_dd = date.today().strftime("%m-%d")
    return messages.get(mm_dd)


print(get_message())

如果 get_message returns 不是 None,则将其传递给 Telegram 机器人。 运行 每天一次来自 cron。