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

1

7

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!

Pernas answered 18/10, 2020 at 14:31 Comment(0)
B
10

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()
Beltz answered 18/10, 2020 at 14:42 Comment(3)
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?Pernas
@BortsovBogdan I've added some example on how you would use it as if-else logic and send a messageBeltz
The bot must be added as an admin to the channel in question in order for this to work.Clie

© 2022 - 2024 — McMap. All rights reserved.