통합 슬랙api 전송(텍스트, 이미지)

2023. 4. 28. 21:20프로젝트/슬랙 봇 비서 만들기

import requests

def send_slack_image(api_token, channel, image_path=None, message=None):
    if image_path:
        url = "https://slack.com/api/files.upload"
        headers = {
            "Authorization": f"Bearer {api_token}"
        }
        #  HTTP 요청을 보낼 때 인증 헤더를 설정
        # 인증 헤더는 API 호출에 필요한 인증 정보를 제공하는 데 사용되며,
        # 이 경우 API 호출에 필요한 Bearer 토큰을 전달
        # Bearer 토큰은 OAuth 2.0 인증 방식에서 사용되는 액세스 토큰의 한 형태
        # OAuth 2.0은 API 호출에 필요한 권한 부여 및 인증을 처리하기 위한 프로토콜
        # Bearer 토큰은 OAuth 2.0에서 사용되는 토큰 중 하나로, API 호출을 인증하는 데 사용
        # 즉, API 서버는 Authorization 헤더에서 Bearer 토큰 값을 추출하고, 해당 토큰이 유효한지 확인한 후에 API 호출을 승인
    
        
        payload = {
            "channels": channel,
        }
        # payload는 일반적으로 HTTP 요청에서 바디에 전송하는 데이터를 담는 변수
        
        if message:
            payload["initial_comment"] = message
		# Slack API를 사용하여 Slack 채널로 메시지를 전송할 때, payload 변수에 추가로 메시지를 포함
    	# https://api.slack.com/methods/files.upload


        with open(image_path, "rb") as image_file:
            files = {
                "file": image_file
            }
            response = requests.post(url, headers=headers, params=payload, files=files)
            # with 구문은 일반적으로 파일 객체를 열 때 많이 사용
            # with 구문을 사용하여 파일 객체를 열면, 파일을 사용한 후에 자동으로 파일 객체를 닫음
            # "rb" 모드로 이미지 파일을 열어서 image_file 변수에 할당
            # 업로드할 이미지 파일을 files 딕셔너리에 추가
            # 파일 객체를 그대로 전달하여 파일을 업로드 
            # requests 라이브러리를 사용하여 Slack API에 POST 요청을 보내고, 이를 response 변수에 할당
            # 요청에 필요한 headers, params, files 등의 정보를 함께 전송
            # headers는 인증 토큰 등의 정보를 전송
            # params는 Slack API에서 요구하는 요청 파라미터를 전송
            # files는 이미지 파일을 전송
    
    else:
        url = "https://slack.com/api/chat.postMessage"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_token}"
        }
        payload = {
            "channel": channel,
            "text": message
        }
        response = requests.post(url, headers=headers, json=payload)

    print(response.json())

# 사용 예제
api_token = "토큰값" # 실제 토큰으로 변경하세요
channel = "#금융"  # 전송할 채널 이름
image_path = None  # 전송할 이미지의 경로 (없으면 None)
message = "이미지 없을떄 메시지"  # 보낼 메시지 (선택 사항)

send_slack_image(api_token, channel, image_path, message)

 

이미지 or 텍스트 slack api 전송

728x90