[slack-sdk] 특정 채널의 전체 사용자 목록 가져오기

1.슬랙 > 특정 채널 (원하는 채널) > 채널 내 사용자 목록 정보를 가져오는 방법입니다.

워크스페이스 전체가 아닌, 개설된 (개설한) 특정 채널의 참가된 사용자 목록을 가져오는 코드 입니다.

python slack_sdk 패키지를 이용합니다. ( https://pypi.org/project/slack-sdk/ )

 

2.채널에 참가한 사용자 목록을 조회 하고, 참여한 사용자의 정보를 매칭 하기 위해 2개 API 를 사용 합니다. 

 

https://api.slack.com/methods/conversations.members
https://api.slack.com/methods/users.info

 

conversations.members API method

Retrieve members of a conversation.

api.slack.com

 

users.info API method

Gets information about a user.

api.slack.com

 

API 호출은 다음과 같습니다.

 

1. 사용자 목록을 알고 싶은 채널에 사용자 목록 가져오기 (conversations.members)
2. 가져온 각 사용자를 매칭하여 사용자의 세부 정보를 붙히기 세부 정보 조회 (users.info)
3. 채널에 존재하는 사용자와 사용자 정보 출력 

 

사용자 목록을 가져올때는 (client.conversations_members), 동일하게 limit 파라미터에 조회 할 계정 개수 지정 합니다.

 

설정을 하지 않으면 기본값은 0 입니다. (0 은 제한 없이 모두 가져온다 의미 )

기본값이 0 이므로 가져올 계정이 많으면 역시 응답 시간이 지연 될 수 있습니다.

 

테스트 시에는 10, 20 등으로  조정 하여 사용 하고 (10개, 20개만 가져온다 의미), 코드가 완성 되고 주기적인 배치 작업등으로 수집 해야 하는 경우 0 으로 사용하길 권장합니다.

 

3.작성된 코드

bot_token 에 생성한 Bot 의 토큰을 입력하고 실행합니다.

응답되는 정보는 다양한 정보가 포함되어 있습니다. 필요한 정보는 파싱 하여 사용합니다.

 

__author__ = 'https://github.com/password123456/'
__version__ = '1.0.2-230828'

import sys
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError


class Bcolors:
    Black = '\033[30m'
    Red = '\033[31m'
    Green = '\033[32m'
    Yellow = '\033[33m'
    Blue = '\033[34m'
    Magenta = '\033[35m'
    Cyan = '\033[36m'
    White = '\033[37m'
    Endc = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


def get_list_of_users_on_channel(token, channel_id):
    client = WebClient(token=token)
    try:
        # https://api.slack.com/methods/conversations.members
        # The 'limit' parameter should be adjusted to match your environment. Default 20
        # The maximum number of user lists to return. Fewer than the requested number of items may be returned
        result = client.conversations_members(channel=channel_id, limit=200)
        i = 0
        for user in result['members']:
            try:
                # https://api.slack.com/methods/users.info
                info = client.users_info(user=user).data
                if not info['user']['is_bot']:
                    i = i + 1
                    member_id = info['user']['id']
                    display_name = info['user']['name']
                    real_name = info['user']['real_name']
                    phone = info['user']['profile']['phone']
                    email = info['user']['profile']['email']
                    title = info['user']['profile']['title']

                    if not member_id:
                        member_id = 'null'
                    elif not display_name:
                        display_name = 'null'
                    elif not real_name:
                        real_name = 'null'
                    elif not phone:
                        phone = 'null'
                    elif not email:
                        email = 'null'

                    print(f'{i},{real_name},{display_name},{title},{member_id},{email},{phone}')
            except SlackApiError as e:
                print(f'{Bcolors.Yellow}- Api Error:: {e} {Bcolors.Endc}')
    except SlackApiError as e:
        print(f'{Bcolors.Yellow}- Api Error:: {e} {Bcolors.Endc}')


def main():
    bot_token = 'slack_apps_oauth_token(bot_token)'
    channel = 'Channel number for which you want to know the list of users'

    get_list_of_users_on_channel(bot_token, channel)


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.exit(0)
    except Exception as e:
        print(f'{Bcolors.Yellow}- ::Exception:: Func:[{__name__.__name__}] '
              f'Line:[{sys.exc_info()[-1].tb_lineno}] [{type(e).__name__}] {e}{Bcolors.Endc}')

 

4.결과 보기

1,Luke Skywalker,Jedi Knight,U01...GS,luke@......
2,Han Solo,Smuggler,U01...GS,han@.........
3.Princess Leia Organa,Rebel Leader,U01...GS,leia@.....
4,Darth Vader (Anakin Skywalker),Sith Lord,U01...GS,darth@.......
5,Obi-Wan Kenobi,Jedi Master,U01...GS,obiwan@........

 

5.유의 사항

채널의 사용자 목록을 확인 하기 위해 봇은 해당 채널에 참가 되어 있어야 합니다.

 

{ "ok": false, "error": "not_in_channel" } 응답이 발생 한다면,  봇이 해당 채널에 참가 되어 있는지 확인 합니다. 참가 되지 않았다면 추가 합니다.

 

 

봇이 채널에 참여 되어 있는데 코드가 동작 되지 않는다면, API 실행시 필요한 권한을 확인 합니다.

 

번호  API 필요 권한 API 정보
1  conversations.members channels:read
groups:read
im:read
mpim:read
https://api.slack.com/methods/conversations.members
2  users.info users:read https://api.slack.com/methods/users.info

 

 

API 스펙에 정의된 필요 권한을 넣었으나 되지 않는 경우는,  API 에러 에서 출력되는 필요 권한 (무슨 권한이 필요하다고 표시 됩니다.) 을 추가 합니다.

 

슬랙 API 문서에는 API 를 응용, 구현 했을때 필요 권한이 충분히 설명 되어 있지 않는 경우가 있습니다.

 

예를 들면, 채널의 정보를 접근 하기 위해 channels:read 를 추가 하였고, 봇도 join 하였는데, 실행이 되지 않고, API 응답에서 channels:join 을 요구 하는 경우 > channels:join 권한 추가 > 해결