代码之家  ›  专栏  ›  技术社区  ›  Ican

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

  •  7
  • Ican  · 技术社区  · 8 年前

    嗨,我想在特定的时间从机器人发送消息(没有我的消息),例如每周六早上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)
    

    但ofc不起作用。 尝试使用

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

    但同样没有结果。不知道该怎么办,请帮忙提建议。

    2 回复  |  直到 8 年前
        1
  •  18
  •   Justin Lillico    6 年前

    我也有同样的问题,我可以用 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)))
    

        2
  •  6
  •   stuckoverflow Samit Saxena    5 年前

    您可以使用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

    快乐的编码!!!