끄적끄적 인턴생활 (2020)/슬랙봇 만들기(2020)

slack api & azure 스토리지 계정 api 연동 그리고 슬랙 출력

jellylucy 2021. 12. 28. 13:15

 

저번주에 slack api로 출력문/ 스레드 출력했는데

안봤다고 바로 코드 이해 못함. ㅋㅋㅋㅋㅋㅋㅋㅋㅋ


slack api 연동해 사용자 출력. bot 출력문 생성하기 (slack 회색코드문)

출처 입력

1. import 문

import json
import requests
from pandas.io.json import json_normalize
# 라이브러리 임포트하기
import schedule
import time
 

request가 아마 api관련 모듈로 기억한다.

import os, uuid
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__
 

이거는 azure관련 import 문.

 

2. slack bot 생성시 발급받은 토큰 문자열

slack_token = ['토큰문자열']
# Token 문자열 변수 만들기 

ChannelName = "bot_test"

URL ='https://slack.com/api/conversations.list'
# 채널 조회 API 메소드 : conversations.list

# 파라미터(매개변수)
params = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'token': slack_token
}
 

: 변수 네개 만듦.

slack_token, Channel_name, URL(api조회하는메소드), params

# API 호출
res = requests.get(URL, params = params)

channel_list = json_normalize(res.json()['channels'])
channel_id = list(channel_list.loc[channel_list['name'] == ChannelName, 'id'])[0]

print(f"""
채널 이름: {ChannelName}
채널 id: {channel_id}
""")
 

: request.get으로 slack의 api를 얻는다

: 모르겠음.. 그냥 끌어다써서 ㅋㅋㅋㅋㅋㅋ

json.nomalize이용

channel list를 만들고 list 변수에 channelname을 넣고 [0]원소에 channel_id를 넣음


# 글 내용
Text = "slack bot test"

# 채널 내 문구 조회 API 메소드: conversations.list
URL = 'https://slack.com/api/conversations.history'

# 파라미터
params = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'token': slack_token,
    'channel': channel_id
         }
 

: 변수 3개를 만듦

Text, URL, params를 만든다

 

# API 호출
res = requests.get(URL, params = params)    

chat_data = json_normalize(res.json()['messages'])
chat_data['text'] = chat_data['text'].apply(lambda x: x.replace("\xa0"," "))
ts = chat_data.loc[chat_data['text'] == Text, 'ts'].to_list()[0]

print(f"""
글 내용: {Text}
ts: {ts}
""")
 

:requests.get으로 api를 찾고

json.nomalize이용.

chat_data에 ts라는 변수이용해 chat_data['text'] == Text저장. [0]에 저장.

# Bot으로 등록할 댓글 메시지 문구
message = f"""
테스트 메시지 입니다.
"""

# 파라미터
data = {'Content-Type': 'application/x-www-form-urlencoded',
        'token': slack_token,
        'channel': channel_id, 
        'text': message,
        'reply_broadcast': 'True', 
        'thread_ts': ts
        } 

# 메시지 등록 API 메소드: chat.postMessage
URL = "https://slack.com/api/chat.postMessage"
res = requests.post(URL, data=data)
 

:message, data(이 안에 'thread_ts' 가 스레드로 가는걸 의미 ), URL 만들고

res으로 requests.post!

 


실행결과