'how to check bot-user is member of specific chat or telegram channel? python-telegram-bot

How to check bot-user is member of specific channel or chat member?
I'm new learner of python-telegram-bot. So , Please give me full answer. Ps. I'm using python-telegram-bot I have used method: get_chat_member().

def is_member(update, context):
    userid = update.effective_user.id
    chatid = "@chatusername"
    try:
       res = context.bot.get_chat_member(chat_id=chatid, user_id=userid)
       if res.status in ['member', 'administrator']:
           return True
    except Exception as e:
       return False

this function only works on some chat and telegram channels but sometimes I encounter an error (telegram.error.BadRequest: User not found) . But I am sure the user is a member of the telegram channel If you have a better solution, share it with us



Solution 1:[1]

If you wanna find out a member in a group, or somewhere else, First you need to know the target group id. And then you gotta see the target user ID.

Let's retrieve this information when the user sends a message to the bot.

def check_user_in_the_group(update,context):

    group_chat_id = update.message.chat.id #replace this with group id number, if you already know it
    user_id = update.message.from_user.id #replace this with user id number, if you already know it


    check = context.bot.getChatMember(chat_id,user_id) #check if the user exist in the target group

    if check: #If check variable isn't null, user is in the group
        print('user is in the chat')
    else:
        print('Not found')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1