Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message in specific time TelegramBot

Hi i want to send message from bot in specific time (without message from me), for example every Saturday morning at 8:00am. Here is my code:

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)

But ofc that's not working. Tried with

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

but again no result. Have no idea what to do, help please with advice.

like image 548
Ican Avatar asked Jan 16 '18 19:01

Ican


People also ask

Can Telegram BOT send scheduled message?

Users can now schedule recurring messages in the Telegram app itself. No more third-party applications! Recurring messages (@cron_telebot) is a Telegram bot I built specifically to schedule recurring messages on Telegram. You may add/delete/view the details of multiple recurring jobs and set advanced options for them.


2 Answers

I had this same issue and I was able to solve it using the schedule library. I always find examples are the easiest way:

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)))

I hope you find this useful, solved the problem for me :).

like image 137
Justin Lillico Avatar answered Sep 21 '22 01:09

Justin Lillico


You could manage the task with cron/at or similar.

Make a script, maybe called 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!')

Then program in cron like this.

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

Happy Coding!!!

like image 23
Pjl Avatar answered Sep 18 '22 01:09

Pjl