이 페이지는 BlueTalk(블루톡) 서버와 Python 코드로 직접 통신하는 예제를 모아둔 곳입니다.
예제들은 모두 현재 서버 구현(/upload/chat-file, /chat-file/:id, /health)을 기준으로 작성되어 있습니다.
예제 실행 전에 Python 환경에서 다음 패키지를 설치해 주세요.
pip install requests websockets
이 문서에서는 REST 예제에 집중하고, WebSocket은 개념 수준으로만 간단히 보여줍니다.
실제 실시간 채팅/DM 봇은 Node.js + socket.io-client로 구현하는 것을 추천드립니다.
Python 스크립트에서 BlueTalk 서버로 직접 파일을 업로드하고 싶을 때 사용할 수 있는 예제입니다.
예를 들어, 자동화 스크립트가 이미지를 올려 공지 채팅에 첨부하고 싶을 때 사용할 수 있습니다.
# upload_file.py
import os
import mimetypes
import requests
API_BASE = "https://server.bluetalk.kr"
BLT_SITE_KEY = "발급받은_site_key"
CHANNEL_KEY = "global"
USER_ID = "system_bot" # 예: 봇/관리자 계정
USER_KEY = "서버에서_생성한_user_key"
def upload_chat_file(local_path: str):
if not os.path.exists(local_path):
print("파일이 존재하지 않습니다:", local_path)
return None
mime_type, _ = mimetypes.guess_type(local_path)
mime_type = mime_type or "application/octet-stream"
files = {
"file": (os.path.basename(local_path), open(local_path, "rb"), mime_type),
}
data = {
"site_key": BLT_SITE_KEY,
"channel_key": CHANNEL_KEY,
"user_id": USER_ID,
"user_key": USER_KEY,
}
try:
resp = requests.post(f"{API_BASE}/upload/chat-file", files=files, data=data, timeout=15)
except Exception as e:
print("업로드 요청 중 오류:", e)
return None
if resp.status_code != 200:
print("HTTP 오류:", resp.status_code, resp.text)
return None
js = resp.json()
if not js.get("ok"):
print("업로드 실패:", js)
return None
f = js.get("file", {})
print("업로드 성공:", f)
print("파일 URL 예시:", f"{API_BASE}/chat-file/{f.get('id')}")
return f
if __name__ == "__main__":
upload_chat_file("test.png")
성공 시 {"ok": true, "file": {...}} 구조의 JSON이 반환되며,
file["id"] 값을 이용해 채팅 메시지에 첨부할 수 있습니다.
BlueTalk 서버가 정상 동작 중인지 Python으로 확인하는 간단한 헬스 체크 예제입니다.
# health_check.py
import requests
API_BASE = "https://server.bluetalk.kr"
def check_health():
try:
resp = requests.get(f"{API_BASE}/health", timeout=5)
print("Status:", resp.status_code)
print("Body :", resp.text)
except Exception as e:
print("Health check 실패:", e)
if __name__ == "__main__":
check_health()
cron이나 모니터링 시스템에서 이 스크립트를 주기적으로 실행해
응답 상태를 간단히 모니터링할 수 있습니다.
BlueTalk는 socket.io 기반 WebSocket을 사용합니다.
Python에서는 python-socketio 같은 라이브러리를 사용하면 socket.io 서버에 붙을 수 있습니다.
아래 코드는 개념만 보여주는 예제이며,
실제 이벤트 이름/페이로드는
WebSocket 이벤트 문서를 참고해 맞춰야 합니다.
# ws_client_example.py
import socketio
SERVER_ORIGIN = "https://server.bluetalk.kr" # socket.io는 http/https로 지정
BLT_SITE_KEY = "발급받은_site_key"
USER_ID = "python_bot"
NICKNAME = "파이썬봇"
USER_KEY = "서버에서_생성한_user_key"
sio = socketio.Client()
@sio.event
def connect():
print("서버 연결 완료:", sio.sid)
# 연결되면 바로 테스트 메시지 전송 (예시)
payload = {
"channel_key": "global",
"content": "[Python 봇] 테스트 메시지입니다.",
"attachment_ids": []
}
def ack(res):
print("전송 응답:", res)
sio.emit("channel:message", payload, callback=ack)
@sio.event
def disconnect():
print("서버와 연결 종료")
@sio.on("channel:message")
def on_channel_message(data):
print("[채널메시지 수신]", data)
def main():
sio.connect(
SERVER_ORIGIN,
transports=["websocket"],
auth={
"site": BLT_SITE_KEY,
"user_id": USER_ID,
"nickname": NICKNAME,
"user_key": USER_KEY
}
)
sio.wait()
if __name__ == "__main__":
main()
Python에서도 위와 같이 socket.io 클라이언트를 사용할 수는 있지만,
장기 실행 프로세스 관리 측면에서는 Node.js 기반 봇을 추천드립니다.
마지막으로, Python 백엔드(FastAPI/Django 등)에서 user_key를 생성하고
이를 HTML 템플릿의 window.SITE_KEY / window.GLOBAL_*로 넘겨
JS SDK(BlueTalk 위젯)를 초기화하는 기본 패턴입니다.
# settings.py 또는 config
import os
import hashlib
BLT_SITE_KEY = os.getenv("BLT_SITE_KEY", "발급받은_site_key")
BLT_SECRET = os.getenv("BLT_SECRET", "서버_비밀문자열")
def make_user_key(user_id: str) -> str:
payload = f"{user_id}|{BLT_SITE_KEY}|{BLT_SECRET}"
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
# FastAPI + Jinja2 예시 (핵심 부분만)
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from settings import BLT_SITE_KEY, make_user_key
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
user = request.session.get("user") if hasattr(request, "session") else None
if user:
user_id = user["id"]
nickname = user["nick"]
else:
user_id = "guest"
nickname = "손님"
user_key = make_user_key(user_id)
return templates.TemplateResponse("index.html", {
"request": request,
"blt_site_key": BLT_SITE_KEY,
"blt_user_id": user_id,
"blt_nickname": nickname,
"blt_user_key": user_key,
})
{# templates/index.html #}
<div id="bluetalk" style="height:480px;"></div>
<script src="https://bluetalk.kr/talk/bluetalk.js"></script>
<script>
window.SITE_KEY = "{{ blt_site_key }}";
window.GLOBAL_USER_ID = "{{ blt_user_id }}";
window.GLOBAL_USER_KEY = "{{ blt_user_key }}";
window.GLOBAL_NICKNAME = "{{ blt_nickname }}";
const bt = new BlueTalk({
mode: "global",
targetId: "bluetalk"
});
bt.init();
</script>
/upload/chat-file, /chat-file/:id, /health 등을 호출할 수 있습니다.make_user_key() 같은 함수를 만들어, user_id를 기반으로 안전하게 user_key를 생성해야 합니다.window.SITE_KEY / window.GLOBAL_* 값을 세팅한 뒤 new BlueTalk().init()으로 위젯을 초기화합니다.Bluetalk.init() 형태는 모두 제거하거나, 이 문서의 패턴으로 변경해야 합니다.Python 외에 PHP/Node.js 예제는 각각 PHP 예제, Node.js 예제 문서를 참고해 주세요.