Search code examples
pythonslackslack-api

Is there a way to ignore bot users when using users.info?


I am trying to get emails from users on slack. All of the user id's come from channels.info, this also includes bot user id's. When I run users.info to see the info for all the users in the channel, it won't let me get emails because the bot user's which are also passed through the API don't have an email field.

def get_users():

    url = 'https://slack.com/api/users.info'
    headers = {'Accept': 'application/x-www-form-urlencoded'}

    users = get_channel()
    result = []
    for user in users:
        payload = {
            'token': API_KEY,
            'user': user
        }
        r = requests.get(url, headers=headers, params=payload)

        if r.status_code == 200:
            result.append(r.json()['user']['profile']['email])
    return result

I am currently getting a KeyErorr with'email' because the bot users don't have an email field. Is there a way to ignore the bot user's all together. Currently all the user id's are taken from channels.info and looped through users.info, so the info is gathered for each user id from channels.info


Solution

  • To avoid the exception on the client side, you can use dictionary.get() to have it return None instead of throwing a KeyError.

    email = r.json()['user']['profile'].get('email')
    if email is not None:
       result.append(email)
    

    There is some more detail about dictionary.get() in this question and it's answers: Why dict.get(key) instead of dict[key]?