-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUltronPreAlpha.py
4082 lines (3550 loc) · 182 KB
/
UltronPreAlpha.py
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
import tkinter as tk
from tkinter import ttk
import threading
import asyncio
import telnetlib3
import time
import queue
import re
import sys
import requests
import openai
import json
import os
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError
from pytube import YouTube
from pydub import AudioSegment
import subprocess
from openai import OpenAI
import smtplib
from email.mime.text import MIMEText
import shlex
from bs4 import BeautifulSoup
import imaplib
import email
from email.utils import parseaddr
# Load API keys from api_keys.json
def load_api_keys():
if os.path.exists("api_keys.json"):
with open("api_keys.json", "r") as file:
return json.load(file)
return {}
api_keys = load_api_keys()
###############################################################################
# Default/placeholder API keys (updated in Settings window as needed).
###############################################################################
DEFAULT_OPENAI_API_KEY = api_keys.get("openai_api_key", "")
DEFAULT_WEATHER_API_KEY = api_keys.get("weather_api_key", "")
DEFAULT_YOUTUBE_API_KEY = api_keys.get("youtube_api_key", "")
DEFAULT_GOOGLE_CSE_KEY = api_keys.get("google_cse_api_key", "") # Google Custom Search API Key
DEFAULT_GOOGLE_CSE_CX = api_keys.get("google_cse_cx", "") # Google Custom Search Engine ID (cx)
DEFAULT_GOOGLE_CSE_PIC_CX = api_keys.get("google_cse_pic_cx", "85aed09b11ea947b1") # Picture Search Engine ID
DEFAULT_NEWS_API_KEY = api_keys.get("news_api_key", "") # NewsAPI Key
DEFAULT_GOOGLE_PLACES_API_KEY = api_keys.get("google_places_api_key", "") # Google Places API Key
DEFAULT_PEXELS_API_KEY = api_keys.get("pexels_api_key", "") # Pexels API Key
DEFAULT_ALPHA_VANTAGE_API_KEY = api_keys.get("alpha_vantage_api_key", "") # Alpha Vantage API Key
DEFAULT_COINMARKETCAP_API_KEY = api_keys.get("coinmarketcap_api_key", "") # CoinMarketCap API Key
DEFAULT_GIPHY_API_KEY = api_keys.get("giphy_api_key", "") # Add default Giphy API Key
# Initialize DynamoDB client
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table_name = 'ChatBotConversations'
table = dynamodb.Table(table_name)
class BBSBotApp:
def __init__(self, master):
self.master = master
self.master.title("BBS Chatbot Jeremy")
# Load nospam states first
saved_states = self.load_no_spam_state()
self.no_spam_mode = tk.BooleanVar(value=saved_states['nospam'])
self.no_spam_perm = saved_states['nospam_perm'] # Initialize from saved state
# ----------------- Configurable variables ------------------
self.host = tk.StringVar(value="bbs.example.com")
self.port = tk.IntVar(value=23)
self.openai_api_key = tk.StringVar(value=DEFAULT_OPENAI_API_KEY)
self.weather_api_key = tk.StringVar(value=DEFAULT_WEATHER_API_KEY)
self.youtube_api_key = tk.StringVar(value=DEFAULT_YOUTUBE_API_KEY)
self.google_cse_api_key = tk.StringVar(value=DEFAULT_GOOGLE_CSE_KEY)
self.google_cse_cx = tk.StringVar(value=DEFAULT_GOOGLE_CSE_CX) # For search
self.google_cse_pic_cx = tk.StringVar(value=DEFAULT_GOOGLE_CSE_PIC_CX) # For pictures
self.news_api_key = tk.StringVar(value=DEFAULT_NEWS_API_KEY)
self.google_places_api_key = tk.StringVar(value=DEFAULT_GOOGLE_PLACES_API_KEY)
self.pexels_api_key = tk.StringVar(value=DEFAULT_PEXELS_API_KEY) # Ensure Pexels API Key is loaded
self.nickname = tk.StringVar(value=self.load_nickname())
self.username = tk.StringVar(value=self.load_username())
self.password = tk.StringVar(value=self.load_password())
self.remember_username = tk.BooleanVar(value=False)
self.remember_password = tk.BooleanVar(value=False)
self.in_teleconference = False # Flag to track teleconference state
self.mud_mode = tk.BooleanVar(value=False)
self.alpha_vantage_api_key = tk.StringVar(value=DEFAULT_ALPHA_VANTAGE_API_KEY) # Ensure Alpha Vantage API Key is loaded
self.coinmarketcap_api_key = tk.StringVar(value=DEFAULT_COINMARKETCAP_API_KEY) # Ensure CoinMarketCap API Key is loaded
self.logon_automation_enabled = tk.BooleanVar(value=False) # Correct initialization
self.auto_login_enabled = tk.BooleanVar(value=False) # Add Auto Login toggle
self.giphy_api_key = tk.StringVar(value=DEFAULT_GIPHY_API_KEY) # Add Giphy API Key
self.split_view_enabled = False # Add Split View toggle
self.split_view_clones = [] # Track split view clones
self.public_message_history = {} # Dictionary to store public messages
self.multi_line_buffer = {} # Maps username -> accumulated message string
self.multiline_timeout = {} # Maps username -> timeout ID (from after())
# For best ANSI alignment, recommend a CP437-friendly monospace font:
self.font_name = tk.StringVar(value="Courier New")
self.font_size = tk.IntVar(value=10)
# Terminal mode (ANSI only)
self.terminal_mode = tk.StringVar(value="ANSI")
# Telnet references
self.reader = None
self.writer = None
self.stop_event = threading.Event() # signals background thread to stop
self.connected = False
# A queue to pass data from telnet thread => main thread
self.msg_queue = queue.Queue()
# A buffer to accumulate partial lines
self.partial_line = ""
self.partial_message = "" # Buffer to accumulate partial messages
self.favorites = self.load_favorites() # Load favorite BBS addresses
self.favorites_window = None # Track the Favorites window instance
self.chat_members = set() # Set to keep track of chat members
self.last_seen = self.load_last_seen() # Load last seen timestamps from file
self.last_spoke = self.load_last_spoke() # Load last spoke timestamps from file
# Build UI
self.build_ui()
# Periodically check for incoming messages
self.master.after(100, self.process_incoming_messages)
self.keep_alive_stop_event = threading.Event()
self.keep_alive_task = None
self.loop = asyncio.new_event_loop() # Initialize loop attribute
asyncio.set_event_loop(self.loop) # Set the event loop
self.dynamodb_client = boto3.client('dynamodb', region_name='us-east-1')
self.table_name = table_name
self.create_dynamodb_table()
self.previous_line = "" # Store the previous line to detect multi-line triggers
self.user_list_buffer = [] # Buffer to accumulate user list lines
self.timers = {} # Dictionary to store active timers
self.auto_greeting_enabled = self.load_greeting_state()
self.pending_messages_table_name = 'PendingMessages'
self.create_pending_messages_table()
self.openai_client = OpenAI(api_key=self.openai_api_key.get())
self.in_teleconference = False # Add this flag
self.join_timer = None # Add timer reference
# Start checking for incoming emails
self.master.after(10000, self.check_incoming_mail) # Start checking after 10 seconds
def create_dynamodb_table(self):
"""Create DynamoDB table if it doesn't exist."""
try:
self.dynamodb_client.describe_table(TableName=self.table_name)
except self.dynamodb_client.exceptions.ResourceNotFoundException:
self.dynamodb_client.create_table(
TableName=self.table_name,
KeySchema=[
{'AttributeName': 'username', 'KeyType': 'HASH'},
{'AttributeName': 'timestamp', 'KeyType': 'RANGE'}
],
AttributeDefinitions=[
{'AttributeName': 'username', 'AttributeType': 'S'},
{'AttributeName': 'timestamp', 'AttributeType': 'N'}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
self.dynamodb_client.get_waiter('table_exists').wait(TableName=self.table_name)
def create_pending_messages_table(self):
"""Create DynamoDB table for pending messages if it doesn't exist."""
try:
self.dynamodb_client.describe_table(TableName=self.pending_messages_table_name)
except self.dynamodb_client.exceptions.ResourceNotFoundException:
self.dynamodb_client.create_table(
TableName=self.pending_messages_table_name,
KeySchema=[
{'AttributeName': 'recipient', 'KeyType': 'HASH'},
{'AttributeName': 'timestamp', 'KeyType': 'RANGE'}
],
AttributeDefinitions=[
{'AttributeName': 'recipient', 'AttributeType': 'S'},
{'AttributeName': 'timestamp', 'AttributeType': 'N'}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
self.dynamodb_client.get_waiter('table_exists').wait(TableName=self.pending_messages_table_name)
def save_conversation(self, username, message, response):
"""Save conversation to DynamoDB."""
timestamp = int(time.time())
# Ensure the response is split into chunks of 250 characters
response_chunks = self.chunk_message(response, 250)
for chunk in response_chunks:
table.put_item(
Item={
'username': username,
'timestamp': timestamp,
'message': message,
'response': chunk
}
)
# Update the timestamp for each chunk to maintain order
timestamp += 1
def get_conversation_history(self, username):
"""Retrieve conversation history from DynamoDB."""
response = table.query(
KeyConditionExpression=boto3.dynamodb.conditions.Key('username').eq(username)
)
items = response.get('Items', [])
# Combine response chunks into full responses
conversation_history = []
current_response = ""
for item in items:
current_response += item['response']
if len(current_response) >= 250:
conversation_history.append({
'message': item['message'],
'response': current_response
})
current_response = ""
if current_response:
conversation_history.append({
'message': items[-1]['message'],
'response': current_response
})
return conversation_history
def save_pending_message(self, recipient, sender, message):
"""Save a pending message to DynamoDB."""
timestamp = int(time.time())
pending_messages_table = dynamodb.Table(self.pending_messages_table_name)
pending_messages_table.put_item(
Item={
'recipient': recipient.lower(),
'timestamp': timestamp,
'sender': sender,
'message': message
}
)
def get_pending_messages(self, recipient):
"""Retrieve pending messages for a recipient from DynamoDB."""
pending_messages_table = dynamodb.Table(self.pending_messages_table_name)
response = pending_messages_table.query(
KeyConditionExpression=boto3.dynamodb.conditions.Key('recipient').eq(recipient.lower())
)
return response.get('Items', [])
def delete_pending_message(self, recipient, timestamp):
"""Delete a pending message from DynamoDB."""
pending_messages_table = dynamodb.Table(self.pending_messages_table_name)
pending_messages_table.delete_item(
Key={
'recipient': recipient.lower(),
'timestamp': timestamp
}
)
def build_ui(self):
"""Set up frames, text areas, input boxes, etc."""
main_frame = ttk.Frame(self.master, name='main_frame')
main_frame.pack(fill=tk.BOTH, expand=True)
# ----- Config frame -----
config_frame = ttk.LabelFrame(main_frame, text="Connection Settings")
config_frame.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(config_frame, text="BBS Host:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.E)
self.host_entry = ttk.Entry(config_frame, textvariable=self.host, width=30)
self.host_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W)
self.create_context_menu(self.host_entry)
ttk.Label(config_frame, text="Port:").grid(row=0, column=2, padx=5, pady=5, sticky=tk.E)
self.port_entry = ttk.Entry(config_frame, textvariable=self.port, width=6)
self.port_entry.grid(row=0, column=3, padx=5, pady=5, sticky=tk.W)
self.create_context_menu(self.port_entry)
self.connect_button = ttk.Button(config_frame, text="Connect", command=self.toggle_connection)
self.connect_button.grid(row=0, column=4, padx=5, pady=5)
# Add a "Settings" button
settings_button = ttk.Button(config_frame, text="Settings", command=self.show_settings_window)
settings_button.grid(row=0, column=5, padx=5, pady=5)
# Add a "Favorites" button
favorites_button = ttk.Button(config_frame, text="Favorites", command=self.show_favorites_window)
favorites_button.grid(row=0, column=6, padx=5, pady=5)
# Add a "Mud Mode" checkbox
mud_mode_check = ttk.Checkbutton(config_frame, text="Mud Mode", variable=self.mud_mode)
mud_mode_check.grid(row=0, column=7, padx=5, pady=5)
# Add a "Split View" button
split_view_button = ttk.Button(config_frame, text="Split View", command=self.toggle_split_view)
split_view_button.grid(row=0, column=8, padx=5, pady=5)
# Add a "Teleconference" button
teleconference_button = ttk.Button(config_frame, text="Teleconference", command=self.send_teleconference_command)
teleconference_button.grid(row=0, column=9, padx=5, pady=5)
# ----- Username frame -----
username_frame = ttk.LabelFrame(main_frame, text="Username")
username_frame.pack(fill=tk.X, padx=5, pady=5)
self.username_entry = ttk.Entry(username_frame, textvariable=self.username, width=30)
self.username_entry.pack(side=tk.LEFT, padx=5, pady=5)
self.create_context_menu(self.username_entry)
self.remember_username_check = ttk.Checkbutton(username_frame, text="Remember", variable=self.remember_username)
self.remember_username_check.pack(side=tk.LEFT, padx=5, pady=5)
self.send_username_button = ttk.Button(username_frame, text="Send", command=self.send_username)
self.send_username_button.pack(side=tk.LEFT, padx=5, pady=5)
# ----- Password frame -----
password_frame = ttk.LabelFrame(main_frame, text="Password")
password_frame.pack(fill=tk.X, padx=5, pady=5)
self.password_entry = ttk.Entry(password_frame, textvariable=self.password, width=30, show="*")
self.password_entry.pack(side=tk.LEFT, padx=5, pady=5)
self.create_context_menu(self.password_entry)
self.remember_password_check = ttk.Checkbutton(password_frame, text="Remember", variable=self.remember_password)
self.remember_password_check.pack(side=tk.LEFT, padx=5, pady=5)
self.send_password_button = ttk.Button(password_frame, text="Send", command=self.send_password)
self.send_password_button.pack(side=tk.LEFT, padx=5, pady=5)
# ----- Terminal output -----
terminal_frame = ttk.LabelFrame(main_frame, text="BBS Output")
terminal_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.terminal_display = tk.Text(
terminal_frame,
wrap=tk.WORD,
height=15,
state=tk.NORMAL,
bg="black"
)
self.terminal_display.configure(state=tk.DISABLED)
self.terminal_display.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scroll_bar = ttk.Scrollbar(terminal_frame, command=self.terminal_display.yview)
scroll_bar.pack(side=tk.RIGHT, fill=tk.Y)
self.terminal_display.configure(yscrollcommand=scroll_bar.set)
self.define_ansi_tags()
# ----- Input frame -----
input_frame = ttk.LabelFrame(main_frame, text="Send Message")
input_frame.pack(fill=tk.X, padx=5, pady=5)
self.input_var = tk.StringVar()
self.input_box = ttk.Entry(input_frame, textvariable=self.input_var, width=80)
self.input_box.pack(side=tk.LEFT, padx=5, pady=5, fill=tk.X, expand=True)
self.input_box.bind("<Return>", self.send_message)
self.create_context_menu(self.input_box)
self.send_button = ttk.Button(input_frame, text="Send", command=self.send_message)
self.send_button.pack(side=tk.LEFT, padx=5, pady=5)
# Set initial font
self.update_display_font()
def create_context_menu(self, widget):
"""Create a right-click context menu for the given widget."""
menu = tk.Menu(widget, tearoff=0)
menu.add_command(label="Cut", command=lambda: widget.event_generate("<<Cut>>"))
menu.add_command(label="Copy", command=lambda: widget.event_generate("<<Copy>>"))
menu.add_command(label="Paste", command=lambda: widget.event_generate("<<Paste>>"))
menu.add_command(label="Select All", command=lambda: widget.event_generate("<<SelectAll>>"))
def show_context_menu(event):
menu.tk_popup(event.x_root, event.y_root)
widget.bind("<Button-3>", show_context_menu)
def show_settings_window(self):
"""Open a Toplevel with fields for API keys, font settings, etc."""
settings_win = tk.Toplevel(self.master)
settings_win.title("Settings")
row_index = 0
# ----- OpenAI API Key -----
ttk.Label(settings_win, text="OpenAI API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
openai_api_key_entry = ttk.Entry(settings_win, textvariable=self.openai_api_key, width=40)
openai_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(openai_api_key_entry)
row_index += 1
# ----- Weather API Key -----
ttk.Label(settings_win, text="Weather API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
weather_api_key_entry = ttk.Entry(settings_win, textvariable=self.weather_api_key, width=40)
weather_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(weather_api_key_entry)
row_index += 1
# ----- YouTube API Key -----
ttk.Label(settings_win, text="YouTube API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
youtube_api_key_entry = ttk.Entry(settings_win, textvariable=self.youtube_api_key, width=40)
youtube_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(youtube_api_key_entry)
row_index += 1
# ----- Google CSE Key -----
ttk.Label(settings_win, text="Google CSE API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
google_cse_api_key_entry = ttk.Entry(settings_win, textvariable=self.google_cse_api_key, width=40)
google_cse_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(google_cse_api_key_entry)
row_index += 1
# ----- Google CSE ID (search) -----
ttk.Label(settings_win, text="Google CSE ID (search):").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
google_cse_cx_entry = ttk.Entry(settings_win, textvariable=self.google_cse_cx, width=40)
google_cse_cx_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(google_cse_cx_entry)
row_index += 1
# ----- Google CSE ID (pictures) -----
ttk.Label(settings_win, text="Google CSE ID (pictures):").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
google_cse_pic_cx_entry = ttk.Entry(settings_win, textvariable=self.google_cse_pic_cx, width=40)
google_cse_pic_cx_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(google_cse_pic_cx_entry)
row_index += 1
# ----- News API Key -----
ttk.Label(settings_win, text="News API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
news_api_key_entry = ttk.Entry(settings_win, textvariable=self.news_api_key, width=40)
news_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(news_api_key_entry)
row_index += 1
# ----- Google Places API Key -----
ttk.Label(settings_win, text="Google Places API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
google_places_api_key_entry = ttk.Entry(settings_win, textvariable=self.google_places_api_key, width=40)
google_places_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(google_places_api_key_entry)
row_index += 1
# ----- Pexels API Key -----
ttk.Label(settings_win, text="Pexels API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
pexels_api_key_entry = ttk.Entry(settings_win, textvariable=self.pexels_api_key, width=40)
pexels_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(pexels_api_key_entry)
row_index += 1
# ----- Alpha Vantage API Key -----
ttk.Label(settings_win, text="Alpha Vantage API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
alpha_vantage_api_key_entry = ttk.Entry(settings_win, textvariable=self.alpha_vantage_api_key, width=40)
alpha_vantage_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(alpha_vantage_api_key_entry)
row_index += 1
# ----- CoinMarketCap API Key -----
ttk.Label(settings_win, text="CoinMarketCap API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
coinmarketcap_api_key_entry = ttk.Entry(settings_win, textvariable=self.coinmarketcap_api_key, width=40)
coinmarketcap_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(coinmarketcap_api_key_entry)
row_index += 1
# ----- Giphy API Key -----
ttk.Label(settings_win, text="Giphy API Key:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
giphy_api_key_entry = ttk.Entry(settings_win, textvariable=self.giphy_api_key, width=40)
giphy_api_key_entry.grid(row=row_index, column=1, padx=5, pady=5)
self.create_context_menu(giphy_api_key_entry)
row_index += 1
# ----- Font Name -----
ttk.Label(settings_win, text="Font Name:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
font_options = ["Courier New", "Px437 IBM VGA8", "Terminus (TTF)", "Consolas", "Lucida Console"]
font_dropdown = ttk.Combobox(settings_win, textvariable=self.font_name, values=font_options, state="readonly")
font_dropdown.grid(row=row_index, column=1, padx=5, pady=5, sticky=tk.W)
row_index += 1
# ----- Font Size -----
ttk.Label(settings_win, text="Font Size:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
ttk.Entry(settings_win, textvariable=self.font_size, width=5).grid(row=row_index, column=1, padx=5, pady=5, sticky=tk.W)
row_index += 1
# Info label about recommended fonts
info_label = ttk.Label(
settings_win,
text=(
"Tip: For best ANSI alignment, install a CP437-compatible\n"
"monospace font like 'Px437 IBM VGA8' or 'Terminus (TTF)'.\n"
"Then select its name from the Font Name dropdown."
)
)
info_label.grid(row=row_index, column=0, columnspan=2, padx=5, pady=5, sticky=tk.W)
row_index += 1
# Add Mud Mode checkbox
ttk.Label(settings_win, text="Mud Mode:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
ttk.Checkbutton(settings_win, variable=self.mud_mode).grid(row=row_index, column=1, padx=5, pady=5, sticky=tk.W)
row_index += 1
# Add Logon Automation checkbox
ttk.Label(settings_win, text="Logon Automation:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
ttk.Checkbutton(settings_win, variable=self.logon_automation_enabled).grid(row=row_index, column=1, padx=5, pady=5, sticky=tk.W)
row_index += 1
# Add Auto Login checkbox
ttk.Label(settings_win, text="Auto Login:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
ttk.Checkbutton(settings_win, variable=self.auto_login_enabled).grid(row=row_index, column=1, padx=5, pady=5, sticky=tk.W)
row_index += 1
# Add No Spam Mode checkbox
ttk.Label(settings_win, text="No Spam Mode:").grid(row=row_index, column=0, padx=5, pady=5, sticky=tk.E)
ttk.Checkbutton(settings_win, variable=self.no_spam_mode).grid(row=row_index, column=1, padx=5, pady=5, sticky=tk.W)
row_index += 1
# ----- Save Button -----
save_button = ttk.Button(settings_win, text="Save", command=lambda: self.save_settings(settings_win))
save_button.grid(row=row_index, column=0, columnspan=2, pady=10)
def save_settings(self, window):
"""Called when user clicks 'Save' in the settings window."""
self.update_display_font()
self.openai_client = OpenAI(api_key=self.openai_api_key.get())
# Save new API keys
self.save_api_keys()
window.destroy()
def save_api_keys(self):
"""Save API keys to a file."""
api_keys = {
"openai_api_key": self.openai_api_key.get(),
"weather_api_key": self.weather_api_key.get(),
"youtube_api_key": self.youtube_api_key.get(),
"google_cse_api_key": self.google_cse_api_key.get(),
"google_cse_cx": self.google_cse_cx.get(),
"google_cse_pic_cx": self.google_cse_pic_cx.get(),
"news_api_key": self.news_api_key.get(),
"google_places_api_key": self.google_places_api_key.get(),
"pexels_api_key": self.pexels_api_key.get(),
"alpha_vantage_api_key": self.alpha_vantage_api_key.get(),
"coinmarketcap_api_key": self.coinmarketcap_api_key.get(),
"giphy_api_key": self.giphy_api_key.get() # Save Giphy API Key
}
with open("api_keys.json", "w") as file:
json.dump(api_keys, file)
def load_api_keys(self):
"""Load API keys from a file."""
if os.path.exists("api_keys.json"):
with open("api_keys.json", "r") as file:
api_keys = json.load(file)
self.openai_api_key.set(api_keys.get("openai_api_key", ""))
self.weather_api_key.set(api_keys.get("weather_api_key", ""))
self.youtube_api_key.set(api_keys.get("youtube_api_key", ""))
self.google_cse_api_key.set(api_keys.get("google_cse_api_key", ""))
self.google_cse_cx.set(api_keys.get("google_cse_cx", ""))
self.google_cse_pic_cx.set(api_keys.get("google_cse_pic_cx", ""))
self.news_api_key.set(api_keys.get("news_api_key", ""))
self.google_places_api_key.set(api_keys.get("google_places_api_key", ""))
self.pexels_api_key.set(api_keys.get("pexels_api_key", "")) # Ensure Pexels API Key is loaded
self.alpha_vantage_api_key.set(api_keys.get("alpha_vantage_api_key", "")) # Ensure Alpha Vantage API Key is loaded
self.coinmarketcap_api_key.set(api_keys.get("coinmarketcap_api_key", "")) # Ensure CoinMarketCap API Key is loaded
self.giphy_api_key.set(api_keys.get("giphy_api_key", "")) # Ensure Giphy API Key is loaded
def update_display_font(self):
"""Update the Text widget's font based on self.font_name and self.font_size."""
new_font = (self.font_name.get(), self.font_size.get())
self.terminal_display.configure(font=new_font)
def define_ansi_tags(self):
"""Define text tags for basic ANSI foreground colors (30-37, 90-97)."""
self.terminal_display.tag_configure("normal", foreground="white")
color_map = {
'30': 'black',
'31': 'red',
'32': 'green',
'33': 'yellow',
'34': 'blue',
'35': 'magenta',
'36': 'cyan',
'37': 'white',
'90': 'bright_black',
'91': 'bright_red',
'92': 'bright_green',
'93': 'bright_yellow',
'94': 'bright_blue',
'95': 'bright_magenta',
'96': 'bright_cyan',
'97': 'bright_white'
}
for code, color_name in color_map.items():
if color_name.startswith("bright_"):
base_color = color_name.split("_", 1)[1]
self.terminal_display.tag_configure(color_name, foreground=base_color)
else:
self.terminal_display.tag_configure(color_name, foreground=color_name)
def toggle_connection(self):
"""Connect or disconnect from the BBS."""
if self.connected:
asyncio.run_coroutine_threadsafe(self.disconnect_from_bbs(), self.loop).result()
else:
self.start_connection()
def connect_to_bbs(self, address):
"""Connect to the BBS with the given address."""
self.host.set(address)
self.start_connection()
def start_connection(self):
"""Start the telnetlib3 client in a background thread."""
host = self.host.get()
port = self.port.get()
self.stop_event.clear()
def run_telnet():
asyncio.set_event_loop(self.loop)
self.loop.run_until_complete(self.telnet_client_task(host, port))
thread = threading.Thread(target=run_telnet, daemon=True)
thread.start()
self.append_terminal_text(f"Connecting to {host}:{port}...\n", "normal")
self.start_keep_alive() # Start keep-alive coroutine
async def telnet_client_task(self, host, port):
"""Async function connecting via telnetlib3 (CP437 + ANSI), reading bigger chunks."""
try:
reader, writer = await telnetlib3.open_connection(
host=host,
port=port,
term=self.terminal_mode.get().lower(),
encoding='cp437',
cols=136 # Set terminal width to 136 columns
)
except Exception as e:
self.msg_queue.put_nowait(f"Connection failed: {e}\n")
return
self.reader = reader
self.writer = writer
self.connected = True
self.connect_button.config(text="Disconnect")
self.msg_queue.put_nowait(f"Connected to {host}:{port}\n")
try:
while not self.stop_event.is_set():
data = await reader.read(4096)
if not data:
break
self.msg_queue.put_nowait(data)
except asyncio.CancelledError:
pass
except Exception as e:
self.msg_queue.put_nowait(f"Error reading from server: {e}\n")
finally:
await self.disconnect_from_bbs()
def auto_login_sequence(self):
"""Automate the login sequence."""
if self.connected and self.writer:
self.send_username()
self.master.after(1000, self.send_password)
self.master.after(2000, self.press_enter_repeatedly, 5)
def press_enter_repeatedly(self, count):
"""Press ENTER every 1 second for a specified number of times."""
if self.connected and self.writer:
if count > 0:
self.send_enter_keystroke()
self.master.after(1000, self.press_enter_repeatedly, count - 1)
else:
self.master.after(1000, self.send_teleconference_command)
def send_teleconference_command(self):
"""Send '/go Wordldlink', wait 0.5 seconds, and then send 'ENTER'."""
if self.connected and self.writer:
asyncio.run_coroutine_threadsafe(self._send_message('/go tele'), self.loop)
self.master.after(500, lambda: asyncio.run_coroutine_threadsafe(self._send_message('\r\n'), self.loop))
async def disconnect_from_bbs(self):
"""Stop the background thread and close connections."""
if not self.connected:
return
self.stop_join_timer() # Stop join timer on disconnect
self.in_teleconference = False # Reset teleconference state
self.stop_event.set()
self.stop_keep_alive() # Stop keep-alive coroutine
if self.writer:
try:
self.writer.close()
await self.writer.drain() # Ensure the writer is closed properly
except Exception as e:
print(f"Error closing writer: {e}")
else:
print("Writer is already None")
self.connected = False
self.reader = None
self.writer = None
def update_connect_button():
try:
if self.connect_button and self.connect_button.winfo_exists():
self.connect_button.config(text="Connect")
except tk.TclError:
pass
# Schedule the update_connect_button call from the main thread
if threading.current_thread() is threading.main_thread():
update_connect_button()
else:
try:
self.master.after_idle(update_connect_button)
except RuntimeError as e:
print(f"Error scheduling update_connect_button: {e}")
self.msg_queue.put_nowait("Disconnected from BBS.\n")
def process_incoming_messages(self):
"""Check the queue for data, parse lines, schedule next check."""
try:
while True:
data = self.msg_queue.get_nowait()
print(f"Incoming message: {data}") # Log incoming messages
self.process_data_chunk(data)
except queue.Empty:
pass
finally:
self.master.after(100, self.process_incoming_messages)
def process_data_chunk(self, data):
"""Process incoming data and handle triggers."""
data = data.replace('\r\n', '\n').replace('\r', '\n')
self.partial_line += data
lines = self.partial_line.split("\n")
self.partial_line = lines[-1] # Keep the last partial line
for line in lines[:-1]:
self.append_terminal_text(line + "\n", "normal")
# Remove ANSI codes for easier parsing
ansi_escape_regex = re.compile(r'\x1b\[(.*?)m')
clean_line = ansi_escape_regex.sub('', line)
# ENHANCED USER JOIN DETECTION - Add more detailed debugging
join_patterns = [
r'(.+?) just joined this channel!',
r'(.+?)@(.+?) just joined this channel!',
r'-> (.+?) enters\.',
r'-> (.+?)@(.+?) enters\.'
]
for pattern in join_patterns:
join_match = re.search(pattern, clean_line)
if join_match:
username = join_match.group(1)
print(f"[DEBUG] JOIN DETECTED: '{clean_line}' matched pattern '{pattern}'")
print(f"[DEBUG] Extracted username: {username}")
self.handle_user_greeting(username)
break
# Explicitly check for nospamperm command via whisper
whisper_nospamperm_match = re.match(r'From (.+?) \(whispered\): !nospamperm', clean_line) or \
re.match(r':\[(.+?)\] \(whispered\): !nospamperm', clean_line)
if whisper_nospamperm_match:
username = whisper_nospamperm_match.group(1)
print(f"Detected !nospamperm command from {username}")
self.no_spam_perm = not self.no_spam_perm
state = "permanently enabled" if self.no_spam_perm else "disabled"
self.send_private_message(username, f"No Spam Mode has been {state}.")
self.save_no_spam_state()
continue
# Update last seen and last spoke timestamps for any user activity
public_message_match = re.match(r'From (.+?): (.+)', clean_line)
whisper_match = re.match(r'From (.+?) \(whispered\): (.+)', clean_line)
direct_match = re.match(r'From (.+?) \(to you\): (.+)', clean_line)
page_match = re.match(r'(.+?) is paging you from (.+?): (.+)', clean_line)
current_time = int(time.time())
# Update timestamps for any type of message
if public_message_match:
username = public_message_match.group(1)
base_username = username.split('@')[0]
self.last_seen[base_username.lower()] = current_time
self.last_spoke[base_username.lower()] = current_time
elif whisper_match:
username = whisper_match.group(1)
base_username = username.split('@')[0]
self.last_seen[base_username.lower()] = current_time
self.last_spoke[base_username.lower()] = current_time
elif direct_match:
username = direct_match.group(1)
base_username = username.split('@')[0]
self.last_seen[base_username.lower()] = current_time
self.last_spoke[base_username.lower()] = current_time
elif page_match:
username = page_match.group(1)
base_username = username.split('@')[0]
self.last_seen[base_username.lower()] = current_time
self.last_spoke[base_username.lower()] = current_time
# Save timestamps after any updates
if any([public_message_match, whisper_match, direct_match, page_match]):
self.save_last_seen()
self.save_last_spoke()
# Check for private commands first
private_message_match = re.match(r'From (.+?) \(whispered\): (.+)', clean_line)
if private_message_match:
username = private_message_match.group(1)
message = private_message_match.group(2)
# Handle !nospamperm and !nospam via whisper only
if message.strip() in ["!nospamperm", "!nospam"]:
self.handle_private_trigger(username, message)
continue
# Parse message for normal processing
msg_type, username, content = self.parse_message(clean_line)
if msg_type and username and content:
# Ignore messages from Ultron itself
if username.lower() == 'ultron':
continue
# Handle !nospam command when sent publicly by responding via whisper
if content.strip() == "!nospam":
self.handle_private_trigger(username, content)
continue
# Regular message handling
if msg_type == 'page':
if content.startswith('!'):
response = self.get_command_response(content, username)
else:
response = self.get_chatgpt_response(content, username=username)
if response:
self.send_page_response(username, 'teleconference', response)
elif msg_type == 'whisper':
if content.startswith('!'):
response = self.get_command_response(content, username)
else:
response = self.get_chatgpt_response(content, username=username)
if response:
self.send_private_message(username, response)
elif msg_type == 'direct':
if content.startswith('!'):
response = self.get_command_response(content, username)
else:
response = self.get_chatgpt_response(content, username=username)
if response:
if self.no_spam_mode.get() or self.no_spam_perm:
self.send_private_message(username, response)
else:
self.send_direct_message(username, response)
elif msg_type == 'public' and content.startswith('!'):
response = self.get_command_response(content, username)
if response:
if self.no_spam_mode.get() or self.no_spam_perm:
self.send_private_message(username, response)
else:
self.send_full_message(response)
# Update last spoke timestamp for public messages
public_trigger_match = re.match(r'From (.+?): (.+)', clean_line)
if public_trigger_match:
username = public_trigger_match.group(1)
base_username = username.split('@')[0] # Strip domain part
self.last_spoke[base_username.lower()] = int(time.time())
self.save_last_spoke()
def update_chat_members(self, lines_with_users):
"""
Parse user list from the topic/banner message, handling both single and multi-line formats.
Updates chat members list and last seen timestamps.
"""
# Join all lines and normalize whitespace
combined = " ".join(line.strip() for line in lines_with_users.split('\n'))
print(f"[DEBUG] Combined user lines: {combined}")
# Remove ANSI codes
ansi_escape_regex = re.compile(r'\x1b\[(.*?)m')
combined_clean = ansi_escape_regex.sub('', combined)
print(f"[DEBUG] Cleaned combined user lines: {combined_clean}")
# Extract user section between Topic and "are here with you"
user_list_match = re.search(r'Topic:.*?\)\.\s*(.*?)\s*(?:are|is)\s+here with you', combined_clean, re.DOTALL)
if not user_list_match:
print("[DEBUG] Could not find user list section")
return
user_section = user_list_match.group(1)
print(f"[DEBUG] User section: {user_section}")
# Split users by comma and handle 'and' conjunction
user_parts = user_section.replace(" and ", ", ").split(",")
# Process each user entry
usernames = []
for part in user_parts:
clean_part = part.strip()
if clean_part:
# Extract username from email-style address
username = clean_part.split('@')[0]
if username:
username = username.strip() # Remove any whitespace
usernames.append(username)
# Update last seen timestamp for this user
print(f"[DEBUG] Updating last seen for: {username}")
self.last_seen[username.lower()] = int(time.time())
print(f"[DEBUG] Extracted usernames with timestamps: {usernames}")
# Update chat members set
self.chat_members = set(usernames)
self.save_chat_members()
# Save updated last seen timestamps
self.save_last_seen()
print(f"[DEBUG] Updated last seen timestamps: {self.last_seen}")
# Check for pending messages
for username in usernames:
self.check_and_send_pending_messages(username)
def save_chat_members(self):
"""Save chat members to DynamoDB."""
chat_members_table = dynamodb.Table('ChatRoomMembers')
try:
chat_members_table.put_item(
Item={
'room': 'default',
'members': list(self.chat_members)
}
)
print(f"[DEBUG] Saved chat members to DynamoDB: {self.chat_members}")
except Exception as e:
print(f"Error saving chat members to DynamoDB: {e}")
def get_chat_members(self):
"""Retrieve chat members from DynamoDB."""
chat_members_table = dynamodb.Table('ChatRoomMembers')
try:
response = chat_members_table.get_item(Key={'room': 'default'})
members = response.get('Item', {}).get('members', [])
print(f"[DEBUG] Retrieved chat members from DynamoDB: {members}")
return members
except Exception as e:
print(f"Error retrieving chat members from DynamoDB: {e}")
return []
"""
Check for commands in the given line: !weather, !yt, !search, !chat, !news, !map, !pic, !polly, !mp3yt, !help, !seen, !greeting, !stocks, !crypto, !timer, !gif, !msg, !nospam
And now also capture public messages for conversation history.
"""
# Remove ANSI codes for easier parsing
ansi_escape_regex = re.compile(r'\x1b\[(.*?)m')
clean_line = ansi_escape_regex.sub('', line)
# Handle !nospam toggle first, so you can always toggle it
if "!nospam" in clean_line:
self.no_spam_mode.set(not self.no_spam_mode.get())
state = "enabled" if self.no_spam_mode.get() else "disabled"
self.send_full_message(f"No Spam Mode has been {state}.")
return
# Check if the message is private
private_message_match = re.match(r'From (.+?) \(whispered\): (.+)', clean_line)
page_message_match = re.match(r'(.+?) is paging you (from|via) (.+?): (.+)', clean_line)
direct_message_match = re.match(r'From (.+?) \(to you\): (.+)', clean_line)
# Ignore other public messages if no_spam_mode is enabled
if self.no_spam_mode.get() and not private_message_match and not page_message_match and not direct_message_match:
return
# Check for private messages
if private_message_match:
username = private_message_match.group(1)
message = private_message_match.group(2)
self.partial_message += message + " "
if message.endswith("."):
self.handle_private_trigger(username, self.partial_message.strip())
self.partial_message = ""
return