如何在特定时间发送消息 TelegramBot

How to send message in specific time TelegramBot

嗨,我想在特定时间从机器人发送消息(没有我的消息),例如每个星期六早上 8:00am。 这是我的代码:

import telebot
import config
from datetime import time, date, datetime

bot = telebot.TeleBot(config.bot_token)
chat_id=config.my_id    

@bot.message_handler(commands=['start', 'help'])
def print_hi(message):
    bot.send_message(message.chat.id, 'Hi!')


@bot.message_handler(func=lambda message: False) #cause there is no message
def saturday_message():
    now = datetime.now()
    if (now.date().weekday() == 5) and (now.time() == time(8,0)):
        bot.send_message(chat_id, 'Wake up!')

bot.polling(none_stop=True)

但是那是行不通的。 尝试过

urlopen("https://api.telegram.org/bot" +bot_id+ "/sendMessage?chat_id=" +chat_id+ "&text="+msg)

但还是没有结果。不知道该怎么办,请大家指教

您可以使用 cron/at 或类似的方式管理任务。

制作一个脚本,也许叫做alarm_telegram.py

#!/usr/bin/env python
import telebot
import config
    
bot = telebot.TeleBot(config.bot_token)
chat_id=config.my_id
bot.send_message(chat_id, 'Wake up!')

然后像这样在 cron 中编程。

00 8 * * 6 /path/to/your/script/alarm_telegram.py

编码愉快!!!

我遇到了同样的问题,我能够使用 schedule 库解决它。我总是发现示例是最简单的方法:

import schedule
import telebot
from threading import Thread
from time import sleep

TOKEN = "Some Token"

bot = telebot.TeleBot(TOKEN)
some_id = 12345 # This is our chat id.

def schedule_checker():
    while True:
        schedule.run_pending()
        sleep(1)

def function_to_run():
    return bot.send_message(some_id, "This is a message to send.")

if __name__ == "__main__":
    # Create the job in schedule.
    schedule.every().saturday.at("07:00").do(function_to_run)

    # Spin up a thread to run the schedule check so it doesn't block your bot.
    # This will take the function schedule_checker which will check every second
    # to see if the scheduled job needs to be ran.
    Thread(target=schedule_checker).start() 

    # And then of course, start your server.
    server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))

我希望你觉得这有用,解决了我的问题:)。