8

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!

1 Answer 1

12

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()
Sign up to request clarification or add additional context in comments.

5 Comments

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?
@BortsovBogdan I've added some example on how you would use it as if-else logic and send a message
The bot must be added as an admin to the channel in question in order for this to work.
It seems it succeeds even if the user has left the group. Inside the data you will see 'status' : 'left'
Some users get error. Bad Request: PARTICIPANT_ID_INVALID. Method is working, but not always. Who know how to fix this problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.