PyTelegramBotApi中get_chat_member()函数异常:始终返回True无法校验用户频道订阅状态
Hey there, let's break down why your subscription check always returns True—the core problem is how you're interpreting the result of get_chat_member().
Right now, your code assumes that any successful call to get_chat_member() means the user is subscribed, but that's not accurate. The function will return a ChatMember object even if the user has left the channel, been kicked, or is just not a member (for public channels, it won't throw an error for non-members—it'll just return a status of left).
Here's the corrected approach:
We need to check the status field of the ChatMember object returned by get_chat_member(). A user is considered subscribed if their status falls into one of these valid states:
'member'(regular channel subscriber)'administrator'(channel admin)'creator'(channel owner)
Updated Code
import telebot from telebot import types from telebot.apihelper import ApiTelegramException bot = telebot.TeleBot('<TOKEN>') group_id = <Group id> # Remember to prefix with -100 for supergroups/channels @bot.message_handler(commands=['start']) def start(message): is_user_subscribed = is_subscribed(group_id, message.from_user.id) print(is_user_subscribed) 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: chat_member = bot.get_chat_member(chat_id, user_id) # Validate if the user's status counts as subscribed return chat_member.status in ['member', 'administrator', 'creator'] except ApiTelegramException as e: # Handle cases where we can't access member info (e.g., private channel + non-member) if e.result_json['description'] == 'Bad Request: user not found': return False # Fallback to False for any other unexpected errors return False bot.polling(none_stop=True)
Key Details to Keep in Mind:
- Chat ID Format: Double-check your
group_id—Telegram channels/supergroups require an ID prefixed with-100(you can get this using bots like @getidsbot). - Comprehensive Status Checks: By validating the status field, we cover both public channels (where non-members return
leftstatus) and private channels (where non-members trigger a "user not found" error). - Robust Exception Handling: We keep the exception catch for edge cases and add a fallback return
Falseto handle any unexpected API errors gracefully.
内容的提问来源于stack exchange,提问作者JukeeX




