reo7sp / tgbot-cpp

C++ library for Telegram bot API
http://reo7sp.github.io/tgbot-cpp
MIT License
1.01k stars 245 forks source link

How to skip the "Forbidden: bot was blocked by the user" error? #268

Open Amirhan-Taipovjan-Greatest-I opened 1 year ago

Amirhan-Taipovjan-Greatest-I commented 1 year ago

The case: User sent a command and then blocked the bot when bot was switched off.

I can't make any solution for this problem. try-catch, if-else... they didn't help Me. The program sends the error and stops ownself...

miannoodle01 commented 1 year ago

you may write a recursive script, in which on specific error like blocked by user, script starts again like: int main() {try {} catch(exception &e) {if (e == "something") {main()}}}

rd181002 commented 5 months ago

if(bot.getApi().blockedByUser(message->chat->id)) return;

Adding this condition check to the beginning of each 'listener' solved the problem for me.

For instance:

 bot.getEvents().onAnyMessage([&bot](Message::Ptr message) {
        if(bot.getApi().blockedByUser(message->chat->id)) return;
        printf("User wrote %s\n", message->text.c_str());
        if (StringTools::startsWith(message->text, "/start")) {
            return;
        }
        bot.getApi().sendMessage(message->chat->id, "Your message is: " + message->text);
    });