이 페이지는 BlueTalk(블루톡) 서버와 Node.js 코드로 직접 통신하는 예제를 모아둔 곳입니다.
예제들은 모두 현재 서버 구현(/upload/chat-file, /chat-file/:id, WebSocket auth 등)을 기준으로 작성되어 있습니다.
예제 실행 전에 Node.js 프로젝트에서 다음 패키지를 설치해 주세요.
npm install axios form-data socket.io-client
실제 서비스에서는 .env 또는 설정 파일에 BLT_SITE_KEY, BLT_SECRET 등을 보관하시고,
예제 코드에서는 이해를 돕기 위해 일부 값을 직접 하드코딩해서 보여드립니다.
Node.js 서버/백엔드에서 BlueTalk 서버로 파일을 업로드하고 싶을 때 사용할 수 있는 예제입니다.
예를 들어, 관리도구/봇이 이미지를 올려서 공지 채팅에 붙이고 싶을 때 사용할 수 있습니다.
// upload_file.js
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');
// BlueTalk 서버 주소 (예시)
const API_BASE = 'https://server.bluetalk.kr';
// 사이트별 설정
const BLT_SITE_KEY = '발급받은_site_key';
const CHANNEL_KEY = 'global';
// 이 예제에서는 봇/관리자 계정을 가정
const USER_ID = 'system_bot';
const USER_KEY = '서버에서_생성한_user_key';
async function uploadChatFile(localFilePath) {
const fileStream = fs.createReadStream(localFilePath);
const form = new FormData();
form.append('file', fileStream);
form.append('site_key', BLT_SITE_KEY);
form.append('channel_key', CHANNEL_KEY);
form.append('user_id', USER_ID);
form.append('user_key', USER_KEY);
try {
const rsp = await axios.post(API_BASE + '/upload/chat-file', form, {
headers: form.getHeaders()
});
const data = rsp.data;
if (!data.ok) {
console.error('업로드 실패:', data.reason || data.error || data);
return null;
}
const f = data.file; // { id, type, name, size, mime }
console.log('업로드 성공:', f);
console.log('다운로드 URL 예시:', API_BASE + '/chat-file/' + f.id);
return f;
} catch (err) {
console.error('업로드 중 오류:', err.message);
return null;
}
}
// 실행 예시
if (require.main === module) {
const testPath = path.join(__dirname, 'test.png');
uploadChatFile(testPath).then(() => process.exit(0));
}
응답이 { ok: true, file: { ... } } 구조라는 점에 주의하세요.
에러 시에는 { ok:false, reason:'FILE_REQUIRED' } 같은 형태로 reason 필드가 들어옵니다.
Node.js 코드에서 socket.io-client를 이용해 BlueTalk 서버에 접속하고,
채팅 메시지를 주고받는 예제입니다.
예: 봇 계정이 공지 메시지를 보내거나, 특정 이벤트에 따라 자동 답변을 보내는 용도.
// bot_client.js
const { io } = require('socket.io-client');
const SERVER_ORIGIN = 'wss://server.bluetalk.kr';
// 사이트별 설정
const BLT_SITE_KEY = '발급받은_site_key';
// 봇 계정 정보
const BOT_USER_ID = 'system_bot';
const BOT_NICK = '공지봇';
const BOT_USER_KEY = '서버에서_생성한_user_key';
const socket = io(SERVER_ORIGIN, {
transports: ['websocket'],
auth: {
site: BLT_SITE_KEY,
user_id: BOT_USER_ID,
nickname: BOT_NICK,
user_key: BOT_USER_KEY
// 필요하면 avatar_url, admin_key 등 추가 가능
}
});
socket.on('connect', () => {
console.log('BlueTalk 서버 연결 완료, socket.id =', socket.id);
// 예: 글로벌 채널에 공지 메시지 보내기
const payload = {
channel_key: 'global',
content: '[공지] 봇에서 테스트 메시지를 보냅니다.',
attachment_ids: [] // 파일 첨부가 있으면 /upload/chat-file로 업로드 후 파일 id를 넣습니다.
};
socket.emit('channel:message', payload, (res) => {
if (!res || !res.ok) {
console.log('메시지 전송 실패:', res && res.error);
return;
}
console.log('메시지 전송 성공:', res);
});
});
socket.on('disconnect', (reason) => {
console.log('연결 종료:', reason);
});
// 채널/글로벌 메시지 수신 예제
socket.on('channel:message', (msg) => {
console.log('[채널메시지] channel=', msg.channel_key, 'content=', msg.content);
});
socket.on('global:message', (msg) => {
console.log('[글로벌메시지] channel=', msg.channel_key, 'content=', msg.content);
});
실제 이벤트 이름 및 payload 구조는
WebSocket 이벤트 문서에 따라 달라질 수 있습니다.
위 코드는 개념 예제이므로, 실제 서버 이벤트 명칭과 맞는지 확인 후 사용해 주세요.
DM(1:1 메시지) 관련 socket.io-client 예제입니다.
실제 세부 이벤트 이름/필드는 서버 버전/정책에 따라 다를 수 있으니,
DM 기본 예제와 함께 참고하시기 바랍니다.
// dm_bot.js
const { io } = require('socket.io-client');
const SERVER_ORIGIN = 'wss://server.bluetalk.kr';
const BLT_SITE_KEY = '발급받은_site_key';
const BOT_USER_ID = 'dm_bot';
const BOT_NICK = 'DM봇';
const BOT_USER_KEY = '서버에서_생성한_user_key';
const socket = io(SERVER_ORIGIN, {
transports: ['websocket'],
auth: {
site: BLT_SITE_KEY,
user_id: BOT_USER_ID,
nickname: BOT_NICK,
user_key: BOT_USER_KEY
}
});
socket.on('connect', () => {
console.log('DM 봇 소켓 연결됨:', socket.id);
// 예: 특정 dm_key에 메시지 보내기 (dm_key는 서비스 정책에 따라 관리)
const DM_KEY = 'dm_123456789';
socket.emit('dm:message', {
dm_key: DM_KEY,
content: '안녕하세요, DM봇입니다.',
attachment_ids: []
}, (res) => {
if (!res || !res.ok) {
console.log('DM 전송 실패:', res && res.error);
return;
}
console.log('DM 전송 성공:', res);
});
});
// DM 수신 예제
socket.on('dm:message', (msg) => {
console.log('[DM 수신] dm_key=', msg.dm_key, 'from=', msg.from_user_id, 'content=', msg.content);
});
DM 세션(dm_key) 생성/승인/목록 조회 등은
서비스 정책과 서버 구현에 따라 달라집니다.
이 예제는 socket.io-client로 이벤트만 주고받는 구조를 보여주는 참고용입니다.
BlueTalk 서버가 정상 동작 중인지 확인하고 싶을 때 사용할 수 있는 헬스 체크 예제입니다.
// health_check.js
const axios = require('axios');
const API_BASE = 'https://server.bluetalk.kr';
async function checkHealth() {
try {
const rsp = await axios.get(API_BASE + '/health');
console.log('Health Check 응답:', rsp.data);
} catch (err) {
console.error('Health Check 실패:', err.message);
}
}
if (require.main === module) {
checkHealth().then(() => process.exit(0));
}
운영 환경에서는 이 헬스 체크를 모니터링 시스템(예: cron, 시스템 모니터)과 연결해 장애 여부를 확인하는 용도로 사용할 수 있습니다.
/upload/chat-file, /chat-file/:id, /health 등을 호출할 수 있습니다.wss://server.bluetalk.kr에 연결해 이벤트를 주고받습니다.auth.site / auth.user_id / auth.nickname / auth.user_key를 정확히 전달해야 합니다.Bluetalk.init(...) 같은 옛 전역 함수는 Node 환경에서는 사용되지 않습니다. 항상 axios / socket.io-client를 직접 사용하세요.Node 외에 다른 언어(PHP, Python 등) 예제는 각각 PHP 예제, Python 예제 문서를 참고해 주세요.