skip to Main Content

I’m trying to check if a user is subscribed to a specific Telegram channel, but function get_chat_member() always returns True Code:

import telebot
from telebot import types
from telebot.apihelper import ApiTelegramException


bot = telebot.TeleBot('<TOKEN>')

group_id = <Group id>


@bot.message_handler(commands=['start'])
def start(message):

    print(is_subscribed(group_id, message.from_user.id))

    start_message = f'Hi {message.from_user.username}'
    bot.send_message(message.chat.id, start_message, parse_mode='html')


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


bot.polling(none_stop=True)

2

Answers


  1. Chosen as BEST ANSWER

    Problem was solved in old versions it works like i try, now when it response json haves status field in variations "member, creator"


  2. I also came across this issues;

    responce = bot.get_chat_member(chat_id, user_id)

    only returns whether the response is success or not:

    I solved this by adding:

    response = bot.get_chat_member(chat_id, user_id)
        if responce.status == 'left':
            return False
        else:
            return True
    

    full code:

    import telebot
    from telebot.apihelper import ApiTelegramException
    
    bot = telebot.TeleBot("api-key")
    
    CHAT_ID = -100... #replace your channel id
    
    def is_subscribed(chat_id, user_id):
        try:
            response = bot.get_chat_member(chat_id, user_id)
            if response.status == 'left':
                return False
            else:
                return True
    
        except ApiTelegramException as e:
            if e.result_json['description'] == 'Bad Request: chat not found':
                return False
    
    
    
    @bot.message_handler(commands=['start'])
    def send_welcome(message):
    
        if not is_subscribed(CHAT_ID,message.chat.id):
            # user is not subscribed. send message to the user
            bot.send_message(message.chat.id, 'Please subscribe to the channel')
        else:
            bot.send_message(message.chat.id, 'You are subscribed')
    
    bot.polling()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search