-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2089 lines (1757 loc) · 86.4 KB
/
main.py
File metadata and controls
2089 lines (1757 loc) · 86.4 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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# main.py
import asyncio
import json
import logging
import os
import sys
import time
import traceback
import base64
import mimetypes
from collections import Counter, deque
from datetime import datetime, timedelta, timezone
from typing import Any, Deque, Dict, List, Optional
import aiohttp
import discord
from aiohttp import ClientSession, ClientTimeout, TCPConnector, web
from discord import Embed, Activity, ActivityType
from discord.ext import commands, tasks
from discord.ext.commands import Bot, Context
from openai import AsyncOpenAI
from rich.console import Console
from rich.logging import RichHandler
from tiktoken import encoding_for_model
import tiktoken
import random
from PIL import Image
from io import BytesIO
# Local imports
import config
from database import db_manager
logger = logging.getLogger('SecurePathAgent')
console = Console()
def setup_logging() -> logging.Logger:
logger.setLevel(getattr(logging, config.LOG_LEVEL, 'INFO'))
console_handler = RichHandler(rich_tracebacks=True, console=console)
console_handler.setLevel(getattr(logging, config.LOG_LEVEL, 'INFO'))
console_handler.setFormatter(logging.Formatter(config.LOG_FORMAT))
logger.addHandler(console_handler)
for module in ['discord', 'discord.http', 'discord.gateway']:
logging.getLogger(module).setLevel(logging.WARNING)
return logger
logger = setup_logging()
aclient = AsyncOpenAI(api_key=config.OPENAI_API_KEY)
intents = discord.Intents.default()
intents.message_content = True
bot = Bot(command_prefix=config.BOT_PREFIX, intents=intents)
conn: Optional[TCPConnector] = None
session: Optional[ClientSession] = None
user_contexts: Dict[int, Deque[Dict[str, Any]]] = {}
message_counter = Counter()
command_counter = Counter()
api_call_counter = 0
total_token_cost = 0.0 # Added for tracking total token cost
# Usage data tracking
usage_data = {
'perplexity': {
'requests': 0,
'tokens': 0,
'cost': 0.0,
},
'openai_gpt5': {
'input_tokens': 0,
'cached_input_tokens': 0,
'cost': 0.0,
},
'openai_gpt5_vision': {
'requests': 0,
'tokens': 0,
'cost': 0.0,
'average_tokens_per_request': 0.0,
}
}
class RateLimiter:
def __init__(self, max_calls: int, interval: int):
self.max_calls = max_calls
self.interval = interval
self.calls: Dict[int, List[float]] = {}
def is_rate_limited(self, user_id: int) -> bool:
current_time = time.time()
self.calls.setdefault(user_id, [])
self.calls[user_id] = [t for t in self.calls[user_id] if current_time - t <= self.interval]
if len(self.calls[user_id]) >= self.max_calls:
logger.debug(f"User {user_id} is rate limited. {len(self.calls[user_id])} calls in the last {self.interval} seconds.")
return True
self.calls[user_id].append(current_time)
logger.debug(f"User {user_id} made an API call. Total calls in the last {self.interval} seconds: {len(self.calls[user_id])}")
return False
api_rate_limiter = RateLimiter(config.API_RATE_LIMIT_MAX, config.API_RATE_LIMIT_INTERVAL)
# No rate limiting - small server optimization
def get_user_context(user_id: int) -> Deque[Dict[str, Any]]:
return user_contexts.setdefault(user_id, deque(maxlen=config.MAX_CONTEXT_MESSAGES))
def update_user_context(user_id: int, message_content: str, role: str) -> None:
context = get_user_context(user_id)
current_time = time.time()
if not context:
context.append({
'role': 'system',
'content': config.SYSTEM_PROMPT.strip(),
'timestamp': current_time,
})
logger.debug(f"Initialized context with system prompt for user {user_id}.")
if len(context) == 1 and role == 'user':
context.append({
'role': 'user',
'content': message_content.strip(),
'timestamp': current_time,
})
logger.debug(f"Appended first user message for user {user_id}: {message_content[:50]}...")
return
last_role = context[-1]['role']
if last_role == 'user' and role == 'assistant':
context.append({
'role': role,
'content': message_content.strip(),
'timestamp': current_time,
})
logger.debug(f"Appended assistant message for user {user_id}: {message_content[:50]}...")
elif last_role == 'assistant' and role == 'user':
context.append({
'role': role,
'content': message_content.strip(),
'timestamp': current_time,
})
logger.debug(f"Appended user message for user {user_id}: {message_content[:50]}...")
else:
logger.warning(f"Role mismatch for user {user_id}: Expected alternate role, got {role}. Message skipped.")
cutoff_time = current_time - config.MAX_CONTEXT_AGE
old_length = len(context)
user_contexts[user_id] = deque(
[msg for msg in context if msg['timestamp'] >= cutoff_time],
maxlen=config.MAX_CONTEXT_MESSAGES
)
new_length = len(user_contexts[user_id])
if new_length < old_length:
logger.debug(f"Removed {old_length - new_length} old messages from user {user_id}'s context.")
def get_context_messages(user_id: int) -> List[Dict[str, str]]:
context = get_user_context(user_id)
messages = [{"role": msg['role'], "content": msg['content']} for msg in context]
if not messages or messages[0]['role'] != 'system':
messages.insert(0, {
"role": "system",
"content": config.SYSTEM_PROMPT.strip(),
})
logger.debug("Inserted system prompt at the beginning of messages.")
cleaned_messages = [messages[0]]
for i in range(1, len(messages)):
last_role = cleaned_messages[-1]['role']
if last_role in ['system', 'assistant']:
expected_role = 'user'
elif last_role == 'user':
expected_role = 'assistant'
else:
logger.warning(f"Unknown last role '{last_role}' in context.")
continue
if messages[i]['role'] == expected_role:
cleaned_messages.append(messages[i])
else:
logger.warning(f"Role mismatch at message {i}: Expected {expected_role}, got {messages[i]['role']}")
logger.debug("Final cleaned context messages:")
for idx, msg in enumerate(cleaned_messages):
content_preview = msg['content'][:50] + '...' if len(msg['content']) > 50 else msg['content']
logger.debug(f"Message {idx}: Role={msg['role']}, Content={content_preview}")
return cleaned_messages
def truncate_prompt(prompt: str, max_completion_tokens: int, model: str = 'gpt-5') -> str:
try:
encoding = encoding_for_model(model)
except Exception:
encoding = tiktoken.get_encoding("cl100k_base")
tokens = encoding.encode(prompt)
if len(tokens) > max_completion_tokens:
truncated = encoding.decode(tokens[-max_completion_tokens:])
logger.debug(f"Truncated prompt from {len(tokens)} to {max_completion_tokens} tokens.")
return truncated
return prompt
def log_instance_info():
hostname = os.uname().nodename
pid = os.getpid()
logger.info(f"Bot instance started - Hostname: {hostname}, PID: {pid}")
def increment_api_call_counter():
global api_call_counter
api_call_counter += 1
logger.info(f"API call counter: {api_call_counter}")
def increment_token_cost(cost: float):
global total_token_cost
total_token_cost += cost
logger.info(f"Total token cost: ${total_token_cost:.6f}")
async def log_usage_to_db(user: discord.User, command: str, model: str,
input_tokens: int = 0, output_tokens: int = 0,
cached_tokens: int = 0, cost: float = 0.0,
guild_id: Optional[int] = None, channel_id: Optional[int] = None):
if db_manager.pool:
try:
await db_manager.log_usage(
user_id=user.id,
username=f"{user.name}#{user.discriminator}" if user.discriminator != "0" else user.name,
command=command,
model=model,
input_tokens=input_tokens,
output_tokens=output_tokens,
cached_tokens=cached_tokens,
cost=cost,
guild_id=guild_id,
channel_id=channel_id
)
except Exception as e:
logger.error(f"Failed to log usage to database: {e}")
def can_make_api_call(user_id: Optional[int] = None) -> tuple[bool, Optional[str]]:
return True, None
MAX_IMAGE_SIZE_BYTES = 5 * 1024 * 1024 # 5 MB limit
def estimate_tokens(image_size_bytes: int) -> int:
TOKENS_PER_BYTE = 1 / 100
estimated = int(image_size_bytes * TOKENS_PER_BYTE)
logger.debug(f"Estimated tokens based on image size ({image_size_bytes} bytes): {estimated} tokens")
return estimated
async def fetch_perplexity_response(user_id: int, new_message: str) -> Optional[str]:
if session is None:
logger.error("Session is not initialized")
raise Exception("🚫 Network session not available. Please try again.")
can_call, error_msg = can_make_api_call(user_id)
if not can_call:
logger.warning(f"Rate limit reached for user {user_id}")
raise Exception(error_msg)
headers = {
"Authorization": f"Bearer {config.PERPLEXITY_API_KEY}",
"Content-Type": "application/json"
}
current_date = datetime.now().strftime("%Y-%m-%d")
dynamic_system_prompt = f"Today is {current_date}. All information must be accurate up to this date. {config.SYSTEM_PROMPT} CRITICAL: No tables, no comparisons in table format. Use bullet points only. Keep responses under 600 words. Be concise and direct."
context_messages = get_context_messages(user_id)
if context_messages and context_messages[-1]['role'] != 'user':
context_messages.append({"role": "user", "content": new_message.strip()})
messages = [{"role": "system", "content": dynamic_system_prompt}] + context_messages
ninety_days_ago = (datetime.now() - timedelta(days=90)).strftime("%m/%d/%Y")
domain_filter = [
"ethereum.org",
"github.com",
"defillama.com",
"etherscan.io",
"coinmarketcap.com",
"coingecko.com",
"docs.uniswap.org",
"coindesk.com",
"-reddit.com",
"-pinterest.com"
]
logger.debug(f"Using Perplexity domain filter with {len(domain_filter)} elite sources.")
data = {
"model": "sonar-pro",
"messages": messages,
"max_completion_tokens": 800,
"temperature": 0.7,
"search_after_date_filter": ninety_days_ago,
"search_domain_filter": domain_filter,
"search_context_size": "high",
"return_citations": True,
"return_images": False
}
logger.info(f"Sending query to Perplexity API for user {user_id}")
usage_data['perplexity']['requests'] += 1
increment_api_call_counter()
start_time = time.time()
try:
timeout = ClientTimeout(total=config.PERPLEXITY_TIMEOUT)
async with session.post(config.PERPLEXITY_API_URL, json=data, headers=headers, timeout=timeout) as response:
elapsed_time = time.time() - start_time
logger.info(f"Perplexity API request completed in {elapsed_time:.2f} seconds")
if response.status == 200:
resp_json = await response.json()
answer = resp_json.get('choices', [{}])[0].get('message', {}).get('content', '')
citations = resp_json.get('choices', [{}])[0].get('extras', {}).get('citations', [])
search_results = resp_json.get('search_results', [])
logger.debug(f"Citations found: {len(citations)}, Search results: {len(search_results)}")
all_sources = []
for cite in citations:
title = cite.get('title', 'Source')
url = cite.get('url', '#')
if url != '#' and title != 'Source':
all_sources.append((title, url))
for result in search_results:
title = result.get('title', '')
url = result.get('url', '')
if url and title and (title, url) not in all_sources:
all_sources.append((title, url))
logger.debug(f"Total sources processed: {len(all_sources)}")
if all_sources:
formatted_citations = "\n\n**📚 Sources:**\n"
for i, (title, url) in enumerate(all_sources[:6], 1):
display_title = title[:60] + "..." if len(title) > 60 else title
formatted_citations += f"[{i}] [{display_title}]({url})\n"
formatted_citations += "\n*verify claims with original sources*"
answer += formatted_citations
else:
logger.warning("No citations found in Perplexity response")
usage = resp_json.get('usage', {})
prompt_tokens = usage.get('prompt_tokens', 0)
completion_tokens = usage.get('completion_tokens', 0)
total_tokens = usage.get('total_tokens', 0)
usage_data['perplexity']['tokens'] += total_tokens
cost = (usage_data['perplexity']['requests'] * 5 / 1000) + (usage_data['perplexity']['tokens'] / 1_000_000 * 1)
usage_data['perplexity']['cost'] = round(cost, 6)
increment_token_cost(cost)
logger.info(f"Perplexity API usage: Prompt Tokens={prompt_tokens}, Completion Tokens={completion_tokens}, Total Tokens={total_tokens}")
logger.info(f"Estimated Perplexity API call cost: ${cost:.6f}")
return answer
else:
response_text = await response.text()
logger.error(f"Perplexity API request failed with status {response.status}. Response: {response_text}")
except asyncio.TimeoutError:
logger.error(f"Request to Perplexity API timed out after {config.PERPLEXITY_TIMEOUT} seconds")
except Exception as e:
logger.error(f"Error in fetch_perplexity_response: {str(e)}")
logger.error(traceback.format_exc())
return None
async def fetch_openai_response(user_id: int, new_message: str, user: Optional[discord.User] = None,
command: str = "ask", guild_id: Optional[int] = None,
channel_id: Optional[int] = None) -> Optional[str]:
can_call, error_msg = can_make_api_call(user_id)
if not can_call:
logger.warning("Daily API call limit reached. Skipping API call.")
return None
context_messages = get_context_messages(user_id)
messages = [{"role": "system", "content": config.SYSTEM_PROMPT}] + context_messages
if not messages or messages[-1]['role'] != 'user' or messages[-1]['content'] != new_message:
messages.append({"role": "user", "content": new_message})
try:
response = await aclient.chat.completions.create(
model='gpt-5',
messages=messages,
max_completion_tokens=2000,
temperature=0.7,
)
answer = response.choices[0].message.content.strip()
if hasattr(response, 'usage'):
usage = response.usage
prompt_tokens = getattr(usage, 'prompt_tokens', 0)
cached_tokens = getattr(getattr(usage, 'prompt_tokens_details', object()), 'cached_tokens', 0) if hasattr(usage, 'prompt_tokens_details') else 0
completion_tokens = getattr(usage, 'completion_tokens', 0)
total_tokens = getattr(usage, 'total_tokens', 0)
else:
prompt_tokens, cached_tokens, completion_tokens, total_tokens = 0, 0, 0, 0
is_cached = cached_tokens >= 1024
if is_cached:
usage_data['openai_gpt5']['cached_input_tokens'] += cached_tokens
cost = (cached_tokens / 1_000_000 * 0.30) + (completion_tokens / 1_000_000 * 1.20)
logger.debug(f"Cache hit detected. Cached Tokens: {cached_tokens}, Completion Tokens: {completion_tokens}, Cost: ${cost:.6f}")
else:
usage_data['openai_gpt5']['input_tokens'] += prompt_tokens
cost = (prompt_tokens / 1_000_000 * 0.60) + (completion_tokens / 1_000_000 * 2.40)
logger.debug(f"No cache hit. Prompt Tokens: {prompt_tokens}, Completion Tokens: {completion_tokens}, Cost: ${cost:.6f}")
usage_data['openai_gpt5']['cost'] += cost
increment_token_cost(cost)
if user:
await log_usage_to_db(
user=user,
command=command,
model="gpt-5",
input_tokens=prompt_tokens,
output_tokens=completion_tokens,
cached_tokens=cached_tokens,
cost=cost,
guild_id=guild_id,
channel_id=channel_id
)
logger.info(f"OpenAI GPT-5 usage: Prompt Tokens={prompt_tokens}, Cached Tokens={cached_tokens}, Completion Tokens={completion_tokens}, Total Tokens={total_tokens}")
logger.info(f"Estimated OpenAI GPT-5 API call cost: ${cost:.6f}")
return answer
except Exception as e:
logger.error(f"Error fetching response from OpenAI: {str(e)}")
logger.error(traceback.format_exc())
return None
async def send_structured_analysis_embed(
channel: discord.abc.Messageable,
text: str,
color: int,
title: str,
image_url: Optional[str] = None,
user_mention: Optional[str] = None
) -> None:
try:
embed = discord.Embed(
title=title,
description="AI-powered technical analysis with actionable insights",
color=color
)
if image_url:
embed.set_image(url=image_url)
parsed_sections = []
lines = text.split('\n')
current_header = None
current_content = []
for line in lines:
line = line.strip()
if line.startswith('##') or line.startswith('#'):
if current_header and current_content:
parsed_sections.append((current_header, '\n'.join(current_content)))
current_header = line.strip('#').strip()
current_content = []
elif line.startswith('**') and line.endswith('**') and len(line.strip('*').strip()) < 80:
if current_header and current_content:
parsed_sections.append((current_header, '\n'.join(current_content)))
current_header = line.strip('*').strip()
current_content = []
elif line:
current_content.append(line)
if current_header and current_content:
parsed_sections.append((current_header, '\n'.join(current_content)))
if not parsed_sections:
sections = text.split('\n\n')
for i, section in enumerate(sections[:6]):
if section.strip():
lines = section.strip().split('\n')
first_line = lines[0].strip()
if len(first_line) < 80 and any(word in first_line.lower() for word in ['sentiment', 'analysis', 'trend', 'support', 'resistance', 'recommendation', 'outlook', 'summary', 'technical', 'price', 'volume']):
header = first_line
content = '\n'.join(lines[1:]) if len(lines) > 1 else section.strip()
else:
header = "Market Analysis"
content = section.strip()
parsed_sections.append((header, content))
for header, content in parsed_sections[:8]:
if content.strip():
if len(content) > 1000:
content = content[:997] + "..."
embed.add_field(
name=f"📈 {header[:250]}",
value=content or "No specific insights",
inline=False
)
if not parsed_sections or not embed.fields:
content = text[:1000] + "..." if len(text) > 1000 else text
embed.add_field(name="📈 Technical Analysis", value=content, inline=False)
embed.set_author(name="SecurePath Agent", icon_url=bot.user.avatar.url if bot.user.avatar else None)
embed.set_footer(text="SecurePath Agent • Powered by Perplexity Sonar-Pro")
content = user_mention if user_mention else None
await channel.send(content=content, embed=embed)
except Exception as e:
logger.error(f"Failed to send structured analysis embed: {e}")
await send_long_embed(channel, text, color, title, image_url)
async def send_long_embed(
channel: discord.abc.Messageable,
text: str,
color: int = 0x1D82B6,
title: Optional[str] = None,
image_url: Optional[str] = None,
user_mention: Optional[str] = None
) -> None:
if not text:
return
embed_max_length = 4096
parts = [text[i:i + embed_max_length] for i in range(0, len(text), embed_max_length)]
for i, part in enumerate(parts):
if i == 0:
embed = Embed(title=title, description=part, color=color)
if image_url:
embed.set_image(url=image_url)
else:
embed = Embed(description=part, color=color)
embed.set_author(name="SecurePath Agent", icon_url=bot.user.avatar.url if bot.user.avatar else None)
if len(parts) > 1:
embed.set_footer(text=f"SecurePath Agent • Part {i + 1}/{len(parts)} • Powered by Perplexity Sonar-Pro")
else:
embed.set_footer(text="SecurePath Agent • Powered by Perplexity Sonar-Pro")
try:
content = user_mention if i == 0 and user_mention else None
await channel.send(content=content, embed=embed)
channel_name = getattr(channel, 'name', "Direct Message")
logger.debug(f"Sent embed part {i + 1}/{len(parts)} to {channel_name}")
except discord.errors.HTTPException as e:
logger.error(f"Failed to send embed part {i + 1}/{len(parts)}: {str(e)}")
break
async def log_interaction(user: discord.User, channel: discord.abc.Messageable, command: Optional[str], user_input: str, bot_response: str) -> None:
log_channel = bot.get_channel(config.LOG_CHANNEL_ID)
if not log_channel:
logger.warning(f"Log channel with ID {config.LOG_CHANNEL_ID} not found.")
return
truncated_user_input = (user_input[:1024] + '...') if len(user_input) > 1024 else user_input
truncated_bot_response = (bot_response[:1024] + '...') if len(bot_response) > 1024 else bot_response
embed = Embed(
title="📝 User Interaction",
color=0x1D82B6,
timestamp=datetime.now(timezone.utc)
)
embed.set_author(name=f"{user}", icon_url=user.avatar.url if user.avatar else None)
embed.add_field(name="Command", value=command if command else "N/A", inline=True)
embed.add_field(name="User ID", value=str(user.id), inline=True)
embed.add_field(name="Channel", value=channel.mention if isinstance(channel, discord.TextChannel) else "Direct Message", inline=True)
embed.add_field(name="User Input", value=truncated_user_input, inline=False)
embed.add_field(name="Bot Response Preview", value=truncated_bot_response, inline=False)
embed.set_footer(text=f"Time: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}")
try:
await log_channel.send(embed=embed)
logger.debug(f"Logged interaction for user {user.id}")
except discord.errors.HTTPException as e:
logger.error(f"Failed to send interaction log embed: {str(e)}")
async def process_message_with_streaming(message: discord.Message, status_msg: discord.Message, *, question: Optional[str] = None, command: str = 'ask') -> None:
try:
user_id = message.author.id
is_dm = isinstance(message.channel, discord.DMChannel)
logger.debug(f"Processing message from user {user_id} in {'DM' if is_dm else f'channel {message.channel.id}'}")
logger.debug(f"Processing !ask for user {user_id}")
progress_embed = status_msg.embeds[0]
progress_embed.set_field_at(0, name="Status", value="🔍 Searching Perplexity Sonar-Pro...", inline=False)
await status_msg.edit(embed=progress_embed)
if is_dm:
await preload_user_messages(user_id, message.channel)
try:
perplexity_response = await fetch_perplexity_response(user_id, question or message.content)
logger.info(f"Perplexity response generated for user {user_id}")
update_user_context(user_id, question or message.content, 'user')
progress_embed.set_field_at(0, name="Status", value="✨ Finalizing response...", inline=False)
await status_msg.edit(embed=progress_embed)
update_user_context(user_id, perplexity_response, 'assistant')
try:
await status_msg.delete()
except discord.NotFound:
pass
await send_long_embed(
message.channel,
perplexity_response,
user_mention=message.author.mention,
title="🔍 Research Results"
)
await log_interaction(user=message.author, channel=message.channel, command=command, user_input=question or message.content, bot_response=perplexity_response[:1024])
logger.info(f"Successfully sent Perplexity response to user {user_id}")
except Exception as perplexity_error:
raise perplexity_error
except Exception as e:
logger.error(f"Error processing message: {e}")
logger.error(traceback.format_exc())
raise e
async def process_message(message: discord.Message, question: Optional[str] = None, command: Optional[str] = None) -> None:
can_call, error_msg = can_make_api_call(message.author.id)
if not can_call:
await message.channel.send(f"{message.author.mention} {error_msg}")
return
if question is None:
question = message.content.strip()
if not isinstance(message.channel, discord.DMChannel):
question = question[len(config.BOT_PREFIX):].strip()
if not question:
error_message = "Invalid question input."
logger.error(error_message)
await message.channel.send(error_message)
return
logger.info(f"Processing message from {message.author} (ID: {message.author.id}): {question}")
guild_id = message.guild.id if message.guild else None
channel_id = message.channel.id
username = f"{message.author.name}#{message.author.discriminator}" if message.author.discriminator != "0" else message.author.name
if db_manager.pool:
await db_manager.log_user_query(
user_id=message.author.id,
username=username,
command=command or "dm_chat",
query_text=question,
channel_id=channel_id,
guild_id=guild_id,
response_generated=False,
error_occurred=False
)
if len(question) < 5:
await message.channel.send("Please provide a more detailed question (at least 5 characters).")
return
if len(question) > 1000:
await message.channel.send("Your question is too long. Please limit it to 1000 characters.")
return
async with message.channel.typing():
try:
if isinstance(message.channel, discord.DMChannel):
await preload_user_messages(message.author.id, message.channel)
update_user_context(message.author.id, question, role='user')
guild_id = message.guild.id if message.guild else None
channel_id = message.channel.id
if config.USE_PERPLEXITY_API:
answer = await fetch_perplexity_response(message.author.id, question)
if answer and db_manager.pool:
await log_usage_to_db(
user=message.author,
command=command or "dm_chat",
model="perplexity-sonar-pro",
cost=0.001,
guild_id=guild_id,
channel_id=channel_id
)
else:
answer = await fetch_openai_response(
message.author.id,
question,
user=message.author,
command=command or "dm_chat",
guild_id=guild_id,
channel_id=channel_id
)
if answer:
update_user_context(message.author.id, answer, role='assistant')
await send_long_embed(message.channel, answer, color=0x004200)
await log_interaction(
user=message.author,
channel=message.channel,
command=command,
user_input=question,
bot_response=answer[:1024]
)
else:
error_message = "I'm sorry, I couldn't get a response. Please try again later."
embed = Embed(description=error_message, color=0xff0000)
await message.channel.send(embed=embed)
except Exception as e:
logger.error(f"Error processing message from user {message.author.id}: {str(e)}")
logger.error(traceback.format_exc())
error_message = "An unexpected error occurred. Please try again later."
embed = Embed(description=error_message, color=0xff0000)
await message.channel.send(embed=embed)
status_messages = [
"the BTC chart 📊",
"DeFi trends 📈",
"questions ❓",
"SecurePath 🛡️",
"your commands... 👀"
]
@tasks.loop(seconds=15)
async def change_status():
current_status = random.choice(status_messages)
await bot.change_presence(activity=Activity(type=ActivityType.watching, name=current_status))
logger.debug(f"Changed status to: {current_status}")
async def reset_status():
if change_status.is_running():
change_status.cancel()
await asyncio.sleep(0.1)
change_status.start()
logger.debug("Status rotation restarted.")
@bot.event
async def on_ready() -> None:
logger.info(f'{bot.user} has connected to Discord!')
logger.info(f'SecurePath Agent is active in {len(bot.guilds)} guild(s)')
log_instance_info()
db_connected = await db_manager.connect()
if db_connected:
logger.info("Database connection established successfully")
else:
logger.error("Failed to connect to database - usage tracking will be limited")
await send_startup_notification()
if not change_status.is_running():
change_status.start()
logger.info("Started rotating status messages.")
if not reset_api_call_counter.is_running():
reset_api_call_counter.start()
logger.info("Started API call counter reset task.")
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author.bot:
return
await bot.process_commands(message)
if isinstance(message.channel, discord.DMChannel) and not message.content.startswith(config.BOT_PREFIX):
await preload_user_messages(message.author.id, message.channel)
await process_message(message)
async def preload_user_messages(user_id: int, channel: discord.DMChannel) -> None:
if user_id not in user_contexts:
messages = []
bot_user_id = bot.user.id
async for msg in channel.history(limit=100, oldest_first=True):
role = 'user' if msg.author.id == user_id else 'assistant' if msg.author.id == bot_user_id else None
if role:
messages.append({
'role': role,
'content': msg.content.strip(),
'timestamp': msg.created_at.timestamp(),
})
if len(messages) >= 20:
break
user_contexts[user_id] = deque(reversed(messages), maxlen=config.MAX_CONTEXT_MESSAGES)
logger.info(f"Preloaded {len(user_contexts[user_id])} messages for user {user_id} in DMs.")
async def send_startup_notification() -> None:
startup_time = time.time()
await asyncio.sleep(2)
channel = bot.get_channel(config.LOG_CHANNEL_ID)
if not channel:
logger.warning("Admin channel not found for startup notification")
return
try:
import subprocess
git_hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'],
stderr=subprocess.DEVNULL).decode().strip()
version_info = f"`{git_hash}`"
except:
version_info = "unknown"
init_time = time.time() - startup_time
embed = discord.Embed(
title="🚀 Bot Started!",
description="SecurePath Agent deployed and online",
color=0x00ff00,
timestamp=datetime.now(timezone.utc)
)
embed.add_field(name="Version", value=version_info, inline=True)
embed.add_field(name="Startup Time", value=f"{init_time:.2f}s", inline=True)
embed.add_field(name="Guilds", value=str(len(bot.guilds)), inline=True)
db_status = "🟢 Connected" if db_manager.pool else "🔴 Offline"
embed.add_field(name="Database", value=db_status, inline=True)
embed.add_field(name="Latency", value=f"{bot.latency*1000:.0f}ms", inline=True)
dyno_name = os.environ.get('DYNO', 'local')
embed.add_field(name="Dyno", value=f"`{dyno_name}`", inline=True)
embed.set_footer(text="Ready for commands • Mario's crypto agent")
try:
await channel.send(embed=embed)
logger.info(f"Startup notification sent - Version: {version_info}, Init: {init_time:.2f}s")
except discord.HTTPException as e:
logger.error(f"Failed to send startup notification: {e}")
@bot.command(name='analyze')
async def analyze(ctx: Context, *, user_prompt: str = "") -> None:
await bot.change_presence(activity=Activity(type=ActivityType.watching, name="image analysis..."))
# locate an image
img_url = None
if ctx.message.attachments:
att = ctx.message.attachments[0]
if att.content_type and att.content_type.startswith("image/"):
img_url = att.url
elif isinstance(ctx.channel, discord.DMChannel):
await ctx.send("Please attach an image to analyze.")
return
else:
async for msg in ctx.channel.history(limit=5):
if msg.attachments:
att = msg.attachments[0]
if att.content_type and att.content_type.startswith("image/"):
img_url = att.url
break
if not img_url:
await ctx.send("No image found. Please attach a chart or repost it.")
await reset_status()
return
# status embed
status = discord.Embed(
title="📈 Chart Analysis",
description=f"Prompt: {user_prompt or 'Standard technical analysis'}",
color=0x1D82B6
)
status.add_field(name="Status", value="Processing image...", inline=False)
status_msg = await ctx.send(embed=status)
base_prompt = (
"analyze this chart with technical precision. extract actionable intelligence:\n"
"**sentiment:** [bullish/bearish/neutral + confidence %]\n"
"**key levels:** [support/resistance with exact prices]\n"
"**pattern:** [what you see + timeframe]\n"
"**volume:** [unusual activity + implications]\n"
"**risk/reward:** [entry/exit/stop levels]\n"
"**timeframe:** [best trade horizon]\n"
"**catalysts:** [what could move price]\n"
"bullet points only. experienced trader tone."
)
full_prompt = f"{base_prompt} {user_prompt}" if user_prompt else base_prompt
async def run_analysis(model_name: str):
return await aclient.responses.create(
model=model_name,
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": full_prompt},
{"type": "input_image", "image_url": img_url}
]
}],
max_output_tokens=1000
)
try:
# try GPT-5 vision first
try:
resp = await run_analysis("gpt-5-vision-preview")
except Exception as e:
logger.warning(f"gpt-5-vision-preview failed: {e}, falling back to gpt-4o.")
resp = await run_analysis("gpt-4o")
analysis = getattr(resp, "output_text", None)
if not analysis and hasattr(resp, "output"):
parts = []
for o in resp.output or []:
for b in getattr(o, "content", None) or []:
if getattr(b, "type", "") == "output_text":
parts.append(b.text or "")
analysis = "".join(parts)
if not analysis:
raise RuntimeError("Vision model returned empty output.")
await status_msg.delete()
await send_structured_analysis_embed(
ctx.channel,
text=analysis.strip(),
color=0x1D82B6,
title="📈 Chart Analysis",
image_url=img_url,
user_mention=ctx.author.mention
)
except Exception as e:
await ctx.send(f"❌ Analysis failed: {e}")
logger.exception("Error in analyze command")
finally:
await reset_status()
@bot.command(name='ask')
async def ask(ctx: Context, *, question: Optional[str] = None) -> None:
await bot.change_presence(activity=Activity(type=ActivityType.playing, name="researching..."))
logger.debug("Status updated to: [playing] researching...")
if not question:
help_embed = discord.Embed(
title="🤔 Ask Command Help",
description="Get real-time crypto market insights with AI-powered research.",
color=0x1D82B6
)
help_embed.add_field(
name="Usage",
value="`!ask [your question]`",
inline=False
)
help_embed.add_field(
name="Examples",
value="• `!ask What's the latest news on Bitcoin?`\n"
"• `!ask Ethereum price prediction trends`\n"
"• `!ask What's happening with DeFi protocols?`",
inline=False
)
help_embed.set_footer(text="SecurePath Agent • Powered by Perplexity Sonar-Pro")
await ctx.send(embed=help_embed)
await reset_status()
return
if len(question) < 5:
await ctx.send("⚠️ Please provide a more detailed question (at least 5 characters).")
await reset_status()
return
if len(question) > 500:
await ctx.send("⚠️ Question is too long. Please keep it under 500 characters.")
await reset_status()
return
if db_manager.pool:
username = f"{ctx.author.name}#{ctx.author.discriminator}" if ctx.author.discriminator != "0" else ctx.author.name
await db_manager.log_user_query(
user_id=ctx.author.id,
username=username,
command="ask",
query_text=question,
channel_id=ctx.channel.id,
guild_id=ctx.guild.id if ctx.guild else None,
response_generated=False
)
message_counter[ctx.author.id] += 1
command_counter['ask'] += 1
try:
progress_embed = discord.Embed(
title="🔍 SecurePath Agent Research",
description=f"**Query:** {question[:100]}{'...' if len(question) > 100 else ''}",
color=0x1D82B6
)
progress_embed.add_field(name="Status", value="🔄 Initializing research...", inline=False)
progress_embed.set_footer(text="SecurePath Agent • Real-time Intelligence")
status_msg = await ctx.send(embed=progress_embed)
await process_message_with_streaming(ctx.message, status_msg, question=question, command='ask')
logger.info(f"Successfully completed ask command for user {ctx.author.id}")
except Exception as e: