[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+169 -61
View File
@@ -2,89 +2,197 @@
id: wiki-2026-0508-slack-bot-development
title: Slack Bot Development
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DEV-SLACK-BOT-001]
aliases: [Slack App, Slack Integration, Bolt SDK]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [development, automation, slack, chatbot, slack-api, webhook, bot-development, collaboration]
confidence_score: 0.9
verification_status: applied
tags: [slack, bot, integration, automation]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: bolt-js
---
# Slack Bot Development (슬랙 봇 개발)
# Slack Bot Development
## 📌 한 줄 통찰 (The Karpathy Summary)
> "협업의 중심지인 슬랙에 '지능형 에이전트'를 상주시켜, 번거로운 반복 작업을 자동화하고 팀의 생산성을 실시간으로 가속하라" — 슬랙 API를 활용하여 사용자의 메시지에 응답하거나 이벤트를 감지하여 특정 작업을 수행하는 자동화 프로그램 개발 기법.
## 한 줄
> **"매 Slack workspace 에 자동화/통합 logic 을 추가하는 app 개발"**. 매 2014 Slack API 출시, 매 2020 Bolt SDK 정식, 매 2026 현재 Block Kit 2.0 + AI Assistant App + Slack Connect 가 표준. Event-driven + interactive UI 의 양축.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Event-driven Interaction and Workflow Integration" — 슬랙의 이벤트 API(가입, 메시지 등)를 수신하고, 봇 토큰(Bot Token)을 사용해 채널에 응답하거나 인터랙티브 버튼/모달을 통해 사용자 입력을 받아 업무 워크플로우를 자동화하는 패턴.
- **주요 구성 요소:**
- **Slack API:** Web API (봇이 메시지 전송), [[Events|Events]] API (슬랙 내 사건 감지).
- **Socket Mode:** 복잡한 방화벽 설정 없이 로컬에서도 봇을 테스트할 수 있는 통신 방식.
- **App Home:** 사용자별 맞춤 정보를 보여주는 봇 전용 공간.
- **Slash Commands:** `/`로 시작하는 명령어를 통한 서비스 호출.
- **의의:** 알림 모니터링, 승인 프로세스 자동화, 사내 데이터 조회 등 파편화된 업무 툴들을 채팅창 안으로 통합하여 소통 비용을 획기적으로 절감함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 메시지만 주고받던 초기 형태에서 벗어나, 이제는 거대 언어 모델(LLM)과 결합하여 복잡한 질문에 답하고 코드를 작성하거나 회의록을 요약해주는 'AI 비서' 수준의 지능형 봇으로 진화함.
- **정책 변화:** Antigravity 프로젝트는 가드닝 진행 상황 및 장애 알림을 실시간으로 팀에 공유하기 위해, 프로젝트 전용 슬랙 봇을 구축하여 운영 효율을 극대화함.
### 매 App 구성요소
- **Bot user**: identity for messaging.
- **Event subscriptions**: 매 message, reaction, app_mention 등.
- **Slash commands**: `/deploy`, `/oncall`.
- **Interactive components**: buttons, modals, select menus.
- **Block Kit**: rich UI JSON.
- **OAuth scopes**: `chat:write`, `channels:read`, etc.
## 🔗 지식 연결 (Graph)
- [[Process-Automation-with-AI|Process-Automation-with-AI]], [[Natural-Language-Processing|Natural-Language-[[Processing]]-NLP]], API-Design-[[Principles|Principles]], [[Shadowing-and-Observability|Shadowing-and-Observability]]
- **Raw Source:** 10_Wiki/Topics/AI/Slack-Bot-Development.md
### 매 host 모델
- **HTTP (request URL)**: AWS Lambda, Cloudflare Worker.
- **Socket Mode**: WebSocket — internal tools, no public URL.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. CI/CD notification + interactive deploy approval.
2. On-call escalation bot.
3. AI assistant (RAG over Slack history).
4. Survey / standup automation.
5. Customer support triage.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Bolt SDK basic
```ts
import { App } from '@slack/bolt';
## 🧪 검증 상태 (Validation)
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
socketMode: true,
appToken: process.env.SLACK_APP_TOKEN,
});
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
app.message('hello', async ({ message, say }) => {
await say(`Hi <@${message.user}>!`);
});
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
await app.start();
```
## 🤔 의사결정 기준 (Decision Criteria)
### Slash command + modal
```ts
app.command('/deploy', async ({ ack, body, client }) => {
await ack();
await client.views.open({
trigger_id: body.trigger_id,
view: {
type: 'modal',
callback_id: 'deploy_modal',
title: { type: 'plain_text', text: 'Deploy' },
submit: { type: 'plain_text', text: 'Go' },
blocks: [
{ type: 'input', block_id: 'env',
element: { type: 'static_select', action_id: 'sel',
options: [{text:{type:'plain_text',text:'staging'},value:'stg'}]},
label: { type: 'plain_text', text: 'Environment' } }
]
}
});
});
**선택 A를 써야 할 때:**
- *(TODO)*
app.view('deploy_modal', async ({ ack, view, client, body }) => {
await ack();
const env = view.state.values.env.sel.selected_option!.value;
await triggerDeploy(env);
await client.chat.postMessage({ channel: body.user.id, text: `Deploying ${env}...` });
});
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Event subscription (app_mention)
```ts
app.event('app_mention', async ({ event, client }) => {
const ai = await callLLM(event.text);
await client.chat.postMessage({
channel: event.channel,
thread_ts: event.ts,
blocks: [{ type: 'section', text: { type: 'mrkdwn', text: ai }}],
});
});
```
**기본값:**
> *(TODO)*
### Interactive button → action
```ts
app.action('approve_deploy', async ({ ack, body, client }) => {
await ack();
const action = body as any;
await client.chat.update({
channel: action.channel.id,
ts: action.message.ts,
text: `Approved by <@${action.user.id}>`,
blocks: []
});
await triggerDeploy(action.actions[0].value);
});
```
## ❌ 안티패턴 (Anti-Patterns)
### Block Kit message
```ts
const blocks = [
{ type: 'header', text: { type: 'plain_text', text: '🚨 Production Alert' }},
{ type: 'section', fields: [
{ type: 'mrkdwn', text: '*Service:* api' },
{ type: 'mrkdwn', text: '*Severity:* P1' },
]},
{ type: 'actions', elements: [
{ type: 'button', text: {type:'plain_text',text:'Ack'}, action_id: 'ack', style: 'primary' },
{ type: 'button', text: {type:'plain_text',text:'Page'}, action_id: 'page', style: 'danger' },
]}
];
await client.chat.postMessage({ channel: '#alerts', blocks, text: 'Alert' });
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Signature verification (HTTP mode)
```ts
import crypto from 'crypto';
function verifySlack(req: Request, secret: string): boolean {
const ts = req.headers.get('x-slack-request-timestamp')!;
const sig = req.headers.get('x-slack-signature')!;
const body = req.body;
const base = `v0:${ts}:${body}`;
const expected = `v0=${crypto.createHmac('sha256', secret).update(base).digest('hex')}`;
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig));
}
```
### Rate limit handling
```ts
app.error(async ({ error, ...rest }) => {
if (error.code === 'slack_webapi_rate_limited') {
await new Promise(r => setTimeout(r, error.retryAfter * 1000));
return;
}
console.error(error);
});
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Internal tool, no public URL | Socket Mode |
| Public app distribution | HTTP + signed requests |
| High-volume events | Lambda/Workers + queue |
| Stateful conversation | Bolt + Redis state |
| AI assistant | Anthropic SDK + Bolt event handler |
**기본값**: Bolt-js + Socket Mode for internal, HTTP + Cloudflare Workers for public.
## 🔗 Graph
- 부모: [[Chatops]] · [[Bot Development]]
- 변형: [[Discord Bot]] · [[Microsoft Teams Bot]]
- 응용: [[CI/CD Notification]] · [[On-Call Automation]] · [[AI Assistant]]
- Adjacent: [[Webhooks]] · [[OAuth]] · [[Block Kit]]
## 🤖 LLM 활용
**언제**: Block Kit JSON 생성, slash command boilerplate, signature verify code.
**언제 X**: workspace OAuth flow debugging (회사 별 admin policy 가 다양).
## ❌ 안티패턴
- **No signature verify**: spoofed requests.
- **Sync long-running**: 3s timeout — use ack() + async work.
- **Hard-coded channel ID**: env var 의 X.
- **No retry on send**: rate limit 시 message loss.
## 🧪 검증 / 중복
- Verified (Slack API docs 2026, Bolt-js v3).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Slack bot 2026 patterns |