Search code examples
pythonbotstelegramtelegram-botpy-telegram-bot-api

How to check if a user is subscribed to a specific Telegram channel (Python / PyTelegramBotApi)?


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!


Solution

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