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!
How to check if a user is subscribed to a specific Telegram channel (Python / PyTelegramBotApi)?
Asked Answered
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()
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 message –
Beltz
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.