공부한 내용 정리하는 공간입니다.
틀린 내용이 있을 수 있습니다.
모든 지적, 첨언 환영합니다.
오늘의 코드
1. Webhook 방식으로 slack에 텍스트 메세지 전송하기
2. Slack API 를 이용하여 메세지 전송하기
3. Slack API 를 이용하여 파일 전송하기
import requests
slack_url = "사용자의 웹훅 URL"
def sendSlackWebHook(strText):
headers = {
"Content-type": "application/json"
}
data = {
"text": strText
}
res = requests.post(slack_url, headers=headers, json=data)
if res.status_code == 200:
return "OK"
else:
return "Error"
print(sendSlackWebHook("Webhook을 이용한 슬랙 메시지 전송테스트"))
SLACK_API_TOKEN = "사용자의 OAuth Tokens"
SLACK_CHANNEL = "사용자의 채널ID"
def send_message(channel, text):
client = WebClient(token=SLACK_API_TOKEN)
try:
response = client.chat_postMessage(
channel=channel,
text=text
)
print("Message sent successfully:", response["message"]["text"])
except SlackApiError as e:
print("Error sending message:", e.response["error"])
send_message(SLACK_CHANNEL, "Hello, this is a test message from Slack API!")
def upload_file(channel, file_path, message):
client = WebClient(token=SLACK_API_TOKEN)
try:
response = client.files_upload_v2(
channel=channel,
file=file_path,
initial_comment=message
)
print("File uploaded successfully:", response["file"]["name"])
except SlackApiError as e:
print("Error uploading file:", e.response["error"])
upload_file(SLACK_CHANNEL, "image1.jpg", "Here is the file you requested!")
requests.post()
requests 라이브러리에서 제공되는 HTTP POST 요청 함수
웹 서버에 데이터를 보내는 데 사용
requests.post(요청할 url, HTTP 요청 헤더, 서버에 보내는 데이터) 형태로 사용
JSON 형태로 데이터를 보낼 경우 Content-Type: application/json 자동 설정
서버의 응답(상태 코드, 응답한 텍스트 등)을 반환
응답 상태 코드
requests.post()의 결과로 반환되는 서버의 응답
200 : 요청 성공
400 : 클라이언트 오류
500 : 서버 오류
WebClient(token=사용자 slack OAuth 토큰)
slack API와 상호작용하는 데 필요한 객체를 생성하는 함수
생성된 객체로 slack과의 연결을 설정하고, 메세지 전송, 파일 업로드 등 작업 수행 가능
.chat_postMessage(channel='slack 사용자 ID', text='전송할 텍스트')
지정한 slack 채널에 메세지를 전송하는 메서드
WebClient 객체를 통해 호출
응답 객체 : 성공 여부, 메세지가 전송된 채널의 ID, 타임스탬프, 메세지 세부정보
try:
except A as B:
try 블록에서 오류가 발생하면 except 블록에서 처리
except 예외 종류(A) as 변수(B) 의 형태로 사용
A 종류의 예외를 B에 저장하여 활용
딕셔너리[ ][ ]
중첩된 딕셔너리에서 첫 번째 [ ]로 외부 딕셔너리에서 값을 찾고, 그 값이 딕셔너리일 경우 두 번째 [ ]로 내부 딕셔너리에서 값을 찾는 방식
.files_upload_v20(channel='slack 사용자 ID', file='전송할 파일', initial_comment='파일과 함께 채널에 표시될 텍스트')
지정한 slack 채널에 파일을 업로드하는 메서드
WebClient 객체를 통해 호출
응답 객체 : 성공 여부, 파일 정보
오늘의 코드
1. Webhook 방식으로 slack에 텍스트 메세지 전송하기
2. Slack API 를 이용하여 메세지 전송하기
3. Slack API 를 이용하여 파일 전송하기
import requests
slack_url = "사용자의 웹훅 URL"
def sendSlackWebHook(strText):
headers = {
"Content-type": "application/json"
}
data = {
"text": strText
}
res = requests.post(slack_url, headers=headers, json=data)
if res.status_code == 200:
return "OK"
else:
return "Error"
print(sendSlackWebHook("Webhook을 이용한 슬랙 메시지 전송테스트"))
SLACK_API_TOKEN = "xoxb-8301729539731-8324659490000-t5LDznLeZO9xJwbLGXpyHXUT"
SLACK_CHANNEL = "C0898F78741"
def send_message(channel, text):
client = WebClient(token=SLACK_API_TOKEN)
try:
response = client.chat_postMessage(
channel=channel,
text=text
)
print("Message sent successfully:", response["message"]["text"])
except SlackApiError as e:
print("Error sending message:", e.response["error"])
send_message(SLACK_CHANNEL, "Hello, this is a test message from Slack API!")
def upload_file(channel, file_path, message):
client = WebClient(token=SLACK_API_TOKEN)
try:
response = client.files_upload_v2(
channel=channel,
file=file_path,
initial_comment=message
)
print("File uploaded successfully:", response["file"]["name"])
except SlackApiError as e:
print("Error uploading file:", e.response["error"])
upload_file(SLACK_CHANNEL, "image1.jpg", "Here is the file you requested!")
오늘의 코드 결과
결과 첨부 필요
오늘의 코드 설명
1. Webhook 방식으로 slack에 텍스트 메세지 전송하기
slack_url = "사용자의 웹훅 URL"
slack에서 발급받은 weebhook URL을 slack_url에 저장
def sendSlackWebHook(strText):
매개변수 strText가 있는 함수 sendSlackWebHook 정의
headers = {"Content-type": "application/json"}
data = {"text": strText}
딕셔너리 headers, data 정의
res = requests.post(slack_url, headers=headers, json=data)
slack_url에게 headers, json을 포함해서 POST 요청을 보내고 응답을 res에 저장
if res.status_code == 200:
slack_url에서 받은 응답이 200일 경우 실행
요청 성공
print(sendSlackWebHook("Webhook을 이용한 슬랙 메시지 전송테스트"))
함수 sendSlackWebHook의 값을 출력
>strText="Webhook을 이용한 슬랙 메시지 전송테스트"
2. Slack API 를 이용하여 메세지 전송하기
SLACK_API_TOKEN = "사용자의 Aouth Tokens"
SLACK_CHANNEL = "사용자의 채널ID"
slack API를 사용하기위한 토큰과 채널 이름 설정
def send_message(channel, text):
매개변수 channel, text가 있는 함수 send_message 정의
client = WebClient(token=SLACK_API_TOKEN)
slack API의 응답 데이터를 client에 저장
try:
response = client.chat_postMessage(
channel=channel,
text=text
)
함수 send_message의 매개변수 channel을 채널로 지정하고, text를 내용으로 지정해서 사전에 지정한 slack 채널에 메세지를 전송하고 응답 데이터(전송 결과)를 response에 저장
오류가 발생하면 except 블록으로 넘어감
print("Message sent successfully:", response["message"]["text"])
>response=Slack API에서 받은 응답 데이터
> response["message"]=전송된 메세지의 세부 정보를 담고있는 딕셔너리
> response["message"]["text"]=메세지의 내용
except SlackApiError as e:
오류 발생 시 SlackApiError라는 예외를 잡아서 내용을 e에 저장
print("Error sending message:", e.response["error"])
slack API의 오류 메세지를 출력
오류 메세지를 보고 어떤 오류가 발생했는지 알 수 있음
send_message(SLACK_CHANNEL, "Hello, this is a test message from Slack API!")
>channel=SLACK_CHANNEL=사용자의 slack ID
>text="Hello, this is a test message from Slack API!"
사용자의 slack ID를 채널로 "Hello, this is a test message from Slack API!" 메세지를 전송하고 전송 결과를 response에 저장
전송에 성공하면 response 에서 메세지 내용을 가져와서 "Message sent successfully: Hello, this is a test message from Slack API!" 출력
3. Slack API 를 이용하여 파일 전송하기
def upload_file(channel, file_path, message):
매개변수 channel, file_path, message가 있는 함수 upload_file 정의
try:
response = client.files_upload_v2(
channel=channel,
file=file_path,
initial_comment=message
)
함수 upload_file의 매개변수 channel을 채널로 지정하고
file_path을 전송할 파일로 지정하고
message를 전송할 파일에 대해 남길 메세지로 지정해서
사전에 지정한 slack 채널에 파일과 메세지를 전송하고 응답 데이터(전송 결과)를 response에 저장
오류가 발생하면 except 블록으로 넘어감
print("File uploaded successfully:", response["file"]["name"])
>response=Slack API에서 받은 응답 데이터
> response["file"]=전송된 파일의 세부 정보를 담고있는 딕셔너리
> response["file"]["name"]=파일의 이름
except SlackApiError as e:
오류 발생 시 SlackApiError라는 예외를 잡아서 내용을 e에 저장
upload_file(SLACK_CHANNEL, "image1.jpg", "Here is the file you requested!")
>channel=SLACK_CHANNEL=사용자의 slack ID
>file_path="image1.jpg"
>message="Here is the file you requested!"
사용자의 slack ID를 채널로 "image1.jpg" 파일과 "Here is the file you requested!" 메세지를 전송하고 전송 결과를 response에 저장
전송에 성공하면 response 에서 파일 이름을 가져와서 " File uploaded successfully: Here is the file you requested!" 출력