I
I
Ilya T.2017-11-02 21:09:44
Python
Ilya T., 2017-11-02 21:09:44

How to handle external events using pytelegrambotapi?

Wrote several bots. In all cases, I managed something like this:

import telebot
bot = telebot.TeleBot(config.token, threaded=True)

@bot.message_handler(commands=['Меню','start','Обновить'])
def menu(message):
    markup = types.ReplyKeyboardMarkup()
    markup.row('/Обновить')
    bot.send_message(message.chat.id, 'Привет ' + message.chat.first_name,reply_markup=markup)

if __name__ == '__main__':
    bot.polling(none_stop=True)

The disadvantage of this approach is that the bot turns out to be "reactive" i.e. all it can do is respond to user actions. Is it possible to make the bot itself initiate messages on some external events?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dmitriprank, 2017-11-22
@Insaned

Look what a fun thing. And you can, and you can’t at the same time...
1. I’ll start small - until you write the first bot - he can’t write to you at all
2. If 1 point is in order, problem number 2 comes - or manually run the script, in which there will be no polling, but only a command to send a message, or throw it into cron, set the frequency of this script to run, and rejoice, or link your sending to some user action.
No, of course you can pervert, and write something like

while true:
    if (какое-то условие, допустим, your_date == datetime.today()):
        bot.send_message(.....)
        time.sleep(60*60) #Время сам уже выбирай

The logic is to run the script with such a simple code, and it will work for itself (the question is how much it will eat ...), check your condition, and fall asleep for the time you want.

X
X-User, 2017-11-04
@X-User

You can call bot.send_message() at any time. Here some kind of event occurs, you take the user's ID from the database and send a message.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question