4

I am writing a Telegram bot using the PyTelegramBotApi library, I would like to implement the function of checking the user's subscription to a certain telegram channel, and if there is none, offer to subscribe. Thanks in advance for your answers!

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36

1 Answers1

6

use getChatMember method to check if a user is member in a channel or not.

getChatMember

Use this method to get information about a member of a chat. Returns a ChatMember object on success.

import telebot

bot = telebot.TeleBot("TOKEN")

CHAT_ID = -1001...
USER_ID = 700...

result = bot.get_chat_member(CHAT_ID, USER_ID)
print(result)

bot.polling()

Sample result:

You receive a user info if the user is a member

{'user': {'id': 700..., 'is_bot': False, 'first_name': '', 'username': None, 'last_name': None, ... }

or an Exception otherwise

telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: user not found

example on how to use it inside your project

import telebot
from telebot.apihelper import ApiTelegramException

bot = telebot.TeleBot("BOT_TOKEN")

CHAT_ID = -1001...
USER_ID = 700...

def is_subscribed(chat_id, user_id):
    try:
        bot.get_chat_member(chat_id, user_id)
        return True
    except ApiTelegramException as e:
        if e.result_json['description'] == 'Bad Request: user not found':
            return False

if not is_subscribed(CHAT_ID, USER_ID):
    # user is not subscribed. send message to the user
    bot.send_message(CHAT_ID, 'Please subscribe to the channel')
else:
    # user is subscribed. continue with the rest of the logic
    # ...

bot.polling()
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
  • but how is it easier to **parse** the **received data**, and make a condition under which if _a person is sub, the bot will continue to work, or if not signed,_ **ask to subscribe?** – Bortsov Bogdan Oct 18 '20 at 20:14
  • 1
    @BortsovBogdan I've added some example on how you would use it as if-else logic and send a message – Tibebes. M Oct 18 '20 at 21:33
  • The bot must be added as an admin to the channel in question in order for this to work. – Slava Fomin II Jul 12 '23 at 21:03