1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
| #!/usr/bin/env python3
import asyncio
import json
import os
import random
import string
from datetime import datetime, timedelta, timezone
from typing import Any
import requests
from dotenv import load_dotenv
from mcp.server import Server
from mcp.server.stdio import stdio_server
import mcp.types as types
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
AUTH_FILE = "/home/ubuntu/authorized_users.json"
ADMIN_CHAT_ID = os.getenv("ADMIN_CHAT_ID", "")
def get_api_url(method: str) -> str:
return f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
def telegram_request(method: str, params: dict = None) -> Any:
"""Telegram Bot API 공통 요청 함수"""
if not TELEGRAM_BOT_TOKEN:
raise ValueError("TELEGRAM_BOT_TOKEN이 .env 파일에 설정되지 않았습니다.")
try:
response = requests.post(
get_api_url(method),
json=params or {},
timeout=30,
)
response.raise_for_status()
data = response.json()
if not data.get("ok"):
raise ValueError(f"Telegram API 오류: {data.get('description', '알 수 없는 오류')}")
return data.get("result", [])
except requests.exceptions.ConnectionError:
raise RuntimeError("네트워크 연결 실패. 인터넷 연결을 확인하세요.")
except requests.exceptions.Timeout:
raise RuntimeError("요청 시간 초과. 잠시 후 다시 시도하세요.")
except requests.exceptions.HTTPError as e:
raise RuntimeError(f"HTTP 오류: {e}")
# ── 인가 데이터 관리 ──────────────────────────────────────────
def load_auth() -> dict:
"""authorized_users.json 로드. 없으면 빈 구조 반환."""
if os.path.exists(AUTH_FILE):
with open(AUTH_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {"authorized": {}, "pending": {}}
def save_auth(auth: dict) -> None:
"""authorized_users.json 저장."""
with open(AUTH_FILE, "w", encoding="utf-8") as f:
json.dump(auth, f, ensure_ascii=False, indent=2)
def generate_code() -> str:
"""6자리 영숫자 연결 코드 생성."""
chars = string.ascii_uppercase + string.digits
return "".join(random.choices(chars, k=6))
def is_authorized(auth: dict, chat_id: str) -> bool:
"""chat_id가 승인된 사용자인지 확인."""
return str(chat_id) in auth.get("authorized", {})
def is_pending(auth: dict, chat_id: str) -> bool:
"""chat_id가 이미 대기 중인지 확인."""
for entry in auth.get("pending", {}).values():
if str(entry.get("chat_id")) == str(chat_id):
return True
return False
def handle_unauthorized(auth: dict, chat_id: str, name: str) -> None:
"""미승인 사용자에게 연결 코드 발급 및 pending 등록."""
if is_pending(auth, chat_id):
return
code = generate_code()
while code in auth.get("pending", {}):
code = generate_code()
auth.setdefault("pending", {})[code] = {
"chat_id": str(chat_id),
"name": name,
"created_at": datetime.now(timezone.utc).isoformat(),
}
save_auth(auth)
try:
telegram_request("sendMessage", {
"chat_id": str(chat_id),
"text": f"🔐 접근 권한이 필요합니다.\n\n연결 코드: {code}\n\n"
f"관리자에게 이 코드를 전달하여 승인을 요청하세요.",
})
except Exception:
pass
try:
telegram_request("sendMessage", {
"chat_id": ADMIN_CHAT_ID,
"text": (
f"🆕 새로운 사용자 접근 요청\n\n"
f"이름: {name}\n"
f"chat_id: {chat_id}\n"
f"연결 코드: {code}\n\n"
f"승인하려면 이 코드를 알려주세요."
),
})
except Exception:
pass
def filter_authorized_updates(updates: list[dict]) -> list[dict]:
"""업데이트 목록에서 미승인 사용자를 처리하고 승인된 메시지만 반환."""
auth = load_auth()
authorized_updates = []
for update in updates:
message = (update.get("message") or update.get("channel_post")
or update.get("edited_message"))
if not message:
continue
chat_id = str(message["chat"]["id"])
if is_authorized(auth, chat_id):
authorized_updates.append(update)
else:
sender = (message.get("from") or message.get("sender_chat") or {})
name = (sender.get("first_name") or sender.get("username")
or "알 수 없음")
handle_unauthorized(auth, chat_id, name)
return authorized_updates
HISTORY_FILE = "/home/ubuntu/history.json"
def _load_history() -> dict:
"""history.json 로드. 없으면 빈 구조 반환."""
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {"conversations": [], "summary": None}
# ── 메시지 포맷팅 ─────────────────────────────────────────────
def format_message(update: dict) -> dict | None:
"""업데이트에서 메시지 정보 추출"""
message = (update.get("message") or update.get("channel_post")
or update.get("edited_message"))
if not message:
return None
sender = message.get("from") or message.get("sender_chat") or {}
return {
"chat_id": message["chat"]["id"],
"chat_name": (message["chat"].get("title")
or message["chat"].get("first_name", "")),
"from": sender.get("username") or sender.get("first_name", "알 수 없음"),
"text": message.get("text") or message.get("caption", "(텍스트 없음)"),
"date": datetime.fromtimestamp(message["date"], tz=timezone.utc),
}
# MCP 서버 초기화
server = Server("telegram-mcp")
@server.list_tools()
async def list_tools() -> list[types.Tool]:
return [
types.Tool(
name="get_today_messages",
description="오늘 받은 텔레그램 메시지 전체를 가져옵니다.",
inputSchema={
"type": "object",
"properties": {},
"required": [],
},
),
types.Tool(
name="send_message",
description="지정한 chat_id로 텔레그램 메시지를 보냅니다.",
inputSchema={
"type": "object",
"properties": {
"chat_id": {
"type": "string",
"description": "메시지를 보낼 채팅 ID",
},
"text": {
"type": "string",
"description": "보낼 메시지 내용",
},
},
"required": ["chat_id", "text"],
},
),
types.Tool(
name="get_chat_history",
description="최근 N개의 텔레그램 메시지를 가져옵니다.",
inputSchema={
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "가져올 메시지 수 (1~100, 기본값: 10)",
"default": 10,
"minimum": 1,
"maximum": 100,
},
},
"required": [],
},
),
types.Tool(
name="get_pending_users",
description="승인 대기 중인 사용자 목록을 조회합니다.",
inputSchema={
"type": "object",
"properties": {},
"required": [],
},
),
types.Tool(
name="approve_user",
description="연결 코드로 사용자를 승인합니다.",
inputSchema={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "6자리 연결 코드",
},
},
"required": ["code"],
},
),
types.Tool(
name="revoke_user",
description="승인된 사용자의 접근을 취소합니다.",
inputSchema={
"type": "object",
"properties": {
"chat_id": {
"type": "string",
"description": "접근을 취소할 사용자의 chat_id",
},
},
"required": ["chat_id"],
},
),
]
@server.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> list[types.TextContent]:
try:
if name == "get_today_messages":
history = _load_history()
KST = timezone(timedelta(hours=9))
today = datetime.now(KST).date()
today_messages = []
for conv in history.get("conversations", []):
ts = datetime.fromisoformat(conv["timestamp"])
ts_kst = (ts.astimezone(KST) if ts.tzinfo
else ts.replace(tzinfo=timezone.utc).astimezone(KST))
if ts_kst.date() == today:
today_messages.append(conv)
if not today_messages:
return [types.TextContent(type="text",
text="오늘 받은 메시지가 없습니다.")]
lines = [f"오늘 받은 메시지 ({len(today_messages)}건)\n" + "─" * 40]
for conv in today_messages:
ts = datetime.fromisoformat(conv["timestamp"])
ts_kst = (ts.astimezone(KST) if ts.tzinfo
else ts.replace(tzinfo=timezone.utc).astimezone(KST))
time_str = ts_kst.strftime("%H:%M:%S")
lines.append(
f"[{time_str}] {conv['user']} | chat_id: {conv['chat_id']}\n"
f" 사용자: {conv['message']}\n"
f" 응답: {conv['response']}"
)
return [types.TextContent(type="text", text="\n".join(lines))]
elif name == "send_message":
chat_id = arguments.get("chat_id", "").strip()
text = arguments.get("text", "").strip()
if not chat_id:
raise ValueError("chat_id가 필요합니다.")
if not text:
raise ValueError("text가 필요합니다.")
telegram_request("sendMessage", {"chat_id": chat_id, "text": text})
return [types.TextContent(
type="text",
text=f"메시지 전송 완료\nchat_id: {chat_id}\n내용: {text}",
)]
elif name == "get_chat_history":
raw_limit = arguments.get("limit", 10)
limit = max(1, min(int(raw_limit), 100))
history = _load_history()
conversations = history.get("conversations", [])
messages = conversations[-limit:]
if not messages:
return [types.TextContent(type="text",
text="가져올 메시지가 없습니다.")]
lines = [f"최근 {len(messages)}개 메시지\n" + "─" * 40]
for conv in messages:
ts = datetime.fromisoformat(conv["timestamp"])
time_str = ts.strftime("%Y-%m-%d %H:%M:%S")
lines.append(
f"[{time_str}] {conv['user']} | chat_id: {conv['chat_id']}\n"
f" 사용자: {conv['message']}\n"
f" 응답: {conv['response']}"
)
return [types.TextContent(type="text", text="\n".join(lines))]
elif name == "get_pending_users":
auth = load_auth()
pending = auth.get("pending", {})
if not pending:
return [types.TextContent(type="text",
text="승인 대기 중인 사용자가 없습니다.")]
lines = [f"승인 대기 ({len(pending)}명)\n" + "─" * 40]
for code, info in pending.items():
lines.append(
f"코드: {code} | 이름: {info['name']} "
f"| chat_id: {info['chat_id']}\n"
f" 요청일: {info['created_at']}"
)
return [types.TextContent(type="text", text="\n".join(lines))]
elif name == "approve_user":
code = arguments.get("code", "").strip().upper()
if not code:
raise ValueError("연결 코드가 필요합니다.")
auth = load_auth()
pending = auth.get("pending", {})
if code not in pending:
raise ValueError(f"유효하지 않은 연결 코드: {code}")
user_info = pending.pop(code)
chat_id = user_info["chat_id"]
name = user_info["name"]
auth.setdefault("authorized", {})[chat_id] = name
save_auth(auth)
try:
telegram_request("sendMessage", {
"chat_id": chat_id,
"text": "✅ 접근이 승인되었습니다. 이제 봇을 사용할 수 있습니다.",
})
except Exception:
pass
return [types.TextContent(
type="text",
text=f"승인 완료\n이름: {name}\nchat_id: {chat_id}",
)]
elif name == "revoke_user":
chat_id = arguments.get("chat_id", "").strip()
if not chat_id:
raise ValueError("chat_id가 필요합니다.")
auth = load_auth()
authorized = auth.get("authorized", {})
if chat_id not in authorized:
raise ValueError(f"승인된 사용자가 아닙니다: {chat_id}")
name = authorized.pop(chat_id)
save_auth(auth)
return [types.TextContent(
type="text",
text=f"접근 취소 완료\n이름: {name}\nchat_id: {chat_id}",
)]
else:
raise ValueError(f"알 수 없는 도구: {name}")
except (ValueError, RuntimeError) as e:
return [types.TextContent(type="text", text=f"오류: {e}")]
except Exception as e:
return [types.TextContent(type="text", text=f"예기치 않은 오류: {e}")]
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
server.create_initialization_options(),
)
if __name__ == "__main__":
asyncio.run(main())
|