Can a telegram bot block a specific user?

13,757

Firstly I have to say that Telegram Bot API does not have such a capability itself, Therefore you will need to implement it on your own and all you need to do is:

  1. Count the number of the messages that a user sends within a second which won't be so easy without having a database. But if you have a database with a table called Black_List and save all the messages with their sent-time in another table, you'll be able to count the number of messages sent via one specific ChatID in a pre-defined time period(In your case; 1 second) and check if the count is bigger than 5 or not, if the answer was YES you can insert that ChatID to the Black_List table.
  2. Every time the bot receives a message it must run a database query to see that the sender's chatID exists in the Black_List table or not. If it exists it should continue its own job and ignore the message(Or even it can send an alert to the user saying: "You're blocked." which I think can be time consuming).

Note that as I know the current telegram bot API doesn't have the feature to stop receiving messages but as I mentioned above you can ignore the messages from spammers.

In order to save time, You should avoid making a database connection every time the bot receives an update(message), instead you can load the ChatIDs that exist in the Black_List to a DataSet and update the DataSet right after the insertion of a new spammer ChatID to the Black_List table. This way the number of the queries will reduce noticeably.

Share:
13,757
MaGaroo
Author by

MaGaroo

Updated on July 06, 2022

Comments

  • MaGaroo
    MaGaroo almost 2 years

    I have a telegram bot that for any received message runs a program in the server and sends its result back. But there is a problem! If a user sends too many messages to my bot(spamming), it will make server so busy!
    Is there any way to block the people whom send more than 5 messages in a second and don't receive their messages anymore? (using telegram api!!)

    • mymedia
      mymedia about 7 years
      No, you can't. API does not provide this feature. Just make a local block list of users whom the bot will ignore.
    • MaGaroo
      MaGaroo about 7 years
      I want those users' messages don't even exist in the json file which I download from telegram server! Anyway, it's ok if there is no other way.
  • panjeh
    panjeh almost 5 years
    I recommend using redis for implementing this scenario
  • stckvrw
    stckvrw over 2 years
    @Naser.Sadeghi but we can still ban a user in a supergroup/channel, according to core.telegram.org/method/channels.editBanned, right?
  • Naser.Sadeghi
    Naser.Sadeghi over 2 years
    @stckvrw I believe so.