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

Ica*_*can 6 python python-3.x telegram telegram-bot

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

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)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用。试过

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

但又没有结果。不知道该怎么办,请帮忙指点迷津。

Jus*_*ico 15

我有同样的问题,我能够使用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)))
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢你!您是唯一能够回答这个被问过多次的问题的人。使用线程是关键。 (2认同)

Pjl*_*Pjl 6

您可以使用 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!')
Run Code Online (Sandbox Code Playgroud)

然后像这样在cron中编程。

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

编码快乐!!!