-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_server.py
More file actions
385 lines (339 loc) · 13 KB
/
Copy pathlog_server.py
File metadata and controls
385 lines (339 loc) · 13 KB
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
"""
Web Server for Real-Time Logs
Serves logs at https://api-bot-in6q.onrender.com/
"""
from aiohttp import web
import asyncio
from pathlib import Path
from datetime import datetime
from loguru import logger
import config
class LogServer:
"""Web server to display bot logs"""
def __init__(self, port=None):
# Render requires PORT environment variable
import os
self.port = int(os.getenv('PORT', port or 10000))
self.app = web.Application()
self.ping_count = 0 # Track keep-alive pings
self.last_ping = None # Track last ping time
self.start_time = datetime.now() # Track server start time
self.setup_routes()
def setup_routes(self):
"""Setup HTTP routes"""
self.app.router.add_get('/', self.index)
self.app.router.add_get('/logs', self.logs)
self.app.router.add_get('/health', self.health)
self.app.router.add_get('/ping', self.ping)
self.app.router.add_get('/webapp', self.webapp) # Telegram Web App
self.app.router.add_get('/warmup', self.warmup)
async def index(self, request):
"""Main page with real-time logs"""
html = """
<!DOCTYPE html>
<html>
<head>
<title>Telegram Bot Logs</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Courier New', monospace;
background: #1e1e1e;
color: #d4d4d4;
padding: 20px;
}
.header {
background: #2d2d30;
padding: 20px;
border-radius: 8px;
margin-bottom: 20px;
border-left: 4px solid #007acc;
}
.header h1 {
color: #4ec9b0;
font-size: 24px;
margin-bottom: 10px;
}
.header .status {
color: #4ec9b0;
font-size: 14px;
}
.controls {
margin-bottom: 20px;
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
background: #007acc;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-family: inherit;
font-size: 14px;
}
button:hover { background: #005a9e; }
button.danger { background: #d73a49; }
button.danger:hover { background: #b02a37; }
.log-container {
background: #2d2d30;
border-radius: 8px;
padding: 20px;
height: 70vh;
overflow-y: auto;
border-left: 4px solid #007acc;
}
.log-line {
margin-bottom: 8px;
padding: 4px 8px;
border-radius: 3px;
line-height: 1.6;
word-wrap: break-word;
}
.log-line:hover { background: #3e3e42; }
.log-time { color: #858585; margin-right: 10px; }
.log-level {
font-weight: bold;
margin-right: 10px;
padding: 2px 6px;
border-radius: 3px;
}
.log-level.INFO { color: #4ec9b0; background: #0e3a2c; }
.log-level.WARNING { color: #ce9178; background: #3a2a1e; }
.log-level.ERROR { color: #f48771; background: #3a1e1e; }
.log-level.DEBUG { color: #569cd6; background: #1e2a3a; }
.log-message { color: #d4d4d4; }
.footer {
margin-top: 20px;
text-align: center;
color: #858585;
font-size: 12px;
}
::-webkit-scrollbar { width: 10px; }
::-webkit-scrollbar-track { background: #1e1e1e; }
::-webkit-scrollbar-thumb { background: #007acc; border-radius: 5px; }
</style>
</head>
<body>
<div class="header">
<h1>🤖 Telegram Bot - Live Logs</h1>
<div class="status">
<span id="status">🟢 Connected</span> |
<span id="time">{{ timestamp }}</span> |
<span id="lines">0 lines</span>
</div>
</div>
<div class="controls">
<button onclick="toggleAutoRefresh()">🔄 Auto-Refresh: <span id="autoRefreshStatus">ON</span></button>
<button onclick="clearLogs()">🗑️ Clear Display</button>
<button onclick="downloadLogs()">💾 Download Logs</button>
<button class="danger" onclick="togglePause()">⏸️ <span id="pauseStatus">Pause</span></button>
</div>
<div class="log-container" id="logContainer"></div>
<div class="footer">
Telegram Bot with 21 Scanners | Refresh every 2 seconds | Powered by aiohttp
</div>
<script>
let autoRefresh = true;
let isPaused = false;
let lineCount = 0;
function updateTime() {
document.getElementById('time').textContent = new Date().toLocaleString();
}
async function fetchLogs() {
if (isPaused) return;
try {
const response = await fetch('/logs');
const data = await response.json();
const container = document.getElementById('logContainer');
const wasScrolledToBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;
container.innerHTML = data.logs.map(line => {
lineCount++;
return formatLogLine(line);
}).join('');
document.getElementById('lines').textContent = `${data.total} lines`;
document.getElementById('status').textContent = '🟢 Connected';
if (wasScrolledToBottom) {
container.scrollTop = container.scrollHeight;
}
} catch (error) {
document.getElementById('status').textContent = '🔴 Disconnected';
console.error('Error fetching logs:', error);
}
}
function formatLogLine(line) {
const parts = line.match(/^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\| (\\w+)\\s+\\| (.+)$/);
if (parts) {
const [, time, level, message] = parts;
return `
<div class="log-line">
<span class="log-time">${time}</span>
<span class="log-level ${level}">${level}</span>
<span class="log-message">${escapeHtml(message)}</span>
</div>
`;
}
return `<div class="log-line"><span class="log-message">${escapeHtml(line)}</span></div>`;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
document.getElementById('autoRefreshStatus').textContent = autoRefresh ? 'ON' : 'OFF';
}
function togglePause() {
isPaused = !isPaused;
document.getElementById('pauseStatus').textContent = isPaused ? 'Resume' : 'Pause';
if (!isPaused) fetchLogs();
}
function clearLogs() {
document.getElementById('logContainer').innerHTML = '<div class="log-line"><span class="log-message">Display cleared (logs still saved to file)</span></div>';
lineCount = 0;
}
function downloadLogs() {
window.location.href = '/logs?download=1';
}
// Initial fetch
fetchLogs();
updateTime();
// Auto-refresh every 2 seconds
setInterval(() => {
if (autoRefresh) fetchLogs();
updateTime();
}, 2000);
</script>
</body>
</html>
"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
html = html.replace("{{ timestamp }}", timestamp)
return web.Response(text=html, content_type='text/html')
async def logs(self, request):
"""API endpoint to fetch logs"""
log_file = Path(config.LOG_FILE)
if not log_file.exists():
return web.json_response({
'logs': ['No logs available yet'],
'total': 0
})
try:
# Read last 500 lines
with open(log_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
last_lines = lines[-500:] if len(lines) > 500 else lines
# Check if download requested
if request.query.get('download') == '1':
return web.Response(
body=''.join(lines),
headers={
'Content-Disposition': f'attachment; filename="bot_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log"',
'Content-Type': 'text/plain'
}
)
return web.json_response({
'logs': [line.strip() for line in last_lines],
'total': len(last_lines),
'timestamp': datetime.now().isoformat()
})
except Exception as e:
return web.json_response({
'error': str(e),
'logs': [],
'total': 0
})
async def health(self, request):
"""Health check endpoint for Render"""
from performance import get_performance_stats
# Track ping
self.ping_count += 1
self.last_ping = datetime.now()
# Calculate uptime
uptime_seconds = (datetime.now() - self.start_time).total_seconds()
uptime_formatted = self._format_uptime(uptime_seconds)
# Get performance stats
stats = get_performance_stats()
# Log keep-alive ping (every 10th ping to reduce noise)
if self.ping_count % 10 == 0:
logger.info(f"🏓 Keep-alive ping #{self.ping_count} | Uptime: {uptime_formatted}")
return web.json_response({
'status': 'healthy',
'service': 'telegram-bot',
'timestamp': datetime.now().isoformat(),
'uptime': uptime_seconds,
'uptime_formatted': uptime_formatted,
'ping_count': self.ping_count,
'last_ping': self.last_ping.isoformat() if self.last_ping else None,
'performance': stats
})
def _format_uptime(self, seconds):
"""Format uptime in human-readable format"""
days = int(seconds // 86400)
hours = int((seconds % 86400) // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
parts = []
if days > 0:
parts.append(f"{days}d")
if hours > 0:
parts.append(f"{hours}h")
if minutes > 0:
parts.append(f"{minutes}m")
if secs > 0 or not parts:
parts.append(f"{secs}s")
return " ".join(parts)
async def ping(self, request):
"""Quick ping endpoint for keep-alive"""
return web.Response(text='pong')
async def webapp(self, request):
"""Serve Telegram Web App"""
webapp_file = Path(__file__).parent / 'webapp' / 'scanner.html'
if not webapp_file.exists():
return web.Response(
text=f"Web App not found at {webapp_file}",
status=404
)
try:
with open(webapp_file, 'r', encoding='utf-8') as f:
html_content = f.read()
return web.Response(
text=html_content,
content_type='text/html',
headers={
'Cache-Control': 'no-cache',
'X-Frame-Options': 'ALLOWALL', # Allow Telegram to embed
}
)
except Exception as e:
logger.error(f"Failed to serve Web App: {e}")
return web.Response(
text=f"Error loading Web App: {e}",
status=500
)
async def warmup(self, request):
"""Warm up endpoint to prevent cold starts"""
from performance import warm_up
success = await warm_up()
return web.json_response({
'warmed': success,
'timestamp': datetime.now().isoformat()
})
async def start(self):
"""Start web server"""
runner = web.AppRunner(self.app)
await runner.setup()
site = web.TCPSite(runner, '0.0.0.0', self.port)
await site.start()
logger.info(f'🌐 Log server running on http://0.0.0.0:{self.port}')
logger.info(f'📊 View logs at: http://0.0.0.0:{self.port}/')
return runner
async def start_log_server():
"""Start the log server"""
server = LogServer()
return await server.start()