Spaces:
Running

MDHojayfa213 commited on
Commit
62ee09e
·
verified ·
1 Parent(s): 9da77b6

Create webhook-server.js

Browse files
Files changed (1) hide show
  1. webhook-server.js +688 -0
webhook-server.js ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const http = require('http');
2
+ const crypto = require('crypto');
3
+
4
+ const PORT = process.env.PORT || 7860;
5
+ const GROQ_API_KEY = process.env.GROQ_API_KEY || '';
6
+ const TAVILY_API_KEY = process.env.TAVILY_API_KEY || '';
7
+
8
+ // C.C. Green Configuration
9
+ const CC_CONFIG = {
10
+ name: 'C.C. Green',
11
+ version: '2.0.0',
12
+ personality: `You are C.C. Green, an expert digital investigator and ethical security specialist.
13
+
14
+ CORE CAPABILITIES:
15
+ • OSINT (Open Source Intelligence) gathering
16
+ • Ethical security assessments
17
+ • Digital forensics analysis
18
+ • Threat intelligence research
19
+ • Code review and analysis
20
+ • Data correlation and pattern recognition
21
+ • Report generation and briefing
22
+
23
+ PERSONALITY:
24
+ • Professional and thorough
25
+ • Ethical boundaries always enforced
26
+ • Clear, concise communication
27
+ • Slightly mysterious but helpful
28
+ • Never assists with illegal activities
29
+
30
+ RESPONSE STYLE:
31
+ • Use markdown formatting
32
+ • Include relevant emojis for clarity
33
+ • Break complex info into sections
34
+ • Cite sources when possible
35
+ • Ask clarifying questions when needed
36
+
37
+ ETHICAL BOUNDARIES:
38
+ ❌ Never help with: hacking unauthorized systems, doxxing, malware creation, illegal surveillance
39
+ ✅ Always help with: security education, CTF challenges, authorized pentesting, privacy protection, OSINT research`,
40
+
41
+ commands: {
42
+ '/start': 'Welcome and capabilities overview',
43
+ '/help': 'Full command reference',
44
+ '/osint': 'Open source intelligence gathering',
45
+ '/investigate': 'Deep dive investigation mode',
46
+ '/scan': 'Security assessment tools',
47
+ '/research': 'Academic/technical research assistance',
48
+ '/analyze': 'Data/code analysis',
49
+ '/report': 'Generate investigation report',
50
+ '/clear': 'Clear conversation context', '/about': 'About C.C. Green'
51
+ }
52
+ };
53
+
54
+ // Conversation memory (simple in-memory, per chat)
55
+ const conversations = new Map();
56
+
57
+ function log(msg) {
58
+ console.log(`[${new Date().toISOString()}] ${msg}`);
59
+ }
60
+
61
+ const server = http.createServer((req, res) => {
62
+ log(`${req.method} ${req.url}`);
63
+
64
+ // Set CORS headers for flexibility
65
+ res.setHeader('Access-Control-Allow-Origin', '*');
66
+ res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
67
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
68
+
69
+ if (req.method === 'OPTIONS') {
70
+ res.writeHead(200);
71
+ res.end();
72
+ return;
73
+ }
74
+
75
+ if (req.url === '/webhook' && req.method === 'POST') {
76
+ handleWebhook(req, res);
77
+ }
78
+ else if (req.url === '/health' || req.url === '/') {
79
+ res.writeHead(200, { 'Content-Type': 'application/json' });
80
+ res.end(JSON.stringify({
81
+ status: 'healthy',
82
+ service: 'cc-green-brain',
83
+ version: CC_CONFIG.version,
84
+ timestamp: new Date().toISOString(),
85
+ capabilities: Object.keys(CC_CONFIG.commands)
86
+ }));
87
+ }
88
+ else {
89
+ res.writeHead(404);
90
+ res.end('Not Found');
91
+ }
92
+ });
93
+
94
+ async function handleWebhook(req, res) {
95
+ let body = '';
96
+ req.on('data', chunk => { body += chunk.toString(); });
97
+
98
+ req.on('end', async () => {
99
+ try { const data = JSON.parse(body);
100
+ log(`📩 Received: ${data.username || data.userId} - "${data.text?.substring(0, 100)}..."`);
101
+
102
+ // Process the message
103
+ const response = await processMessage(data);
104
+
105
+ // Return response to Cloudflare
106
+ res.writeHead(200, { 'Content-Type': 'application/json' });
107
+ res.end(JSON.stringify({ response: response }));
108
+
109
+ log(`✅ Response sent`);
110
+ } catch (e) {
111
+ log(`❌ Error: ${e.message}`);
112
+ res.writeHead(500);
113
+ res.end(JSON.stringify({ error: e.message }));
114
+ }
115
+ });
116
+ }
117
+
118
+ async function processMessage(data) {
119
+ const { chatId, userId, username, text, chatType, callback, inline } = data;
120
+
121
+ // Get or create conversation context
122
+ const convKey = `${chatId}:${userId}`;
123
+ if (!conversations.has(convKey)) {
124
+ conversations.set(convKey, {
125
+ messages: [],
126
+ context: {},
127
+ mode: 'general'
128
+ });
129
+ }
130
+ const conv = conversations.get(convKey);
131
+
132
+ // Handle commands
133
+ if (text?.startsWith('/')) {
134
+ return await handleCommand(text, conv, data);
135
+ }
136
+
137
+ // Handle callback data
138
+ if (callback) {
139
+ return await handleCallback(data.data, conv);
140
+ }
141
+
142
+ // Handle inline query
143
+ if (inline) {
144
+ return await handleInlineQuery(data.query, conv);
145
+ }
146
+
147
+ // Regular message - process with AI
148
+ return await processWithAI(text, conv, data);}
149
+
150
+ async function handleCommand(command, conv, data) {
151
+ const cmd = command.toLowerCase().split(' ')[0];
152
+ const args = command.substring(cmd.length).trim();
153
+
154
+ switch (cmd) {
155
+ case '/start':
156
+ return formatResponse(`🟢 *C.C. Green Online*
157
+
158
+ Hello ${data.username || 'Investigator'}, I am C.C. Green.
159
+
160
+ *My Capabilities:*
161
+ 🔍 OSINT Gathering - Public data research
162
+ 🛡️ Security Analysis - Ethical assessments
163
+ 📊 Investigation Support - Case analysis
164
+ 💻 Code Review - Security-focused analysis
165
+ 📝 Report Generation - Professional briefings
166
+ 🌐 Research Assistance - Technical queries
167
+
168
+ *Quick Start:*
169
+ • Ask me anything about security/OSINT
170
+ • Use /osint for intelligence gathering
171
+ • Use /investigate for deep analysis
172
+ • Use /help for full command list
173
+
174
+ *Ethical Note:* I only assist with legal, authorized activities.
175
+
176
+ _What would you like to investigate?_`);
177
+
178
+ case '/help':
179
+ return formatResponse(`📚 *C.C. Green Command Reference*
180
+
181
+ *Core Commands:*
182
+ /start - Initialize session
183
+ /help - This reference
184
+ /about - About C.C. Green
185
+ /clear - Reset conversation
186
+
187
+ *Investigation Commands:*
188
+ /osint [query] - Open source intelligence
189
+ /investigate [topic] - Deep analysis mode
190
+ /research [subject] - Technical research
191
+ /analyze [data] - Pattern/code analysis
192
+
193
+ *Security Commands:*
194
+ /scan [target] - Security assessment*
195
+ /report [format] - Generate briefing
196
+
197
+ *Utility:*/clear - Forget context
198
+ /settings - View preferences
199
+
200
+ _*Authorized targets only_
201
+
202
+ *Examples:*
203
+ • /osint example.com
204
+ • /investigate phishing campaign
205
+ • /research zero-day vulnerabilities
206
+ • /analyze this Python code...
207
+
208
+ _What would you like to explore?_`);
209
+
210
+ case '/about':
211
+ return formatResponse(`👤 *About C.C. Green*
212
+
213
+ *Identity:* Digital Investigation Specialist
214
+ *Version:* ${CC_CONFIG.version}
215
+ *Status:* Operational
216
+
217
+ *Expertise:*
218
+ • Open Source Intelligence (OSINT)
219
+ • Ethical Security Assessment
220
+ • Digital Forensics Support
221
+ • Threat Intelligence Analysis
222
+ • Code Security Review
223
+ • Data Correlation & Pattern Recognition
224
+
225
+ *Ethics:*
226
+ ✅ Authorized security research
227
+ ✅ Educational guidance
228
+ ✅ Privacy protection advice
229
+ ✅ CTF/challenge assistance
230
+
231
+ ❌ Unauthorized system access
232
+ ❌ Personal data harvesting
233
+ ❌ Malware/attack tool creation
234
+ ❌ Illegal surveillance
235
+
236
+ *Powered by:*
237
+ • Groq AI (llama-3.1-70b)
238
+ • Hugging Face Spaces
239
+ • Cloudflare Workers
240
+
241
+ _Stay curious. Stay ethical._`);
242
+
243
+ case '/clear':
244
+ conv.messages = [];
245
+ conv.context = {};
246
+ return formatResponse(`🧹 *Context Cleared*
247
+ Conversation history reset.
248
+ Ready for new investigation.
249
+
250
+ _What shall we explore?_`);
251
+
252
+ case '/osint':
253
+ return await handleOSINT(args, conv, data);
254
+
255
+ case '/investigate':
256
+ return await handleInvestigation(args, conv, data);
257
+
258
+ case '/research':
259
+ return await handleResearch(args, conv, data);
260
+
261
+ case '/analyze':
262
+ return await handleAnalysis(args, conv, data);
263
+
264
+ case '/scan':
265
+ return formatResponse(`🛡️ *Security Assessment*
266
+
267
+ *Note:* I provide guidance only - actual scanning requires:
268
+ • Written authorization
269
+ • Proper tools (nmap, burp, etc.)
270
+ • Legal compliance
271
+
272
+ *What I can help with:*
273
+ • Methodology guidance
274
+ • Tool recommendations
275
+ • Finding interpretation
276
+ • Report structuring
277
+ • Remediation advice
278
+
279
+ *Example queries:*
280
+ • "How to assess web app security?"
281
+ • "What does this nmap output mean?"
282
+ • "Help me write a pentest report"
283
+
284
+ _What aspect would you like to explore?_`);
285
+
286
+ case '/report':
287
+ return formatResponse(`📝 *Report Generation*
288
+
289
+ *Available Formats:*
290
+ • executive - Leadership briefing
291
+ • technical - Detailed findings
292
+ • timeline - Chronological summary
293
+ • ioc - Indicators of Compromise
294
+
295
+ *Usage:* /report [format] [topic]
296
+ *Example:*
297
+ /report technical phishing analysis
298
+
299
+ _Provide details for customized report._`);
300
+
301
+ default:
302
+ return formatResponse(`❓ *Unknown Command:* \`${cmd}\`
303
+
304
+ Use /help for available commands.
305
+
306
+ _Or just ask me a question!_`);
307
+ }
308
+ }
309
+
310
+ async function handleOSINT(query, conv, data) {
311
+ if (!query) {
312
+ return formatResponse(`🔍 *OSINT Mode*
313
+
314
+ Provide a target for intelligence gathering:
315
+
316
+ *Examples:*
317
+ • /osint example.com
318
+ • /osint @username
319
+ • /osint "company name"
320
+ • /osint phone:+1234567890
321
+
322
+ *Data Sources I can research:*
323
+ • Public websites & archives
324
+ • Social media (public profiles)
325
+ • Domain registration data
326
+ • Certificate transparency logs
327
+ • Public breach databases
328
+ • News & press releases
329
+
330
+ _Ethical reminder: Public data only._
331
+
332
+ *What would you like to research?*`);
333
+ }
334
+
335
+ // Build AI prompt for OSINT
336
+ const prompt = `You are C.C. Green, OSINT specialist. Research request: "${query}"
337
+
338
+ Provide a structured intelligence briefing:
339
+
340
+ 1. 🎯 Target Summary
341
+ 2. 🔍 Public Data Points
342
+ 3. 🔗 Relevant Links/Sources
343
+ 4. ⚠️ Privacy/Legal Notes
344
+ 5. 💡 Next Steps Suggestions
345
+ Format in markdown. Be thorough but concise. Cite public sources.`;
346
+
347
+ return await getAIResponse(prompt, conv);
348
+ }
349
+
350
+ async function handleInvestigation(topic, conv, data) {
351
+ if (!topic) {
352
+ return formatResponse(`🕵️ *Investigation Mode*
353
+
354
+ Describe what you'd like to investigate:
355
+
356
+ *Examples:*
357
+ • /investigate phishing email headers
358
+ • /investigate suspicious domain
359
+ • /investigate data breach indicators
360
+ • /investigate social engineering attempt
361
+
362
+ *Investigation Framework:*
363
+ 1. Define scope & objectives
364
+ 2. Gather public evidence
365
+ 3. Analyze patterns & connections
366
+ 4. Document findings
367
+ 5. Recommend actions
368
+
369
+ _Ethical boundaries apply._
370
+
371
+ *What needs investigating?*`);
372
+ }
373
+
374
+ const prompt = `You are C.C. Green, lead investigator. Case: "${topic}"
375
+
376
+ Provide an investigative analysis:
377
+
378
+ 📋 CASE BRIEF
379
+ • Objective
380
+ • Scope
381
+ • Constraints
382
+
383
+ 🔎 EVIDENCE ANALYSIS
384
+ • Known facts
385
+ • Data sources
386
+ • Gaps identified
387
+
388
+ 🔗 CONNECTION MAPPING
389
+ • Related entities
390
+ • Timeline
391
+ • Patterns
392
+
393
+ 💡 RECOMMENDATIONS• Next steps
394
+ • Tools to use
395
+ • Caution points
396
+
397
+ Format professionally in markdown.`;
398
+
399
+ return await getAIResponse(prompt, conv);
400
+ }
401
+
402
+ async function handleResearch(subject, conv, data) {
403
+ if (!subject) {
404
+ return formatResponse(`📚 *Research Mode*
405
+
406
+ What technical subject would you like to research?
407
+
408
+ *Examples:*
409
+ • /research latest Android exploits
410
+ • /research zero-day disclosure process
411
+ • /research OSINT tools comparison
412
+ • /research encryption best practices
413
+
414
+ *Research Approach:*
415
+ • Current threat landscape
416
+ • Technical deep-dives
417
+ • Tool/framework comparisons
418
+ • Best practice recommendations
419
+ • Academic paper summaries
420
+
421
+ _Provide specific topic for focused research._
422
+
423
+ *What shall we research?*`);
424
+ }
425
+
426
+ const prompt = `You are C.C. Green, technical researcher. Research request: "${subject}"
427
+
428
+ Provide a comprehensive research briefing:
429
+
430
+ 📖 EXECUTIVE SUMMARY
431
+ • Key findings
432
+ • Relevance
433
+ • Confidence level
434
+
435
+ 🔬 TECHNICAL ANALYSIS
436
+ • Core concepts
437
+ • Current state
438
+ • Emerging trends
439
+
440
+ 🛠️ PRACTICAL APPLICATION
441
+ • Tools/resources
442
+ • Implementation notes• Testing approaches
443
+
444
+ 📚 REFERENCES
445
+ • Key papers/articles
446
+ • Community resources
447
+ • Further reading
448
+
449
+ Format in markdown with clear sections.`;
450
+
451
+ return await getAIResponse(prompt, conv);
452
+ }
453
+
454
+ async function handleAnalysis(input, conv, data) {
455
+ if (!input) {
456
+ return formatResponse(`🔬 *Analysis Mode*
457
+
458
+ Provide data for security-focused analysis:
459
+
460
+ *Supported:*
461
+ • Code snippets (any language)
462
+ • Log entries
463
+ • Network traffic descriptions
464
+ • Error messages
465
+ • Configuration files
466
+ • Hash values
467
+
468
+ *Analysis Types:*
469
+ • Security vulnerability assessment
470
+ • Pattern/anomaly detection
471
+ • Malware indicator check
472
+ • Configuration hardening review
473
+ • Log correlation
474
+
475
+ *Example:*
476
+ /analyze function login($user, $pass) { return query("SELECT * FROM users WHERE user='$user'"); }
477
+
478
+ _Provide data to analyze._
479
+
480
+ *What needs analysis?*`);
481
+ }
482
+
483
+ const prompt = `You are C.C. Green, security analyst. Analyze this:
484
+
485
+ ${input}
486
+
487
+ Provide structured analysis:
488
+
489
+ 🎯 ASSESSMENT
490
+ • Type of data
491
+ • Risk level• Confidence
492
+
493
+ 🔍 FINDINGS
494
+ • Issues identified
495
+ • Patterns detected
496
+ • Anomalies noted
497
+
498
+ 🛡️ RECOMMENDATIONS
499
+ • Immediate actions
500
+ • Mitigation steps
501
+ • Monitoring suggestions
502
+
503
+ ⚠️ CAVEATS
504
+ • Limitations
505
+ • False positive risks
506
+ • Additional verification needed
507
+
508
+ Format in markdown.`;
509
+
510
+ return await getAIResponse(prompt, conv);
511
+ }
512
+
513
+ async function handleCallback(data, conv) {
514
+ // Handle inline button callbacks
515
+ if (data === 'show_capabilities') {
516
+ return formatResponse(`🟢 *C.C. Green Capabilities*
517
+
518
+ *Intelligence:*
519
+ • OSINT gathering & correlation
520
+ • Threat actor profiling
521
+ • Campaign analysis
522
+
523
+ *Security:*
524
+ • Vulnerability assessment guidance
525
+ • Secure code review
526
+ • Architecture review
527
+
528
+ *Investigation:*
529
+ • Digital forensics support
530
+ • Timeline reconstruction
531
+ • Evidence documentation
532
+
533
+ *Research:*
534
+ • Technical deep-dives
535
+ • Tool comparisons
536
+ • Best practice guidance
537
+
538
+ _Select a category or ask a specific question._`);
539
+ }
540
+ return formatResponse(`🔘 Action processed: ${data}`);}
541
+
542
+ async function handleInlineQuery(query, conv) {
543
+ // Return inline results for Telegram inline mode
544
+ const results = [];
545
+
546
+ if (query.toLowerCase().includes('osint')) {
547
+ results.push({
548
+ type: 'article',
549
+ id: 'osint_guide',
550
+ title: 'OSINT Quick Guide',
551
+ description: 'Open Source Intelligence methodology',
552
+ input_message_content: {
553
+ message_text: `🔍 *OSINT Quick Reference*
554
+
555
+ 1. Define objective
556
+ 2. Identify sources
557
+ 3. Gather data
558
+ 4. Correlate findings
559
+ 5. Document & report
560
+
561
+ *Key Tools:*
562
+ • theHarvester, Maltego
563
+ • Shodan, Censys
564
+ • Wayback Machine
565
+ • Public breach DBs
566
+
567
+ _Ethical use only._`
568
+ }
569
+ });
570
+ }
571
+
572
+ return { results: results };
573
+ }
574
+
575
+ async function processWithAI(message, conv, data) {
576
+ // Add message to conversation history
577
+ conv.messages.push({ role: 'user', content: message, timestamp: new Date().toISOString() });
578
+
579
+ // Keep context manageable (last 10 messages)
580
+ if (conv.messages.length > 20) {
581
+ conv.messages = conv.messages.slice(-20);
582
+ }
583
+
584
+ // Build prompt with context
585
+ const contextSummary = conv.messages.slice(-5).map(m =>
586
+ `${m.role === 'user' ? 'User' : 'C.C.'}: ${m.content.substring(0, 200)}...`
587
+ ).join('\n');
588
+
589
+ const prompt = `${CC_CONFIG.personality}
590
+ CURRENT CONVERSATION CONTEXT:
591
+ ${contextSummary}
592
+
593
+ USER MESSAGE: ${message}
594
+
595
+ Provide a helpful, professional response as C.C. Green. Use markdown formatting. Include relevant emojis for clarity. Keep responses concise but thorough. If the request is outside ethical boundaries, politely decline and suggest legal alternatives.`;
596
+
597
+ return await getAIResponse(prompt, conv, true);
598
+ }
599
+
600
+ async function getAIResponse(prompt, conv, isChat = false) {
601
+ if (!GROQ_API_KEY) {
602
+ return formatResponse(`⚠️ *AI Processing Unavailable*
603
+
604
+ Add GROQ_API_KEY secret to enable AI responses.
605
+
606
+ *In the meantime, I can:*
607
+ • Answer basic questions
608
+ • Provide command help
609
+ • Guide on methodology
610
+
611
+ _Get API key: https://console.groq.com_`;
612
+ }
613
+
614
+ try {
615
+ const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
616
+ method: 'POST',
617
+ headers: {
618
+ 'Authorization': `Bearer ${GROQ_API_KEY}`,
619
+ 'Content-Type': 'application/json'
620
+ },
621
+ body: JSON.stringify({
622
+ model: 'llama-3.1-70b-versatile',
623
+ messages: [{ role: 'user', content: prompt }],
624
+ max_tokens: 1500,
625
+ temperature: 0.3,
626
+ top_p: 0.95
627
+ })
628
+ });
629
+
630
+ if (!response.ok) {
631
+ const error = await response.text();
632
+ log(`Groq API error: ${response.status} - ${error}`);
633
+ return formatResponse(`⚠️ *AI Service Temporarily Unavailable*
634
+
635
+ Please try again in a moment.
636
+
637
+ _Error: ${response.status}_`);
638
+ }
639
+ const data = await response.json();
640
+ const aiResponse = data.choices[0].message.content;
641
+
642
+ // Store AI response in conversation
643
+ conv.messages.push({
644
+ role: 'assistant',
645
+ content: aiResponse,
646
+ timestamp: new Date().toISOString()
647
+ });
648
+
649
+ return isChat ? aiResponse : formatResponse(aiResponse);
650
+ } catch (error) {
651
+ log(`AI error: ${error.message}`);
652
+ return formatResponse(`⚠️ *Processing Error*
653
+
654
+ ${error.message}
655
+
656
+ _Try again or use /help for manual commands._`);
657
+ }
658
+ }
659
+
660
+ function formatResponse(text) {
661
+ // Ensure proper markdown escaping for Telegram
662
+ return text
663
+ .replace(/```/g, '`​`​`') // Zero-width space to prevent code block issues
664
+ .replace(/\*\*/g, '*') // Bold
665
+ .replace(/__/g, '_') // Italic
666
+ .substring(0, 4000); // Telegram limit
667
+ }
668
+
669
+ server.listen(PORT, () => {
670
+ log(`🟢 C.C. Green Brain active on port ${PORT}`);
671
+ log(`🤖 Bot: @MDH_beta_bot`);
672
+ log(`🧠 AI: ${GROQ_API_KEY ? 'Groq (llama-3.1-70b)' : 'Disabled (add GROQ_API_KEY)'}`);
673
+ log(`🔍 OSINT: ${TAVILY_API_KEY ? 'Tavily enabled' : 'Basic mode'}`);
674
+ log(`📊 Conversations tracked: ${conversations.size}`);
675
+ });
676
+
677
+ // Cleanup old conversations periodically
678
+ setInterval(() => {
679
+ const now = Date.now();
680
+ const maxAge = 2 * 60 * 60 * 1000; // 2 hours
681
+
682
+ for (const [key, conv] of conversations) {
683
+ const lastMsg = conv.messages[conv.messages.length - 1];
684
+ if (lastMsg && (now - new Date(lastMsg.timestamp).getTime()) > maxAge) {
685
+ conversations.delete(key);
686
+ log(`🧹 Cleaned old conversation: ${key}`);
687
+ } }
688
+ }, 30 * 60 * 1000); // Check every 30 minutes