Python/Python__works

python slacker

말하는감자 2020. 6. 11. 16:22

1. python slack API - 준비


1. bot 만들고 token 얻기

https://api.slack.com/apps
  1. 위의 주소로 접속
  2. Create New App 클릭
  3. App Name 입력 -> Development Slack Workspace 선택 -> Create App 클릭
  4. Your Apps 클릭 -> 방금 생성한 bot 클릭
  5. Verification Token 복사

2. slacker 설치

pip install slacker

2. python slack API - 실제로 사용해보기


1. 공통 부분 작성

from slacker import Slacker
token = "Verification Token"
slack = Slacker(token)

2. 채널 리스트 얻어오기


channel_list = slack.channels.list()
print(channel_list)

1. 채널 리스트의 값을 읽어보기
  • channel_list의 response는 body / error / raw / successful 이렇게 4가지 부분으로 나누어져서 들어옵니다.
  • body 는 dictionary 형태입니다.
    • body 내부는 ok / channels / warning / response_metadata로 들어옵니다.
    • ok는 bool(True / False)
    • channels 는 list로 들어옵니다.
      • 각 list의 내부에는 dictionary 형태로 값이 들어있습니다.
      • id / name / is_channel / created 등등등이 들어있습니다.
      • 이 안에 들어있는 members 안에는 채널에 참여한 사람들의 목록이 list로 들어옵니다.
        • list 안의 값들은 실제 이름이 아닌 id값(ex:UK92X24AC)으로 들어있습니다.
          <class 'dict'>: {'id': '아이디', 'name': '스트링으로 된 채널 이름', 'is_channel': True, 'created': 숫자, 'is_archived': False, 'is_general': False, 'unlinked': 0, 'creator': 생성한사람의아이디, 'name_normalized': 스트링으로된채널이름, 'is_shared': False, 'is_org_shared': False, 'is_member': False, 'is_private': False, 'is_mpim': False, 'members': ['참여자1', '참여자2'], 'topic': {'value': '', 'creator': '', 'last_set': 0}, 'purpose': {'value': '', 'creator': '', 'last_set': 0}, 'previous_names': [], 'num_members': 참여자숫자}
    • warning은 string
      • 'method_deprecated'(ㅠㅠ..)
    • response_metadata는 이 api가 2021년 초반에 사라진다고 나오는군요. 내년에 이 문서를 다시써야 한다는 뜻입니다(ㅠㅠ)
  • raw는 response가 string 형태로 담겨있습니다.
  • successful 은 bool(True / False) 형태로 담겨있습니다.

2. 얻어온 채널 이름을 이용해서 슬랙안의 대화내용 읽어오기
  • channel list에서 가져온 아이디를 하나 골라줍니다.
    id = channel_list.body['channels'][0]['id']
  • 가져온 아이디를 이용해서 대화 내용을 읽어옵니다
    msgs = slack.conversations.history(id)

3. 슬랙 대화내용의 값을 읽어보기

  • 대화 내용은 채널 리스트와 비슷한 형태로 들어옵니다.
  • body / error / raw / successful
  • body 내부의 messages 안에 list 형식으로 대화 내용들이 담겨 있습니다.
  • 각 대화 내용은 dictionary 형태로 담겨있고 client_msg_id, type, 발신자 등등등의 값이 들어있습니다.
    <class 'dict'>: {'client_msg_id': '뭔가어엄청긴아이디', 'type': 'message', 'text': 'ㅋㅋㅋㅋ', 'user': '발신자', 'ts': '뭔지모르겠음', 'team': '뭔지모르겠음', 'blocks': [{'type': 'rich_text', 'block_id': 'DZz', 'elements': [{'type': 'rich_text_section', 'elements': [{'type': 'text', 'text': 'ㅋㅋㅋㅋ'}]}]}]}

4. 슬랙으로 메세지 보내기


slack_message = [{
        'color': '#2B76Ec',
        'title': 'titles',
        'text': 'test_msg'
    }]
slack.chat.post_message(id, text='상단의 title 메세지', attachments=slack_message)

3. 정리


from slacker import Slacker
token = "Verification Token"
slack = Slacker(token)
channel_list = slack.channels.list()
id = channel_list.body['channels'][0]['id']
channel_msg = slack.conversations.history(id)
slack_message = [{
        'color': '#2B76Ec',
        'title': 'titles',
        'text': 'test_msg'
    }]
slack.chat.post_message(id, text='상단의 title 메세지', attachments=slack_message)

'Python > Python__works' 카테고리의 다른 글

실행 중인 메서드이름, 파일 이름  (0) 2020.09.24
fetchone() 분실 사건  (0) 2020.09.22
no module named mysqldb  (0) 2020.03.30
sqlalchemy  (0) 2020.03.04
formatter  (0) 2020.02.26