telegram-mcp-server 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- telegram_mcp_server/__init__.py +9 -0
- telegram_mcp_server/__main__.py +123 -0
- telegram_mcp_server/bot.py +531 -0
- telegram_mcp_server/cli.py +348 -0
- telegram_mcp_server/config.py +25 -0
- telegram_mcp_server/message_queue.py +109 -0
- telegram_mcp_server/server.py +953 -0
- telegram_mcp_server/session.py +188 -0
- telegram_mcp_server-0.1.0.dist-info/METADATA +248 -0
- telegram_mcp_server-0.1.0.dist-info/RECORD +14 -0
- telegram_mcp_server-0.1.0.dist-info/WHEEL +5 -0
- telegram_mcp_server-0.1.0.dist-info/entry_points.txt +2 -0
- telegram_mcp_server-0.1.0.dist-info/licenses/LICENSE +21 -0
- telegram_mcp_server-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Telegram MCP Server - Remote control Claude Code via Telegram"""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
__author__ = "Your Name"
|
|
5
|
+
__license__ = "MIT"
|
|
6
|
+
|
|
7
|
+
from . import server, bot, config, session, message_queue
|
|
8
|
+
|
|
9
|
+
__all__ = ["server", "bot", "config", "session", "message_queue"]
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Main entry point for Telegram MCP Server"""
|
|
2
|
+
import sys
|
|
3
|
+
import os
|
|
4
|
+
import logging
|
|
5
|
+
import asyncio
|
|
6
|
+
from mcp.server.stdio import stdio_server
|
|
7
|
+
|
|
8
|
+
from . import config
|
|
9
|
+
from .server import server
|
|
10
|
+
from .bot import setup_bot
|
|
11
|
+
|
|
12
|
+
# Setup logging
|
|
13
|
+
logging.basicConfig(
|
|
14
|
+
level=logging.INFO,
|
|
15
|
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
16
|
+
handlers=[
|
|
17
|
+
logging.FileHandler('/tmp/telegram-mcp-server.log'),
|
|
18
|
+
logging.StreamHandler(sys.stderr)
|
|
19
|
+
]
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
async def run_telegram_bot():
|
|
26
|
+
"""Run Telegram bot asynchronously (only if not already running)"""
|
|
27
|
+
try:
|
|
28
|
+
config.validate_config()
|
|
29
|
+
except ValueError as e:
|
|
30
|
+
logger.error(f"Configuration error: {e}")
|
|
31
|
+
logger.error("Telegram bot will not start. MCP server will continue without Telegram integration.")
|
|
32
|
+
return
|
|
33
|
+
|
|
34
|
+
# Check if another bot instance is already running
|
|
35
|
+
import socket
|
|
36
|
+
lock_file = "/tmp/telegram-mcp-bot.lock"
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
# Try to create lock file
|
|
40
|
+
if os.path.exists(lock_file):
|
|
41
|
+
# Check if the process is still running
|
|
42
|
+
with open(lock_file, 'r') as f:
|
|
43
|
+
old_pid = f.read().strip()
|
|
44
|
+
|
|
45
|
+
# Check if process exists
|
|
46
|
+
try:
|
|
47
|
+
os.kill(int(old_pid), 0) # Check if process exists
|
|
48
|
+
logger.info(f"Telegram bot already running in another process (PID: {old_pid})")
|
|
49
|
+
logger.info("This MCP server instance will use shared storage without starting bot")
|
|
50
|
+
return
|
|
51
|
+
except OSError:
|
|
52
|
+
# Process doesn't exist, remove stale lock
|
|
53
|
+
os.remove(lock_file)
|
|
54
|
+
|
|
55
|
+
# Write our PID to lock file
|
|
56
|
+
with open(lock_file, 'w') as f:
|
|
57
|
+
f.write(str(os.getpid()))
|
|
58
|
+
|
|
59
|
+
logger.info("Starting Telegram bot (first instance)...")
|
|
60
|
+
|
|
61
|
+
# Setup bot
|
|
62
|
+
bot_app = setup_bot(config.TELEGRAM_BOT_TOKEN)
|
|
63
|
+
|
|
64
|
+
# Set global telegram_bot reference
|
|
65
|
+
from . import server as server_module
|
|
66
|
+
server_module.telegram_bot = bot_app
|
|
67
|
+
|
|
68
|
+
# Initialize and start bot
|
|
69
|
+
try:
|
|
70
|
+
async with bot_app:
|
|
71
|
+
await bot_app.initialize()
|
|
72
|
+
await bot_app.start()
|
|
73
|
+
await bot_app.updater.start_polling(allowed_updates=None)
|
|
74
|
+
# Keep bot running
|
|
75
|
+
while True:
|
|
76
|
+
await asyncio.sleep(1)
|
|
77
|
+
except Exception as e:
|
|
78
|
+
logger.error(f"Telegram bot error: {e}", exc_info=True)
|
|
79
|
+
finally:
|
|
80
|
+
# Remove lock file on exit
|
|
81
|
+
if os.path.exists(lock_file):
|
|
82
|
+
os.remove(lock_file)
|
|
83
|
+
|
|
84
|
+
except Exception as e:
|
|
85
|
+
logger.error(f"Bot startup error: {e}", exc_info=True)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def main():
|
|
89
|
+
"""Main entry point"""
|
|
90
|
+
logger.info("Starting Telegram MCP Server...")
|
|
91
|
+
|
|
92
|
+
# Create task for Telegram bot
|
|
93
|
+
bot_task = asyncio.create_task(run_telegram_bot())
|
|
94
|
+
|
|
95
|
+
# Give bot time to start
|
|
96
|
+
await asyncio.sleep(2)
|
|
97
|
+
|
|
98
|
+
# Run MCP server (stdio)
|
|
99
|
+
logger.info("Starting MCP stdio server...")
|
|
100
|
+
try:
|
|
101
|
+
async with stdio_server() as (read_stream, write_stream):
|
|
102
|
+
await server.run(
|
|
103
|
+
read_stream,
|
|
104
|
+
write_stream,
|
|
105
|
+
server.create_initialization_options()
|
|
106
|
+
)
|
|
107
|
+
finally:
|
|
108
|
+
# Cancel bot task on exit
|
|
109
|
+
bot_task.cancel()
|
|
110
|
+
try:
|
|
111
|
+
await bot_task
|
|
112
|
+
except asyncio.CancelledError:
|
|
113
|
+
pass
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
if __name__ == "__main__":
|
|
117
|
+
try:
|
|
118
|
+
asyncio.run(main())
|
|
119
|
+
except KeyboardInterrupt:
|
|
120
|
+
logger.info("Shutting down...")
|
|
121
|
+
except Exception as e:
|
|
122
|
+
logger.error(f"Fatal error: {e}", exc_info=True)
|
|
123
|
+
sys.exit(1)
|
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
"""Telegram Bot handlers"""
|
|
2
|
+
import os
|
|
3
|
+
import logging
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
|
6
|
+
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
|
|
7
|
+
|
|
8
|
+
from .session import registry
|
|
9
|
+
from .message_queue import message_queue
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def format_time_ago(iso_time: str) -> str:
|
|
15
|
+
"""Format ISO timestamp as human-readable time ago"""
|
|
16
|
+
try:
|
|
17
|
+
dt = datetime.fromisoformat(iso_time)
|
|
18
|
+
now = datetime.now()
|
|
19
|
+
diff = (now - dt).total_seconds()
|
|
20
|
+
|
|
21
|
+
if diff < 60:
|
|
22
|
+
return f"{int(diff)}秒前"
|
|
23
|
+
elif diff < 3600:
|
|
24
|
+
return f"{int(diff / 60)}分钟前"
|
|
25
|
+
elif diff < 86400:
|
|
26
|
+
return f"{int(diff / 3600)}小时前"
|
|
27
|
+
else:
|
|
28
|
+
return f"{int(diff / 86400)}天前"
|
|
29
|
+
except:
|
|
30
|
+
return iso_time
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def cmd_sessions(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
34
|
+
"""List all active sessions"""
|
|
35
|
+
sessions = registry.list_all()
|
|
36
|
+
|
|
37
|
+
if not sessions:
|
|
38
|
+
await update.message.reply_text("没有活跃会话")
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
text = "📋 活跃会话:\n\n"
|
|
42
|
+
for i, (sid, session) in enumerate(sessions.items(), 1):
|
|
43
|
+
status_emoji = {
|
|
44
|
+
"running": "▶️",
|
|
45
|
+
"waiting": "⏸️",
|
|
46
|
+
"idle": "⏹️"
|
|
47
|
+
}.get(session.status, "❓")
|
|
48
|
+
|
|
49
|
+
text += (
|
|
50
|
+
f"{i}️⃣ {status_emoji} `{sid}`\n"
|
|
51
|
+
f" 📁 `{session.project_path}`\n"
|
|
52
|
+
f" 🕐 {format_time_ago(session.last_active)}\n\n"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
await update.message.reply_text(text, parse_mode="Markdown")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def cmd_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
59
|
+
"""Show session status"""
|
|
60
|
+
if not context.args:
|
|
61
|
+
await update.message.reply_text("用法: /status <session_id>")
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
session_id = context.args[0]
|
|
65
|
+
session = registry.get(session_id)
|
|
66
|
+
|
|
67
|
+
if not session:
|
|
68
|
+
await update.message.reply_text(f"❌ 会话 `{session_id}` 不存在", parse_mode="Markdown")
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
status_emoji = {
|
|
72
|
+
"running": "▶️ 运行中",
|
|
73
|
+
"waiting": "⏸️ 等待回复",
|
|
74
|
+
"idle": "⏹️ 空闲"
|
|
75
|
+
}.get(session.status, "❓ 未知")
|
|
76
|
+
|
|
77
|
+
status_text = f"""📊 会话状态
|
|
78
|
+
━━━━━━━━━━━━━━━━
|
|
79
|
+
🆔 ID: `{session.session_id}`
|
|
80
|
+
📁 项目: `{session.project_path}`
|
|
81
|
+
⏱️ 状态: {status_emoji}
|
|
82
|
+
🕐 最后活动: {format_time_ago(session.last_active)}
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
if session.last_message:
|
|
86
|
+
status_text += f"💬 最后消息: {session.last_message[:100]}"
|
|
87
|
+
|
|
88
|
+
await update.message.reply_text(status_text, parse_mode="Markdown")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def cmd_to(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
92
|
+
"""Send message to specific session"""
|
|
93
|
+
if len(context.args) < 2:
|
|
94
|
+
await update.message.reply_text("用法: /to <session_id> <消息>")
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
session_id = context.args[0]
|
|
98
|
+
message = " ".join(context.args[1:])
|
|
99
|
+
|
|
100
|
+
if not registry.exists(session_id):
|
|
101
|
+
await update.message.reply_text(f"❌ 会话 `{session_id}` 不存在", parse_mode="Markdown")
|
|
102
|
+
return
|
|
103
|
+
|
|
104
|
+
# Add message to queue
|
|
105
|
+
message_queue.push(session_id, message)
|
|
106
|
+
|
|
107
|
+
# Silent confirmation (no message) - user will see Claude's response directly
|
|
108
|
+
# Only send confirmation if session is not waiting (might be delayed)
|
|
109
|
+
session = registry.get(session_id)
|
|
110
|
+
if not session.pending_reply:
|
|
111
|
+
await update.message.reply_text(
|
|
112
|
+
f"✅ 已加入队列 `{session_id}` (会话当前不在等待状态)",
|
|
113
|
+
parse_mode="Markdown"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
async def cmd_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
118
|
+
"""View or download project file"""
|
|
119
|
+
if len(context.args) < 2:
|
|
120
|
+
await update.message.reply_text(
|
|
121
|
+
"用法: /file <session_id> <file_path> [download]\n\n"
|
|
122
|
+
"示例:\n"
|
|
123
|
+
"/file testtg src/main.py - 查看文件内容\n"
|
|
124
|
+
"/file testtg config.json download - 下载文件"
|
|
125
|
+
)
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
session_id = context.args[0]
|
|
129
|
+
file_path = context.args[1]
|
|
130
|
+
download_mode = len(context.args) > 2 and context.args[2] == "download"
|
|
131
|
+
|
|
132
|
+
session = registry.get(session_id)
|
|
133
|
+
if not session:
|
|
134
|
+
await update.message.reply_text(f"❌ 会话 `{session_id}` 不存在", parse_mode="Markdown")
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
full_path = os.path.join(session.project_path, file_path)
|
|
138
|
+
|
|
139
|
+
if not os.path.exists(full_path):
|
|
140
|
+
await update.message.reply_text(f"❌ 文件不存在: `{file_path}`", parse_mode="Markdown")
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
# Check if it's a file (not directory)
|
|
144
|
+
if not os.path.isfile(full_path):
|
|
145
|
+
await update.message.reply_text(f"❌ 不是文件: `{file_path}`", parse_mode="Markdown")
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
# If download mode, always send as document
|
|
149
|
+
if download_mode:
|
|
150
|
+
try:
|
|
151
|
+
with open(full_path, 'rb') as f:
|
|
152
|
+
await update.message.reply_document(
|
|
153
|
+
document=f,
|
|
154
|
+
filename=os.path.basename(file_path),
|
|
155
|
+
caption=f"📄 {file_path}"
|
|
156
|
+
)
|
|
157
|
+
except Exception as e:
|
|
158
|
+
await update.message.reply_text(f"❌ 发送文件失败: {str(e)}")
|
|
159
|
+
return
|
|
160
|
+
|
|
161
|
+
# Otherwise, try to display content
|
|
162
|
+
try:
|
|
163
|
+
with open(full_path, 'r', encoding='utf-8') as f:
|
|
164
|
+
content = f.read()
|
|
165
|
+
|
|
166
|
+
# If file is too large, send as document
|
|
167
|
+
if len(content) > 4000:
|
|
168
|
+
with open(full_path, 'rb') as f:
|
|
169
|
+
await update.message.reply_document(
|
|
170
|
+
document=f,
|
|
171
|
+
filename=os.path.basename(file_path),
|
|
172
|
+
caption=f"📄 {file_path} (文件过大,作为附件发送)\n💡 提示: 可直接下载查看"
|
|
173
|
+
)
|
|
174
|
+
else:
|
|
175
|
+
# Detect language for syntax highlighting
|
|
176
|
+
ext = os.path.splitext(file_path)[1]
|
|
177
|
+
lang_map = {
|
|
178
|
+
".py": "python", ".js": "javascript", ".ts": "typescript",
|
|
179
|
+
".go": "go", ".rs": "rust", ".java": "java",
|
|
180
|
+
".c": "c", ".cpp": "cpp", ".h": "c", ".hpp": "cpp",
|
|
181
|
+
".sh": "bash", ".json": "json", ".yaml": "yaml", ".yml": "yaml",
|
|
182
|
+
".xml": "xml", ".html": "html", ".css": "css", ".md": "markdown"
|
|
183
|
+
}
|
|
184
|
+
lang = lang_map.get(ext, "")
|
|
185
|
+
|
|
186
|
+
# Truncate if still too long for Telegram
|
|
187
|
+
if len(content) > 3800:
|
|
188
|
+
content = content[:3800] + "\n\n... (已截断)"
|
|
189
|
+
|
|
190
|
+
# Try to send with Markdown
|
|
191
|
+
try:
|
|
192
|
+
await update.message.reply_text(
|
|
193
|
+
f"📄 `{file_path}`\n\n```{lang}\n{content}\n```",
|
|
194
|
+
parse_mode="Markdown"
|
|
195
|
+
)
|
|
196
|
+
except Exception:
|
|
197
|
+
# Fallback: send as plain text if Markdown fails
|
|
198
|
+
await update.message.reply_text(
|
|
199
|
+
f"📄 {file_path}\n\n{content}"
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
except UnicodeDecodeError:
|
|
203
|
+
# Binary file, send as document
|
|
204
|
+
try:
|
|
205
|
+
with open(full_path, 'rb') as f:
|
|
206
|
+
await update.message.reply_document(
|
|
207
|
+
document=f,
|
|
208
|
+
filename=os.path.basename(file_path),
|
|
209
|
+
caption=f"📄 {file_path} (二进制文件)"
|
|
210
|
+
)
|
|
211
|
+
except Exception as e:
|
|
212
|
+
await update.message.reply_text(f"❌ 发送文件失败: {str(e)}")
|
|
213
|
+
except Exception as e:
|
|
214
|
+
await update.message.reply_text(f"❌ 读取文件失败: {str(e)}")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
218
|
+
"""Handle photo messages"""
|
|
219
|
+
# Get largest photo
|
|
220
|
+
photo = update.message.photo[-1]
|
|
221
|
+
caption = update.message.caption or "用户发送了一张图片"
|
|
222
|
+
|
|
223
|
+
# Download photo
|
|
224
|
+
try:
|
|
225
|
+
file = await context.bot.get_file(photo.file_id)
|
|
226
|
+
file_path = f"/tmp/telegram_photo_{photo.file_id}.jpg"
|
|
227
|
+
await file.download_to_drive(file_path)
|
|
228
|
+
|
|
229
|
+
# Format message with image info
|
|
230
|
+
photo_message = f"[图片] {caption}\n文件路径: {file_path}"
|
|
231
|
+
|
|
232
|
+
# Check if this is a reply to a message (priority)
|
|
233
|
+
if update.message.reply_to_message:
|
|
234
|
+
replied_text = update.message.reply_to_message.text or update.message.reply_to_message.caption or ""
|
|
235
|
+
|
|
236
|
+
import re
|
|
237
|
+
session_id = None
|
|
238
|
+
|
|
239
|
+
# Try to extract session_id
|
|
240
|
+
match = re.search(r'`([a-zA-Z0-9_-]+)`', replied_text)
|
|
241
|
+
if match and registry.exists(match.group(1)):
|
|
242
|
+
session_id = match.group(1)
|
|
243
|
+
|
|
244
|
+
if not session_id:
|
|
245
|
+
all_sessions = registry.list_all()
|
|
246
|
+
for sid in all_sessions.keys():
|
|
247
|
+
if sid in replied_text:
|
|
248
|
+
session_id = sid
|
|
249
|
+
break
|
|
250
|
+
|
|
251
|
+
if session_id:
|
|
252
|
+
message_queue.push(session_id, photo_message)
|
|
253
|
+
try:
|
|
254
|
+
await update.message.set_reaction("👍")
|
|
255
|
+
except:
|
|
256
|
+
pass
|
|
257
|
+
return
|
|
258
|
+
|
|
259
|
+
# No reply, or couldn't extract session - find waiting sessions
|
|
260
|
+
waiting_sessions = registry.list_waiting()
|
|
261
|
+
|
|
262
|
+
if len(waiting_sessions) == 0:
|
|
263
|
+
await update.message.reply_text("没有会话在等待。图片已保存到:\n" + file_path)
|
|
264
|
+
elif len(waiting_sessions) == 1:
|
|
265
|
+
session_id = list(waiting_sessions.keys())[0]
|
|
266
|
+
message_queue.push(session_id, photo_message)
|
|
267
|
+
try:
|
|
268
|
+
await update.message.set_reaction("👍")
|
|
269
|
+
except:
|
|
270
|
+
pass
|
|
271
|
+
else:
|
|
272
|
+
# Store photo data first
|
|
273
|
+
import json
|
|
274
|
+
import hashlib
|
|
275
|
+
|
|
276
|
+
# Use hash to create short ID
|
|
277
|
+
photo_id = hashlib.md5(photo.file_id.encode()).hexdigest()[:8]
|
|
278
|
+
|
|
279
|
+
photo_data = {
|
|
280
|
+
'file_path': file_path,
|
|
281
|
+
'caption': caption,
|
|
282
|
+
'message': photo_message
|
|
283
|
+
}
|
|
284
|
+
with open(f"/tmp/photo_{photo_id}.json", 'w') as f:
|
|
285
|
+
json.dump(photo_data, f)
|
|
286
|
+
|
|
287
|
+
# Create buttons with short callback_data
|
|
288
|
+
keyboard = []
|
|
289
|
+
for sid in waiting_sessions.keys():
|
|
290
|
+
keyboard.append([
|
|
291
|
+
InlineKeyboardButton(
|
|
292
|
+
f"📤 发送到 {sid}",
|
|
293
|
+
callback_data=f"photo_{photo_id}_{sid}" # Short format: photo_HASH_SESSION
|
|
294
|
+
)
|
|
295
|
+
])
|
|
296
|
+
|
|
297
|
+
reply_markup = InlineKeyboardMarkup(keyboard)
|
|
298
|
+
await update.message.reply_text(
|
|
299
|
+
f"多个会话在等待,请选择:\n\n📷 {caption}",
|
|
300
|
+
reply_markup=reply_markup
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
except Exception as e:
|
|
304
|
+
await update.message.reply_text(f"❌ 处理图片失败: {str(e)}")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
async def handle_plain_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
308
|
+
"""Handle plain text messages (auto-route to waiting sessions)"""
|
|
309
|
+
message = update.message.text
|
|
310
|
+
|
|
311
|
+
# Check if this is a reply to a previous message
|
|
312
|
+
if update.message.reply_to_message:
|
|
313
|
+
# Try to extract session_id from the replied message
|
|
314
|
+
replied_text = update.message.reply_to_message.text or update.message.reply_to_message.caption or ""
|
|
315
|
+
|
|
316
|
+
# Extract session_id using multiple patterns
|
|
317
|
+
import re
|
|
318
|
+
session_id = None
|
|
319
|
+
|
|
320
|
+
# Pattern 1: [`session-id`]
|
|
321
|
+
match = re.search(r'\[`([a-zA-Z0-9_-]+)`\]', replied_text)
|
|
322
|
+
if match:
|
|
323
|
+
session_id = match.group(1)
|
|
324
|
+
|
|
325
|
+
# Pattern 2: [session-id]
|
|
326
|
+
if not session_id:
|
|
327
|
+
match = re.search(r'\[([a-zA-Z0-9_-]+)\]', replied_text)
|
|
328
|
+
if match:
|
|
329
|
+
session_id = match.group(1)
|
|
330
|
+
|
|
331
|
+
# Pattern 3: `session-id` (without brackets) - like: ✅ `test-new`
|
|
332
|
+
if not session_id:
|
|
333
|
+
match = re.search(r'`([a-zA-Z0-9_-]+)`', replied_text)
|
|
334
|
+
if match:
|
|
335
|
+
candidate = match.group(1)
|
|
336
|
+
if registry.exists(candidate):
|
|
337
|
+
session_id = candidate
|
|
338
|
+
|
|
339
|
+
# Pattern 4: Search for any known session ID in the text
|
|
340
|
+
if not session_id:
|
|
341
|
+
all_sessions = registry.list_all()
|
|
342
|
+
for sid in all_sessions.keys():
|
|
343
|
+
if sid in replied_text:
|
|
344
|
+
session_id = sid
|
|
345
|
+
break
|
|
346
|
+
|
|
347
|
+
if session_id and registry.exists(session_id):
|
|
348
|
+
message_queue.push(session_id, message)
|
|
349
|
+
# Silent - user will see Claude's response
|
|
350
|
+
# Add a subtle reaction to confirm
|
|
351
|
+
try:
|
|
352
|
+
await update.message.set_reaction("👍")
|
|
353
|
+
except:
|
|
354
|
+
pass # Reaction might not be supported
|
|
355
|
+
return
|
|
356
|
+
|
|
357
|
+
# If we couldn't extract session_id, show available sessions
|
|
358
|
+
all_sessions = registry.list_all()
|
|
359
|
+
text = "⚠️ 无法识别回复的会话。\n\n"
|
|
360
|
+
if all_sessions:
|
|
361
|
+
text += "可用会话:\n"
|
|
362
|
+
for sid in all_sessions.keys():
|
|
363
|
+
text += f" /to {sid} {message}\n"
|
|
364
|
+
else:
|
|
365
|
+
text += "当前没有活跃会话。"
|
|
366
|
+
|
|
367
|
+
await update.message.reply_text(text)
|
|
368
|
+
return
|
|
369
|
+
|
|
370
|
+
# Normal message routing (not a reply)
|
|
371
|
+
# Find sessions waiting for reply
|
|
372
|
+
waiting_sessions = registry.list_waiting()
|
|
373
|
+
|
|
374
|
+
if len(waiting_sessions) == 0:
|
|
375
|
+
await update.message.reply_text(
|
|
376
|
+
"没有会话在等待回复。\n"
|
|
377
|
+
"使用 /to <session_id> <消息> 向指定会话发送消息。"
|
|
378
|
+
)
|
|
379
|
+
elif len(waiting_sessions) == 1:
|
|
380
|
+
# Auto-route to the only waiting session
|
|
381
|
+
session_id = list(waiting_sessions.keys())[0]
|
|
382
|
+
message_queue.push(session_id, message)
|
|
383
|
+
|
|
384
|
+
# Silent confirmation - user will see Claude's response directly
|
|
385
|
+
# No need to confirm, reduces noise
|
|
386
|
+
else:
|
|
387
|
+
# Multiple sessions waiting, ask user to choose
|
|
388
|
+
text = "多个会话在等待回复,请选择:\n\n"
|
|
389
|
+
for sid in waiting_sessions.keys():
|
|
390
|
+
text += f"/to {sid} {message}\n"
|
|
391
|
+
|
|
392
|
+
await update.message.reply_text(text)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
396
|
+
"""Handle callback queries from inline keyboards"""
|
|
397
|
+
query = update.callback_query
|
|
398
|
+
await query.answer()
|
|
399
|
+
|
|
400
|
+
data = query.data
|
|
401
|
+
|
|
402
|
+
# Handle photo callback: photo_{photo_id}_{session_id}
|
|
403
|
+
if data.startswith("photo_"):
|
|
404
|
+
import json
|
|
405
|
+
|
|
406
|
+
parts = data.split("_") # photo, photo_id, session_id
|
|
407
|
+
if len(parts) >= 3:
|
|
408
|
+
photo_id = parts[1]
|
|
409
|
+
session_id = parts[2]
|
|
410
|
+
|
|
411
|
+
# Load photo data
|
|
412
|
+
try:
|
|
413
|
+
with open(f"/tmp/photo_{photo_id}.json", 'r') as f:
|
|
414
|
+
photo_data = json.load(f)
|
|
415
|
+
|
|
416
|
+
message_queue.push(session_id, photo_data['message'])
|
|
417
|
+
|
|
418
|
+
await query.edit_message_text(
|
|
419
|
+
f"✅ 图片已发送到会话 `{session_id}`",
|
|
420
|
+
parse_mode="Markdown"
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
# Clean up temp file
|
|
424
|
+
try:
|
|
425
|
+
os.remove(f"/tmp/photo_{photo_id}.json")
|
|
426
|
+
except:
|
|
427
|
+
pass
|
|
428
|
+
|
|
429
|
+
except Exception as e:
|
|
430
|
+
await query.edit_message_text(f"❌ 发送失败: {str(e)}")
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
async def cmd_delete(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
434
|
+
"""Delete a session"""
|
|
435
|
+
if not context.args:
|
|
436
|
+
await update.message.reply_text("用法: /delete <session_id>")
|
|
437
|
+
return
|
|
438
|
+
|
|
439
|
+
session_id = context.args[0]
|
|
440
|
+
session = registry.get(session_id)
|
|
441
|
+
|
|
442
|
+
if not session:
|
|
443
|
+
await update.message.reply_text(f"❌ 会话 `{session_id}` 不存在", parse_mode="Markdown")
|
|
444
|
+
return
|
|
445
|
+
|
|
446
|
+
# Try to send exit command
|
|
447
|
+
message_queue.push(session_id, "exit")
|
|
448
|
+
|
|
449
|
+
await update.message.reply_text(
|
|
450
|
+
f"🗑️ 正在删除会话 `{session_id}`...\n\n"
|
|
451
|
+
f"已发送退出命令。\n"
|
|
452
|
+
f"- 如果 AI 助手正在运行,它会收到退出指令\n"
|
|
453
|
+
f"- 如果进程已关闭,会话将被清理\n\n"
|
|
454
|
+
f"会话将在 10 秒后从列表中移除。",
|
|
455
|
+
parse_mode="Markdown"
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
# Wait a bit for the session to process exit
|
|
459
|
+
await asyncio.sleep(10)
|
|
460
|
+
|
|
461
|
+
# Remove session from registry
|
|
462
|
+
if registry.exists(session_id):
|
|
463
|
+
registry.sessions.pop(session_id, None)
|
|
464
|
+
registry._save_to_file()
|
|
465
|
+
await update.message.reply_text(
|
|
466
|
+
f"✅ 会话 `{session_id}` 已删除",
|
|
467
|
+
parse_mode="Markdown"
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
472
|
+
"""Show help message"""
|
|
473
|
+
help_text = """🤖 Telegram MCP Server 使用帮助
|
|
474
|
+
|
|
475
|
+
📋 会话管理
|
|
476
|
+
/sessions - 列出所有活跃会话
|
|
477
|
+
/status <session_id> - 查看会话状态
|
|
478
|
+
/delete <session_id> - 删除会话(发送退出命令)
|
|
479
|
+
|
|
480
|
+
💬 消息发送
|
|
481
|
+
/to <session_id> <消息> - 向指定会话发送消息
|
|
482
|
+
直接发送消息 - 自动发送到唯一等待的会话
|
|
483
|
+
|
|
484
|
+
📄 文件操作
|
|
485
|
+
/file <session_id> <file_path> - 查看文件内容(带语法高亮)
|
|
486
|
+
/file <session_id> <file_path> download - 下载文件
|
|
487
|
+
|
|
488
|
+
💬 自然语言请求(在无人值守模式下)
|
|
489
|
+
"查看 src/main.py" - AI 会自动发送文件
|
|
490
|
+
"发送 config.json 给我" - AI 会自动发送
|
|
491
|
+
"展示刚才修改的代码" - AI 会智能发送代码段
|
|
492
|
+
|
|
493
|
+
❓ 帮助
|
|
494
|
+
/help - 显示此帮助信息
|
|
495
|
+
|
|
496
|
+
💡 提示
|
|
497
|
+
- 如果只有一个会话在等待回复,直接发送消息即可
|
|
498
|
+
- 会话 ID 通常是项目目录名
|
|
499
|
+
- 使用 TELEGRAM_SESSION 环境变量自定义会话名
|
|
500
|
+
- 在无人值守模式下,AI 会智能判断何时发送代码/文件
|
|
501
|
+
"""
|
|
502
|
+
await update.message.reply_text(help_text)
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def setup_bot(token: str) -> Application:
|
|
506
|
+
"""Setup and configure bot"""
|
|
507
|
+
application = Application.builder().token(token).build()
|
|
508
|
+
|
|
509
|
+
# Add command handlers
|
|
510
|
+
application.add_handler(CommandHandler("sessions", cmd_sessions))
|
|
511
|
+
application.add_handler(CommandHandler("status", cmd_status))
|
|
512
|
+
application.add_handler(CommandHandler("to", cmd_to))
|
|
513
|
+
application.add_handler(CommandHandler("file", cmd_file))
|
|
514
|
+
application.add_handler(CommandHandler("delete", cmd_delete))
|
|
515
|
+
application.add_handler(CommandHandler("help", cmd_help))
|
|
516
|
+
application.add_handler(CommandHandler("start", cmd_help))
|
|
517
|
+
|
|
518
|
+
# Add callback query handler (for inline keyboard buttons)
|
|
519
|
+
application.add_handler(CallbackQueryHandler(handle_callback))
|
|
520
|
+
|
|
521
|
+
# Add photo handler
|
|
522
|
+
application.add_handler(
|
|
523
|
+
MessageHandler(filters.PHOTO, handle_photo)
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
# Add plain message handler
|
|
527
|
+
application.add_handler(
|
|
528
|
+
MessageHandler(filters.TEXT & ~filters.COMMAND, handle_plain_message)
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
return application
|