Skydata001 commited on
Commit
d562dc2
·
verified ·
1 Parent(s): a85248d

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +657 -845
main.py CHANGED
@@ -2,9 +2,12 @@ import os
2
  import asyncio
3
  import threading
4
  import logging
5
- import traceback
 
6
  import time
 
7
  from datetime import datetime
 
8
 
9
  import aiohttp
10
  import discord
@@ -12,1212 +15,1021 @@ import gradio as gr
12
 
13
 
14
  # ============================================================
15
- # CONFIGURATION
16
  # ============================================================
17
 
18
  DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
19
 
20
- if not DISCORD_TOKEN:
21
- raise RuntimeError(
22
- "DISCORD_TOKEN is missing. "
23
- "Please add DISCORD_TOKEN to Hugging Face Space Secrets."
24
- )
25
-
26
-
27
- # ============================================================
28
- # GLOBAL STATE
29
- # ============================================================
30
 
31
- LOG_LIMIT = 2000
32
 
33
- log_lines = []
34
- log_lock = threading.Lock()
35
 
36
- bot_thread = None
37
 
38
- service_started_at = datetime.now()
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- connection_attempts = 0
41
- successful_connections = 0
42
- reconnect_count = 0
43
 
44
- last_status = "STARTING"
45
- last_error = "None"
 
46
 
47
- bot_instance = None
 
48
 
49
 
50
  # ============================================================
51
  # LOG SYSTEM
52
  # ============================================================
53
 
54
- def current_time():
55
- return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
56
-
57
-
58
  def add_log(level, message):
59
- global last_status
60
- global last_error
61
-
62
- line = (
63
- f"[{current_time()}] "
64
- f"[{level.upper():8}] "
65
- f"{message}"
66
- )
67
-
68
- with log_lock:
69
- log_lines.append(line)
70
-
71
- if len(log_lines) > LOG_LIMIT:
72
- del log_lines[:-LOG_LIMIT]
73
-
74
- if level.upper() == "ERROR":
75
- last_error = message
76
 
77
- if level.upper() in [
78
- "SUCCESS",
79
- "ONLINE"
80
- ]:
81
- last_status = "ONLINE"
82
 
83
- elif level.upper() == "WARNING":
84
- if last_status != "ONLINE":
85
- last_status = "WARNING"
86
-
87
- elif level.upper() == "ERROR":
88
- last_status = "ERROR"
89
 
90
  print(line, flush=True)
91
 
92
 
93
  def get_logs():
94
- with log_lock:
95
- return "\n".join(log_lines)
96
-
97
-
98
- # ============================================================
99
- # STARTUP LOGS
100
- # ============================================================
101
-
102
- add_log(
103
- "SYSTEM",
104
- "=================================================="
105
- )
106
-
107
- add_log(
108
- "SYSTEM",
109
- "Discord Bot Service is starting"
110
- )
111
-
112
- add_log(
113
- "SYSTEM",
114
- "Hugging Face Space detected"
115
- )
116
-
117
- add_log(
118
- "SYSTEM",
119
- "Python runtime initialized"
120
- )
121
-
122
- add_log(
123
- "SYSTEM",
124
- "Discord.py initializing"
125
- )
126
-
127
- add_log(
128
- "SYSTEM",
129
- "Gradio interface initializing"
130
- )
131
-
132
- add_log(
133
- "SYSTEM",
134
- "Live logging system initialized"
135
- )
136
-
137
- add_log(
138
- "SYSTEM",
139
- "=================================================="
140
- )
141
-
142
 
143
- # ============================================================
144
- # DISCORD LOGGING
145
- # ============================================================
146
 
147
  class DiscordLogHandler(logging.Handler):
148
 
149
  def emit(self, record):
150
-
151
  try:
152
-
153
  message = self.format(record)
154
 
 
 
155
  if record.levelno >= logging.ERROR:
156
  level = "ERROR"
157
-
158
  elif record.levelno >= logging.WARNING:
159
  level = "WARNING"
160
-
161
- elif record.levelno >= logging.INFO:
162
- level = "INFO"
163
-
164
- else:
165
  level = "DEBUG"
166
 
167
- add_log(
168
- level,
169
- message
170
- )
171
 
172
  except Exception:
173
  pass
174
 
175
 
 
 
 
 
176
  discord_handler = DiscordLogHandler()
177
 
178
  discord_handler.setFormatter(
179
- logging.Formatter(
180
- "%(name)s: %(message)s"
181
- )
182
  )
183
 
184
-
185
  discord_logger = logging.getLogger("discord")
186
-
187
- discord_logger.setLevel(
188
- logging.INFO
189
- )
190
-
191
- discord_logger.addHandler(
192
- discord_handler
193
- )
194
 
195
 
196
  # ============================================================
197
- # DISCORD INTENTS
198
  # ============================================================
199
 
200
- intents = discord.Intents.default()
201
-
202
- intents.guilds = True
 
 
 
 
203
 
204
 
205
  # ============================================================
206
- # DISCORD BOT
207
  # ============================================================
208
 
209
- class OnlineBot(discord.Client):
 
 
210
 
211
- def __init__(self, **kwargs):
 
 
 
212
 
213
- super().__init__(**kwargs)
 
214
 
215
- self.ready_once = False
 
 
 
216
 
217
- # ========================================================
218
- # ON READY
219
- # ========================================================
 
220
 
221
- async def on_ready(self):
222
 
223
- global successful_connections
224
- global last_status
 
225
 
226
- successful_connections += 1
 
227
 
228
- last_status = "ONLINE"
 
229
 
230
- add_log(
231
- "SUCCESS",
232
- "=================================================="
 
233
  )
234
 
235
- add_log(
236
- "SUCCESS",
237
- "Discord connection established"
238
- )
239
 
240
- add_log(
241
- "SUCCESS",
242
- f"Logged in as: {self.user}"
243
- )
244
 
245
- add_log(
246
- "INFO",
247
- f"Bot ID: {self.user.id}"
248
- )
 
 
 
249
 
250
  add_log(
251
- "INFO",
252
- f"Connected servers: {len(self.guilds)}"
253
  )
254
 
255
- if self.user:
256
-
257
  add_log(
258
  "INFO",
259
- f"Bot username: {self.user.name}"
260
  )
261
 
262
- for guild in self.guilds:
263
-
264
- add_log(
265
- "INFO",
266
- f"Server: {guild.name} | ID: {guild.id}"
267
- )
268
 
269
- if not self.ready_once:
270
 
271
- self.ready_once = True
272
 
273
- add_log(
274
- "ONLINE",
275
- "Bot is ONLINE and ready"
276
- )
277
 
278
- else:
279
 
280
- add_log(
281
- "SUCCESS",
282
- "Bot successfully reconnected"
283
- )
284
 
285
- add_log(
286
- "SUCCESS",
287
- "=================================================="
288
- )
289
 
290
- # ========================================================
291
- # NEW SERVER
292
- # ========================================================
293
 
294
- async def on_guild_join(self, guild):
 
 
 
295
 
296
- add_log(
297
- "EVENT",
298
- "=================================================="
299
- )
 
 
300
 
301
- add_log(
302
- "EVENT",
303
- "Bot was added to a new server"
304
- )
305
 
306
- add_log(
307
- "INFO",
308
- f"Server name: {guild.name}"
309
- )
310
 
311
- add_log(
312
- "INFO",
313
- f"Server ID: {guild.id}"
314
  )
315
 
316
- add_log(
317
- "INFO",
318
- f"Server owner ID: {guild.owner_id}"
319
- )
320
 
321
- add_log(
322
- "INFO",
323
- f"Member count: {guild.member_count}"
324
- )
325
 
326
- add_log(
327
- "INFO",
328
- "Searching for the first writable text channel..."
329
- )
330
 
331
- channel = await self.find_first_writable_channel(
332
- guild
333
- )
334
 
335
- if channel is None:
 
 
 
336
 
337
- add_log(
338
- "ERROR",
339
- "No writable text channel was found"
340
- )
341
 
342
- add_log(
343
- "ERROR",
344
- f"Server: {guild.name}"
345
- )
346
 
347
- return
348
 
349
- add_log(
350
- "SUCCESS",
351
- f"First writable channel: #{channel.name}"
352
- )
353
 
354
  add_log(
355
- "INFO",
356
- f"Channel ID: {channel.id}"
357
  )
358
 
359
  add_log(
360
- "INFO",
361
- "Attempting to send online message..."
362
  )
363
 
364
- try:
365
-
366
- await channel.send(
367
- "Hello, I'm online"
368
- )
369
-
370
- add_log(
371
- "SUCCESS",
372
- "Hello, I'm online"
373
- )
374
-
375
- add_log(
376
- "SUCCESS",
377
- f"Message sent to #{channel.name}"
378
- )
379
-
380
- except discord.Forbidden:
381
-
382
- add_log(
383
- "ERROR",
384
- f"Permission denied in #{channel.name}"
385
- )
386
-
387
- except discord.NotFound:
388
-
389
- add_log(
390
- "ERROR",
391
- f"Channel #{channel.name} no longer exists"
392
- )
393
-
394
- except discord.HTTPException as e:
395
-
396
- add_log(
397
- "ERROR",
398
- f"Discord HTTP error: {e}"
399
- )
400
 
401
- except Exception as e:
402
 
403
- add_log(
404
- "ERROR",
405
- f"Unexpected channel message error: {e}"
406
- )
407
 
408
- add_log(
409
- "ERROR",
410
- traceback.format_exc()
411
- )
412
 
413
- add_log(
414
- "EVENT",
415
- "=================================================="
416
- )
417
 
418
- # ========================================================
419
- # FIND FIRST WRITABLE CHANNEL
420
- # ========================================================
 
421
 
422
- async def find_first_writable_channel(
423
- self,
424
- guild
425
- ):
 
 
426
 
427
- try:
428
 
429
- channels = sorted(
430
- guild.text_channels,
431
- key=lambda channel: (
432
- channel.position,
433
- channel.id
434
- )
435
- )
436
 
437
- add_log(
438
- "DEBUG",
439
- f"Found {len(channels)} text channels"
440
- )
441
 
442
- me = guild.me
443
 
444
- if me is None:
445
 
446
- add_log(
447
- "WARNING",
448
- "guild.me is unavailable"
449
  )
450
 
451
- return None
452
 
453
- for index, channel in enumerate(
454
- channels,
455
- start=1
456
- ):
457
 
458
- try:
 
 
 
459
 
460
- permissions = channel.permissions_for(
461
- me
 
462
  )
463
 
464
  add_log(
465
- "DEBUG",
466
- (
467
- f"Channel #{channel.name} "
468
- f"[{index}/{len(channels)}] | "
469
- f"view={permissions.view_channel} | "
470
- f"send={permissions.send_messages}"
471
- )
472
  )
473
 
474
- if (
475
- permissions.view_channel
476
- and permissions.send_messages
477
- ):
478
 
479
- return channel
480
 
481
- except Exception as e:
482
 
483
  add_log(
484
- "WARNING",
485
- (
486
- f"Could not check "
487
- f"#{channel.name}: {e}"
488
- )
489
  )
490
 
491
- except Exception as e:
492
-
493
- add_log(
494
- "ERROR",
495
- f"Channel search failed: {e}"
496
- )
497
-
498
- add_log(
499
- "ERROR",
500
- traceback.format_exc()
501
- )
502
 
503
- return None
504
 
505
- # ========================================================
506
- # GUILD REMOVE
507
- # ========================================================
508
 
509
- async def on_guild_remove(self, guild):
510
 
511
  add_log(
512
- "EVENT",
513
- f"Bot left server: {guild.name}"
514
  )
515
 
516
  add_log(
517
- "INFO",
518
- f"Server ID: {guild.id}"
519
  )
520
 
 
 
521
 
522
  # ============================================================
523
- # CREATE BOT
524
  # ============================================================
525
 
526
- bot_instance = OnlineBot(
527
- intents=intents
528
- )
529
 
 
 
 
 
530
 
531
- # ============================================================
532
- # DISCORD BOT RUNNER
533
- # ============================================================
534
 
535
- def start_discord_bot():
536
 
537
- global bot_thread
538
- global connection_attempts
539
- global reconnect_count
540
 
541
- def runner():
 
 
 
 
 
 
 
 
 
 
 
 
 
542
 
543
- global connection_attempts
544
- global reconnect_count
 
 
 
 
545
 
546
  add_log(
547
- "SYSTEM",
548
- "Starting Discord event loop..."
549
  )
550
 
551
- retry_delay = 10
552
-
553
- while True:
554
 
555
- connection_attempts += 1
 
 
 
556
 
557
- add_log(
558
- "INFO",
559
- (
560
- f"Discord connection attempt "
561
- f"#{connection_attempts}"
562
- )
563
- )
564
-
565
- try:
566
-
567
- add_log(
568
- "INFO",
569
- "Connecting to Discord Gateway..."
570
- )
571
-
572
- bot_instance.run(
573
- DISCORD_TOKEN,
574
- reconnect=True,
575
- log_handler=None
576
- )
577
-
578
- add_log(
579
- "WARNING",
580
- "Discord bot stopped normally"
581
- )
582
 
583
- # ------------------------------------------------
584
- # INVALID TOKEN
585
- # ------------------------------------------------
586
 
587
- except discord.LoginFailure:
588
 
589
- add_log(
590
- "ERROR",
591
- "Discord login failed"
592
- )
593
 
594
- add_log(
595
- "ERROR",
596
- "DISCORD_TOKEN is invalid"
597
- )
598
 
599
- add_log(
600
- "ERROR",
601
- "Fix the token in Hugging Face Secrets"
602
- )
603
 
604
- break
605
 
606
- # ------------------------------------------------
607
- # PRIVILEGED INTENTS
608
- # ------------------------------------------------
609
 
610
- except discord.PrivilegedIntentsRequired:
 
 
611
 
612
- add_log(
613
- "ERROR",
614
- "Discord requires privileged intents"
615
- )
616
 
617
- add_log(
618
- "ERROR",
619
- "Check Discord Developer Portal"
620
- )
621
 
622
- break
623
 
624
- # ------------------------------------------------
625
- # AIOHTTP CONNECTOR ERROR
626
- # ------------------------------------------------
 
627
 
628
- except aiohttp.ClientConnectorError as e:
629
 
630
- reconnect_count += 1
 
 
631
 
632
- add_log(
633
- "ERROR",
634
- (
635
- "Cannot connect to Discord "
636
- f"HTTPS endpoint: {e}"
637
- )
638
- )
639
 
640
- add_log(
641
- "WARNING",
642
- "Discord network connection failed"
643
- )
644
 
645
- add_log(
646
- "INFO",
647
- (
648
- f"Retrying in "
649
- f"{retry_delay} seconds..."
650
- )
651
- )
652
 
653
- # ------------------------------------------------
654
- # CONNECTION RESET
655
- # ------------------------------------------------
 
656
 
657
- except ConnectionResetError as e:
 
 
 
658
 
659
- reconnect_count += 1
 
 
 
660
 
661
- add_log(
662
- "ERROR",
663
- f"Connection reset by remote host: {e}"
664
- )
665
 
666
- add_log(
667
- "WARNING",
668
- "Discord connection was reset"
669
- )
670
 
671
- add_log(
672
- "INFO",
673
- (
674
- f"Retrying in "
675
- f"{retry_delay} seconds..."
676
- )
677
- )
678
 
679
- # ------------------------------------------------
680
- # TIMEOUT
681
- # ------------------------------------------------
682
 
683
- except asyncio.TimeoutError:
 
684
 
685
- reconnect_count += 1
686
 
687
  add_log(
688
  "ERROR",
689
- "Discord connection timed out"
690
  )
691
 
692
- add_log(
693
- "INFO",
694
- (
695
- f"Retrying in "
696
- f"{retry_delay} seconds..."
697
- )
698
- )
699
 
700
- # ------------------------------------------------
701
- # NETWORK ERROR
702
- # ------------------------------------------------
703
 
704
- except ConnectionError as e:
 
 
 
705
 
706
- reconnect_count += 1
707
 
708
- add_log(
709
- "ERROR",
710
- f"Network error: {e}"
711
- )
712
 
713
- add_log(
714
- "INFO",
715
- (
716
- f"Retrying in "
717
- f"{retry_delay} seconds..."
718
- )
719
- )
720
-
721
- # ------------------------------------------------
722
- # GENERAL ERROR
723
- # ------------------------------------------------
724
 
725
- except Exception as e:
726
 
727
- reconnect_count += 1
728
 
729
- add_log(
730
- "ERROR",
731
- f"Discord bot stopped with error: {e}"
732
- )
733
 
734
- add_log(
735
- "ERROR",
736
- traceback.format_exc()
737
- )
738
 
739
- add_log(
740
- "INFO",
741
- (
742
- f"Retrying in "
743
- f"{retry_delay} seconds..."
744
- )
745
- )
746
 
747
- # ------------------------------------------------
748
- # RETRY
749
- # ------------------------------------------------
750
 
751
- time.sleep(
752
- retry_delay
753
- )
 
754
 
755
- if retry_delay < 60:
756
 
757
- retry_delay = min(
758
- retry_delay + 5,
759
- 60
760
- )
761
 
762
- bot_thread = threading.Thread(
763
- target=runner,
764
- daemon=True,
765
- name="DiscordBotThread"
766
- )
767
 
768
- bot_thread.start()
 
 
 
769
 
770
- add_log(
771
- "SYSTEM",
772
- "Discord bot thread started"
773
- )
774
 
 
775
 
776
- # ============================================================
777
- # SERVICE INFORMATION
778
- # ============================================================
779
 
780
- def get_status():
 
 
 
781
 
782
- uptime = datetime.now() - service_started_at
783
 
784
- total_seconds = int(
785
- uptime.total_seconds()
786
- )
 
787
 
788
- days = total_seconds // 86400
789
 
790
- hours = (
791
- total_seconds % 86400
792
- ) // 3600
 
793
 
794
- minutes = (
795
- total_seconds % 3600
796
- ) // 60
797
 
798
- seconds = (
799
- total_seconds % 60
800
- )
801
 
802
- if bot_instance.is_ready():
 
803
 
804
- status = "🟢 ONLINE"
805
 
806
- elif bot_instance.is_closed():
807
 
808
- status = "🔴 DISCONNECTED"
809
 
810
- else:
811
 
812
- status = "🟡 CONNECTING"
813
-
814
- return (
815
- f"Service status: {status}\n"
816
- f"Service uptime: "
817
- f"{days}d {hours}h {minutes}m {seconds}s\n"
818
- f"Connection attempts: {connection_attempts}\n"
819
- f"Successful connections: {successful_connections}\n"
820
- f"Reconnect attempts: {reconnect_count}\n"
821
- f"Discord servers: {len(bot_instance.guilds)}\n"
822
- f"Bot user: {bot_instance.user}\n"
823
- f"Bot ID: "
824
- f"{bot_instance.user.id if bot_instance.user else 'N/A'}\n"
825
- f"Last error: {last_error}"
826
- )
827
 
828
 
829
  # ============================================================
830
- # CUSTOM HTML
831
  # ============================================================
832
 
833
- CUSTOM_HTML = r"""
834
- <div class="dashboard">
835
-
836
- <div class="top">
837
 
838
- <div>
839
-
840
- <div class="title">
841
- Discord Bot Console
842
- </div>
843
-
844
- <div class="subtitle">
845
- Lightweight Discord Service
846
- • Hugging Face
847
- • Gradio
848
- </div>
849
-
850
- </div>
851
 
852
- <div class="live">
853
 
854
- <span class="pulse"></span>
855
-
856
- LIVE
 
857
 
858
- </div>
859
 
860
- </div>
861
 
 
862
 
863
- <div class="cards">
 
 
 
864
 
865
- <div class="card">
866
 
867
- <div class="small">
868
- SERVICE
869
- </div>
870
 
871
- <div class="big">
872
- DISCORD BOT
873
- </div>
874
 
875
- </div>
876
 
 
877
 
878
- <div class="card">
 
 
 
879
 
880
- <div class="small">
881
- RUNTIME
882
- </div>
883
 
884
- <div class="big">
885
- PYTHON
886
- </div>
887
 
888
- </div>
 
 
 
 
 
889
 
 
890
 
891
- <div class="card">
 
 
892
 
893
- <div class="small">
894
- WEB UI
895
- </div>
 
896
 
897
- <div class="big">
898
- GRADIO
899
- </div>
 
900
 
901
- </div>
 
 
 
902
 
 
 
 
903
 
904
- <div class="card">
905
 
906
- <div class="small">
907
- STATUS
908
- </div>
909
 
910
- <div class="big online">
911
- LIVE
912
- </div>
913
 
914
- </div>
 
 
 
915
 
916
- </div>
 
 
 
917
 
918
- </div>
919
 
 
920
 
921
- <style>
 
 
922
 
923
- .dashboard {
 
 
 
924
 
925
- width: 100%;
 
 
 
926
 
927
- box-sizing: border-box;
 
 
 
928
 
929
- font-family:
930
- Inter,
931
- system-ui,
932
- -apple-system,
933
- BlinkMacSystemFont,
934
- "Segoe UI",
935
- sans-serif;
936
 
937
- }
 
 
 
938
 
 
939
 
940
- .top {
 
 
 
941
 
942
- display: flex;
 
 
 
943
 
944
- justify-content: space-between;
945
 
946
- align-items: center;
 
 
947
 
948
- padding: 24px;
 
 
 
949
 
950
- border-radius: 20px;
 
 
 
951
 
952
- border:
953
- 1px solid
954
- rgba(255,255,255,0.08);
 
955
 
956
- background:
957
- rgba(255,255,255,0.035);
 
 
958
 
959
- margin-bottom: 12px;
 
 
960
 
961
- }
 
962
 
 
 
 
 
963
 
964
- .title {
 
 
 
965
 
966
- font-size: 27px;
967
 
968
- font-weight: 800;
969
 
970
- letter-spacing: -0.5px;
 
 
971
 
972
- }
973
 
 
974
 
975
- .subtitle {
 
 
 
976
 
977
- margin-top: 6px;
978
 
979
- font-size: 13px;
 
 
980
 
981
- opacity: 0.55;
982
 
983
- }
 
 
 
984
 
 
 
 
 
985
 
986
- .live {
 
 
 
 
987
 
988
- display: flex;
989
 
990
- align-items: center;
 
 
 
991
 
992
- gap: 8px;
993
 
994
- padding:
995
- 8px
996
- 13px;
997
 
998
- border-radius: 999px;
999
 
1000
- font-size: 11px;
1001
 
1002
- font-weight: 800;
 
1003
 
1004
- letter-spacing: 1px;
 
 
1005
 
1006
- background:
1007
- rgba(0,255,120,0.08);
 
 
1008
 
1009
- color:
1010
- #55ff9b;
1011
 
1012
- }
 
 
 
1013
 
 
 
 
 
1014
 
1015
- .pulse {
 
 
 
1016
 
1017
- width: 8px;
 
 
 
1018
 
1019
- height: 8px;
 
 
 
1020
 
1021
- border-radius: 50%;
 
 
 
1022
 
1023
- background:
1024
- #55ff9b;
 
 
1025
 
1026
- box-shadow:
1027
- 0 0 14px
1028
- rgba(85,255,155,0.8);
 
1029
 
1030
- }
1031
 
 
 
 
 
1032
 
1033
- .cards {
 
 
 
1034
 
1035
- display: grid;
 
1036
 
1037
- grid-template-columns:
1038
- repeat(
1039
- auto-fit,
1040
- minmax(
1041
- 150px,
1042
- 1fr
1043
- )
1044
- );
1045
 
1046
- gap: 10px;
 
 
1047
 
 
 
 
1048
  }
1049
 
1050
-
1051
- .card {
1052
-
1053
- padding: 17px;
1054
-
1055
  border-radius: 16px;
1056
-
1057
- border:
1058
- 1px solid
1059
- rgba(255,255,255,0.07);
1060
-
1061
- background:
1062
- rgba(255,255,255,0.025);
1063
-
1064
  }
1065
 
1066
-
1067
- .small {
1068
-
1069
- font-size: 10px;
1070
-
1071
- font-weight: 700;
1072
-
1073
- opacity: 0.45;
1074
-
1075
- letter-spacing: 1px;
1076
-
1077
  }
1078
 
 
 
 
 
 
 
1079
 
1080
- .big {
1081
-
1082
- margin-top: 7px;
1083
-
1084
- font-size: 15px;
1085
-
1086
- font-weight: 800;
1087
-
1088
  }
1089
 
 
 
 
 
 
1090
 
1091
- .online {
 
 
 
 
 
 
 
1092
 
1093
- color:
1094
- #55ff9b;
 
1095
 
 
 
 
 
 
 
1096
  }
1097
 
1098
- </style>
 
 
 
 
1099
  """
1100
 
1101
 
1102
- # ============================================================
1103
- # GRADIO UI
1104
- # ============================================================
1105
-
1106
  with gr.Blocks(
1107
- title="Discord Bot Console"
 
1108
  ) as app:
1109
 
1110
- gr.HTML(
1111
- CUSTOM_HTML
1112
  )
1113
 
1114
- gr.Markdown(
1115
- "## Live Console"
1116
  )
1117
 
1118
- logs = gr.Textbox(
 
1119
  value=get_logs(),
1120
- label=(
1121
- "Log from when the service started "
1122
- "to the live log"
1123
- ),
1124
  lines=30,
1125
- max_lines=50,
1126
- interactive=False,
1127
- autoscroll=True
1128
- )
1129
-
1130
- gr.Markdown(
1131
- "## Service Information"
1132
- )
1133
-
1134
- status_box = gr.Textbox(
1135
- value=get_status(),
1136
- label="Bot Status",
1137
- lines=8,
1138
  interactive=False
1139
  )
1140
 
1141
- with gr.Row():
1142
-
1143
- refresh_logs_button = gr.Button(
1144
- "Refresh Logs"
1145
- )
1146
-
1147
- refresh_status_button = gr.Button(
1148
- "Refresh Status"
1149
- )
1150
-
1151
-
1152
- # ========================================================
1153
- # REFRESH LOGS
1154
- # ========================================================
1155
-
1156
- refresh_logs_button.click(
1157
- fn=get_logs,
1158
- outputs=logs
1159
- )
1160
-
1161
-
1162
- # ========================================================
1163
- # REFRESH STATUS
1164
- # ========================================================
1165
-
1166
- refresh_status_button.click(
1167
- fn=get_status,
1168
- outputs=status_box
1169
- )
1170
-
1171
-
1172
- # ========================================================
1173
- # LIVE LOG TIMER
1174
- # ========================================================
1175
-
1176
- log_timer = gr.Timer(
1177
  value=1
1178
  )
1179
 
1180
- log_timer.tick(
1181
- fn=get_logs,
1182
- outputs=logs
1183
- )
1184
-
1185
-
1186
- # ========================================================
1187
- # LIVE STATUS TIMER
1188
- # ========================================================
1189
-
1190
- status_timer = gr.Timer(
1191
- value=2
1192
- )
1193
-
1194
- status_timer.tick(
1195
- fn=get_status,
1196
- outputs=status_box
1197
  )
1198
 
1199
 
1200
  # ============================================================
1201
- # START DISCORD BOT
1202
  # ============================================================
1203
 
1204
- start_discord_bot()
1205
-
1206
-
1207
- # ============================================================
1208
- # START GRADIO
1209
- # ============================================================
1210
 
1211
  add_log(
1212
  "SYSTEM",
1213
  "Starting Gradio web interface..."
1214
  )
1215
 
1216
- add_log(
1217
- "SYSTEM",
1218
- "Service is ready"
1219
- )
1220
-
1221
  app.launch(
1222
  server_name="0.0.0.0",
1223
  server_port=7860,
 
2
  import asyncio
3
  import threading
4
  import logging
5
+ import socket
6
+ import ssl
7
  import time
8
+ import traceback
9
  from datetime import datetime
10
+ from zoneinfo import ZoneInfo
11
 
12
  import aiohttp
13
  import discord
 
15
 
16
 
17
  # ============================================================
18
+ # CONFIG
19
  # ============================================================
20
 
21
  DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
22
 
23
+ ALGIERS_TZ = ZoneInfo("Africa/Algiers")
 
 
 
 
 
 
 
 
 
24
 
25
+ MAX_LOG_LINES = 2500
26
 
27
+ logs = []
28
+ logs_lock = threading.Lock()
29
 
30
+ bot_instance = None
31
 
32
+ stats = {
33
+ "attempts": 0,
34
+ "successful_connections": 0,
35
+ "reconnects": 0,
36
+ "last_error": "None",
37
+ "status": "Starting",
38
+ "gateway": "Unknown",
39
+ "https": "Unknown",
40
+ "dns": "Unknown",
41
+ "token": "Unknown",
42
+ "guilds": 0,
43
+ "bot_user": "Unknown",
44
+ }
45
 
 
 
 
46
 
47
+ # ============================================================
48
+ # TIME
49
+ # ============================================================
50
 
51
+ def now():
52
+ return datetime.now(ALGIERS_TZ).strftime("%Y-%m-%d %H:%M:%S")
53
 
54
 
55
  # ============================================================
56
  # LOG SYSTEM
57
  # ============================================================
58
 
 
 
 
 
59
  def add_log(level, message):
60
+ line = f"[{now()}] [{level:<8}] {message}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ with logs_lock:
63
+ logs.append(line)
 
 
 
64
 
65
+ if len(logs) > MAX_LOG_LINES:
66
+ del logs[:-MAX_LOG_LINES]
 
 
 
 
67
 
68
  print(line, flush=True)
69
 
70
 
71
  def get_logs():
72
+ with logs_lock:
73
+ return "\n".join(logs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
 
 
 
75
 
76
  class DiscordLogHandler(logging.Handler):
77
 
78
  def emit(self, record):
 
79
  try:
 
80
  message = self.format(record)
81
 
82
+ level = "INFO"
83
+
84
  if record.levelno >= logging.ERROR:
85
  level = "ERROR"
 
86
  elif record.levelno >= logging.WARNING:
87
  level = "WARNING"
88
+ elif record.levelno >= logging.DEBUG:
 
 
 
 
89
  level = "DEBUG"
90
 
91
+ add_log(level, message)
 
 
 
92
 
93
  except Exception:
94
  pass
95
 
96
 
97
+ # ============================================================
98
+ # DISCORD LOGGING
99
+ # ============================================================
100
+
101
  discord_handler = DiscordLogHandler()
102
 
103
  discord_handler.setFormatter(
104
+ logging.Formatter("%(name)s: %(message)s")
 
 
105
  )
106
 
 
107
  discord_logger = logging.getLogger("discord")
108
+ discord_logger.setLevel(logging.INFO)
109
+ discord_logger.addHandler(discord_handler)
 
 
 
 
 
 
110
 
111
 
112
  # ============================================================
113
+ # BASIC STARTUP
114
  # ============================================================
115
 
116
+ add_log("SYSTEM", "=" * 60)
117
+ add_log("SYSTEM", "Discord Bot Diagnostic Service")
118
+ add_log("SYSTEM", "Starting service...")
119
+ add_log("SYSTEM", "Hugging Face Space environment detected")
120
+ add_log("SYSTEM", f"Python version: {__import__('sys').version.split()[0]}")
121
+ add_log("SYSTEM", f"Platform: {__import__('platform').platform()}")
122
+ add_log("SYSTEM", "=" * 60)
123
 
124
 
125
  # ============================================================
126
+ # TOKEN CHECK
127
  # ============================================================
128
 
129
+ if not DISCORD_TOKEN:
130
+ stats["token"] = "MISSING"
131
+ stats["status"] = "Token Missing"
132
 
133
+ add_log(
134
+ "ERROR",
135
+ "DISCORD_TOKEN was not found in Space Secrets."
136
+ )
137
 
138
+ else:
139
+ stats["token"] = "FOUND"
140
 
141
+ add_log(
142
+ "INFO",
143
+ "DISCORD_TOKEN detected."
144
+ )
145
 
146
+ add_log(
147
+ "INFO",
148
+ f"Token length: {len(DISCORD_TOKEN)} characters"
149
+ )
150
 
 
151
 
152
+ # ============================================================
153
+ # DNS TEST
154
+ # ============================================================
155
 
156
+ def test_dns():
157
+ add_log("TEST", "Testing DNS resolution for discord.com...")
158
 
159
+ try:
160
+ start = time.time()
161
 
162
+ addresses = socket.getaddrinfo(
163
+ "discord.com",
164
+ 443,
165
+ type=socket.SOCK_STREAM
166
  )
167
 
168
+ elapsed = round((time.time() - start) * 1000, 2)
 
 
 
169
 
170
+ unique_ips = []
 
 
 
171
 
172
+ for item in addresses:
173
+ ip = item[4][0]
174
+
175
+ if ip not in unique_ips:
176
+ unique_ips.append(ip)
177
+
178
+ stats["dns"] = "PASS"
179
 
180
  add_log(
181
+ "PASS",
182
+ f"DNS resolved successfully in {elapsed} ms"
183
  )
184
 
185
+ for ip in unique_ips[:10]:
 
186
  add_log(
187
  "INFO",
188
+ f"discord.com -> {ip}"
189
  )
190
 
191
+ return True
 
 
 
 
 
192
 
193
+ except Exception as e:
194
 
195
+ stats["dns"] = "FAIL"
196
 
197
+ add_log(
198
+ "ERROR",
199
+ f"DNS resolution failed: {type(e).__name__}: {e}"
200
+ )
201
 
202
+ return False
203
 
 
 
 
 
204
 
205
+ # ============================================================
206
+ # HTTPS TEST
207
+ # ============================================================
 
208
 
209
+ async def test_https_async():
 
 
210
 
211
+ add_log(
212
+ "TEST",
213
+ "Testing HTTPS connection to https://discord.com ..."
214
+ )
215
 
216
+ timeout = aiohttp.ClientTimeout(
217
+ total=15,
218
+ connect=10,
219
+ sock_connect=10,
220
+ sock_read=10
221
+ )
222
 
223
+ try:
 
 
 
224
 
225
+ start = time.time()
 
 
 
226
 
227
+ connector = aiohttp.TCPConnector(
228
+ ssl=True,
229
+ limit=5
230
  )
231
 
232
+ async with aiohttp.ClientSession(
233
+ connector=connector,
234
+ timeout=timeout
235
+ ) as session:
236
 
237
+ async with session.get(
238
+ "https://discord.com",
239
+ allow_redirects=True
240
+ ) as response:
241
 
242
+ elapsed = round(
243
+ (time.time() - start) * 1000,
244
+ 2
245
+ )
246
 
247
+ stats["https"] = "PASS"
 
 
248
 
249
+ add_log(
250
+ "PASS",
251
+ f"HTTPS connection successful in {elapsed} ms"
252
+ )
253
 
254
+ add_log(
255
+ "INFO",
256
+ f"Discord HTTPS status code: {response.status}"
257
+ )
258
 
259
+ return True
 
 
 
260
 
261
+ except Exception as e:
262
 
263
+ stats["https"] = "FAIL"
 
 
 
264
 
265
  add_log(
266
+ "ERROR",
267
+ f"HTTPS connection failed: {type(e).__name__}: {e}"
268
  )
269
 
270
  add_log(
271
+ "ERROR",
272
+ traceback.format_exc()
273
  )
274
 
275
+ return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
 
 
277
 
278
+ # ============================================================
279
+ # GATEWAY HTTP TEST
280
+ # ============================================================
 
281
 
282
+ async def test_gateway_http_async():
 
 
 
283
 
284
+ url = "https://discord.com/api/v10/gateway"
 
 
 
285
 
286
+ add_log(
287
+ "TEST",
288
+ "Testing Discord Gateway endpoint..."
289
+ )
290
 
291
+ timeout = aiohttp.ClientTimeout(
292
+ total=15,
293
+ connect=10,
294
+ sock_connect=10,
295
+ sock_read=10
296
+ )
297
 
298
+ try:
299
 
300
+ start = time.time()
 
 
 
 
 
 
301
 
302
+ async with aiohttp.ClientSession(
303
+ timeout=timeout
304
+ ) as session:
 
305
 
306
+ async with session.get(url) as response:
307
 
308
+ text = await response.text()
309
 
310
+ elapsed = round(
311
+ (time.time() - start) * 1000,
312
+ 2
313
  )
314
 
315
+ if response.status == 200:
316
 
317
+ stats["gateway"] = "PASS"
 
 
 
318
 
319
+ add_log(
320
+ "PASS",
321
+ f"Gateway HTTP endpoint reachable in {elapsed} ms"
322
+ )
323
 
324
+ add_log(
325
+ "INFO",
326
+ f"Gateway HTTP status: {response.status}"
327
  )
328
 
329
  add_log(
330
+ "INFO",
331
+ f"Gateway response: {text[:500]}"
 
 
 
 
 
332
  )
333
 
334
+ return True
 
 
 
335
 
336
+ else:
337
 
338
+ stats["gateway"] = "FAIL"
339
 
340
  add_log(
341
+ "ERROR",
342
+ f"Gateway returned HTTP {response.status}"
 
 
 
343
  )
344
 
345
+ add_log(
346
+ "ERROR",
347
+ f"Response: {text[:500]}"
348
+ )
 
 
 
 
 
 
 
349
 
350
+ return False
351
 
352
+ except Exception as e:
 
 
353
 
354
+ stats["gateway"] = "FAIL"
355
 
356
  add_log(
357
+ "ERROR",
358
+ f"Gateway test failed: {type(e).__name__}: {e}"
359
  )
360
 
361
  add_log(
362
+ "ERROR",
363
+ traceback.format_exc()
364
  )
365
 
366
+ return False
367
+
368
 
369
  # ============================================================
370
+ # RUN NETWORK DIAGNOSTICS
371
  # ============================================================
372
 
373
+ async def run_diagnostics():
 
 
374
 
375
+ add_log("SYSTEM", "")
376
+ add_log("SYSTEM", "=" * 60)
377
+ add_log("SYSTEM", "NETWORK DIAGNOSTICS")
378
+ add_log("SYSTEM", "=" * 60)
379
 
380
+ dns_ok = await asyncio.to_thread(test_dns)
 
 
381
 
382
+ https_ok = await test_https_async()
383
 
384
+ gateway_ok = await test_gateway_http_async()
 
 
385
 
386
+ add_log("SYSTEM", "")
387
+ add_log("SYSTEM", "=" * 60)
388
+ add_log("SYSTEM", "DIAGNOSTIC RESULT")
389
+ add_log("SYSTEM", "=" * 60)
390
+
391
+ add_log(
392
+ "RESULT",
393
+ f"DNS: {stats['dns']}"
394
+ )
395
+
396
+ add_log(
397
+ "RESULT",
398
+ f"HTTPS: {stats['https']}"
399
+ )
400
 
401
+ add_log(
402
+ "RESULT",
403
+ f"Gateway: {stats['gateway']}"
404
+ )
405
+
406
+ if dns_ok and https_ok and gateway_ok:
407
 
408
  add_log(
409
+ "PASS",
410
+ "Basic Discord network connectivity appears healthy."
411
  )
412
 
413
+ else:
 
 
414
 
415
+ add_log(
416
+ "ERROR",
417
+ "Discord network connectivity test FAILED."
418
+ )
419
 
420
+ add_log(
421
+ "ERROR",
422
+ "The problem may be network restrictions, routing, firewall, or Discord-side blocking."
423
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
 
425
+ add_log("SYSTEM", "=" * 60)
 
 
426
 
 
427
 
428
+ # ============================================================
429
+ # DISCORD BOT
430
+ # ============================================================
 
431
 
432
+ class OnlineBot(discord.Client):
 
 
 
433
 
434
+ def __init__(self):
 
 
 
435
 
436
+ intents = discord.Intents.default()
437
 
438
+ intents.guilds = True
 
 
439
 
440
+ super().__init__(
441
+ intents=intents
442
+ )
443
 
444
+ self.ready_event = asyncio.Event()
 
 
 
445
 
446
+ async def on_connect(self):
 
 
 
447
 
448
+ stats["status"] = "Connected to Gateway"
449
 
450
+ add_log(
451
+ "PASS",
452
+ "Discord Gateway connection established."
453
+ )
454
 
455
+ async def on_ready(self):
456
 
457
+ stats["status"] = "ONLINE"
458
+ stats["successful_connections"] += 1
459
+ stats["guilds"] = len(self.guilds)
460
 
461
+ if self.user:
 
 
 
 
 
 
462
 
463
+ stats["bot_user"] = (
464
+ f"{self.user} ({self.user.id})"
465
+ )
 
466
 
467
+ add_log(
468
+ "SUCCESS",
469
+ "=============================================="
470
+ )
 
 
 
471
 
472
+ add_log(
473
+ "SUCCESS",
474
+ "BOT IS ONLINE"
475
+ )
476
 
477
+ add_log(
478
+ "SUCCESS",
479
+ f"Bot: {self.user}"
480
+ )
481
 
482
+ add_log(
483
+ "SUCCESS",
484
+ f"Bot ID: {self.user.id}"
485
+ )
486
 
487
+ add_log(
488
+ "SUCCESS",
489
+ f"Servers: {len(self.guilds)}"
490
+ )
491
 
492
+ add_log(
493
+ "SUCCESS",
494
+ "=============================================="
495
+ )
496
 
497
+ self.ready_event.set()
 
 
 
 
 
 
498
 
499
+ # Send message to existing servers
500
+ for guild in self.guilds:
 
501
 
502
+ try:
503
+ await self.send_online_message(guild)
504
 
505
+ except Exception as e:
506
 
507
  add_log(
508
  "ERROR",
509
+ f"Failed in guild '{guild.name}': {e}"
510
  )
511
 
512
+ async def on_disconnect(self):
 
 
 
 
 
 
513
 
514
+ stats["status"] = "DISCONNECTED"
 
 
515
 
516
+ add_log(
517
+ "WARNING",
518
+ "Discord Gateway disconnected."
519
+ )
520
 
521
+ async def on_resumed(self):
522
 
523
+ stats["status"] = "ONLINE"
 
 
 
524
 
525
+ add_log(
526
+ "SUCCESS",
527
+ "Discord Gateway session resumed."
528
+ )
 
 
 
 
 
 
 
529
 
530
+ async def on_guild_join(self, guild):
531
 
532
+ stats["guilds"] = len(self.guilds)
533
 
534
+ add_log(
535
+ "SUCCESS",
536
+ f"Bot added to server: {guild.name}"
537
+ )
538
 
539
+ await self.send_online_message(guild)
 
 
 
540
 
541
+ async def on_guild_remove(self, guild):
 
 
 
 
 
 
542
 
543
+ stats["guilds"] = len(self.guilds)
 
 
544
 
545
+ add_log(
546
+ "WARNING",
547
+ f"Bot removed from server: {guild.name}"
548
+ )
549
 
550
+ async def send_online_message(self, guild):
551
 
552
+ channel = self.find_first_writable_channel(guild)
 
 
 
553
 
554
+ if channel is None:
 
 
 
 
555
 
556
+ add_log(
557
+ "WARNING",
558
+ f"No writable text channel found in: {guild.name}"
559
+ )
560
 
561
+ return
 
 
 
562
 
563
+ try:
564
 
565
+ await channel.send(
566
+ "Hello, I'm online"
567
+ )
568
 
569
+ add_log(
570
+ "SUCCESS",
571
+ f"Sent online message to #{channel.name} in {guild.name}"
572
+ )
573
 
574
+ except discord.Forbidden:
575
 
576
+ add_log(
577
+ "WARNING",
578
+ f"Permission denied in #{channel.name} ({guild.name})"
579
+ )
580
 
581
+ except Exception as e:
582
 
583
+ add_log(
584
+ "ERROR",
585
+ f"Message error in {guild.name}: {type(e).__name__}: {e}"
586
+ )
587
 
588
+ def find_first_writable_channel(self, guild):
 
 
589
 
590
+ me = guild.me
 
 
591
 
592
+ if me is None:
593
+ return None
594
 
595
+ for channel in guild.text_channels:
596
 
597
+ permissions = channel.permissions_for(me)
598
 
599
+ if permissions.view_channel and permissions.send_messages:
600
 
601
+ return channel
602
 
603
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604
 
605
 
606
  # ============================================================
607
+ # BOT CONNECTION ENGINE
608
  # ============================================================
609
 
610
+ async def bot_connection_engine():
 
 
 
611
 
612
+ global bot_instance
 
 
 
 
 
 
 
 
 
 
 
 
613
 
614
+ if not DISCORD_TOKEN:
615
 
616
+ add_log(
617
+ "ERROR",
618
+ "Bot cannot start because DISCORD_TOKEN is missing."
619
+ )
620
 
621
+ stats["status"] = "TOKEN ERROR"
622
 
623
+ return
624
 
625
+ await run_diagnostics()
626
 
627
+ add_log(
628
+ "SYSTEM",
629
+ "Starting Discord connection engine..."
630
+ )
631
 
632
+ attempt = 0
633
 
634
+ while True:
 
 
635
 
636
+ attempt += 1
 
 
637
 
638
+ stats["attempts"] = attempt
639
 
640
+ stats["status"] = "CONNECTING"
641
 
642
+ add_log(
643
+ "INFO",
644
+ f"Discord connection attempt #{attempt}"
645
+ )
646
 
647
+ bot = OnlineBot()
 
 
648
 
649
+ bot_instance = bot
 
 
650
 
651
+ connection_task = asyncio.create_task(
652
+ bot.start(
653
+ DISCORD_TOKEN,
654
+ reconnect=True
655
+ )
656
+ )
657
 
658
+ try:
659
 
660
+ # ------------------------------------------------
661
+ # WAIT FOR READY
662
+ # ------------------------------------------------
663
 
664
+ add_log(
665
+ "INFO",
666
+ "Waiting for Discord Gateway / bot_ready..."
667
+ )
668
 
669
+ await asyncio.wait_for(
670
+ bot.ready_event.wait(),
671
+ timeout=45
672
+ )
673
 
674
+ add_log(
675
+ "SUCCESS",
676
+ "Bot passed the 45-second connection watchdog."
677
+ )
678
 
679
+ # ------------------------------------------------
680
+ # BOT IS NOW RUNNING
681
+ # ------------------------------------------------
682
 
683
+ try:
684
 
685
+ await connection_task
 
 
686
 
687
+ except Exception as e:
 
 
688
 
689
+ add_log(
690
+ "ERROR",
691
+ f"Discord runtime stopped: {type(e).__name__}: {e}"
692
+ )
693
 
694
+ add_log(
695
+ "ERROR",
696
+ traceback.format_exc()
697
+ )
698
 
699
+ except asyncio.TimeoutError:
700
 
701
+ stats["status"] = "TIMEOUT"
702
 
703
+ stats["last_error"] = (
704
+ "Discord Gateway did not become ready within 45 seconds"
705
+ )
706
 
707
+ add_log(
708
+ "ERROR",
709
+ "=============================================="
710
+ )
711
 
712
+ add_log(
713
+ "ERROR",
714
+ "DISCORD CONNECTION TIMEOUT"
715
+ )
716
 
717
+ add_log(
718
+ "ERROR",
719
+ "Discord did not reach on_ready within 45 seconds."
720
+ )
721
 
722
+ add_log(
723
+ "ERROR",
724
+ "The connection may be blocked, reset, or unreachable from this Space."
725
+ )
 
 
 
726
 
727
+ add_log(
728
+ "ERROR",
729
+ "Stopping the stuck connection attempt..."
730
+ )
731
 
732
+ connection_task.cancel()
733
 
734
+ try:
735
+ await connection_task
736
+ except BaseException:
737
+ pass
738
 
739
+ try:
740
+ await bot.close()
741
+ except Exception:
742
+ pass
743
 
744
+ except Exception as e:
745
 
746
+ stats["last_error"] = (
747
+ f"{type(e).__name__}: {e}"
748
+ )
749
 
750
+ add_log(
751
+ "ERROR",
752
+ f"Discord connection error: {type(e).__name__}: {e}"
753
+ )
754
 
755
+ add_log(
756
+ "ERROR",
757
+ traceback.format_exc()
758
+ )
759
 
760
+ try:
761
+ connection_task.cancel()
762
+ except Exception:
763
+ pass
764
 
765
+ try:
766
+ await bot.close()
767
+ except Exception:
768
+ pass
769
 
770
+ # ----------------------------------------------------
771
+ # RECONNECT
772
+ # ----------------------------------------------------
773
 
774
+ stats["reconnects"] += 1
775
+ stats["status"] = "RECONNECTING"
776
 
777
+ delay = min(
778
+ 60,
779
+ 5 * stats["reconnects"]
780
+ )
781
 
782
+ add_log(
783
+ "WARNING",
784
+ f"Retrying Discord connection in {delay} seconds..."
785
+ )
786
 
787
+ await asyncio.sleep(delay)
788
 
 
789
 
790
+ # ============================================================
791
+ # BOT THREAD
792
+ # ============================================================
793
 
794
+ def start_discord_thread():
795
 
796
+ def runner():
797
 
798
+ add_log(
799
+ "SYSTEM",
800
+ "Starting dedicated Discord event loop..."
801
+ )
802
 
803
+ try:
804
 
805
+ asyncio.run(
806
+ bot_connection_engine()
807
+ )
808
 
809
+ except Exception as e:
810
 
811
+ add_log(
812
+ "ERROR",
813
+ f"Discord thread crashed: {type(e).__name__}: {e}"
814
+ )
815
 
816
+ add_log(
817
+ "ERROR",
818
+ traceback.format_exc()
819
+ )
820
 
821
+ thread = threading.Thread(
822
+ target=runner,
823
+ name="DiscordBotThread",
824
+ daemon=True
825
+ )
826
 
827
+ thread.start()
828
 
829
+ add_log(
830
+ "SYSTEM",
831
+ "Discord bot thread started."
832
+ )
833
 
 
834
 
835
+ # ============================================================
836
+ # DASHBOARD
837
+ # ============================================================
838
 
839
+ def dashboard():
840
 
841
+ status = stats["status"]
842
 
843
+ return f"""
844
+ <div class="dashboard">
845
 
846
+ <div class="title">
847
+ DISCORD BOT CONTROL CENTER
848
+ </div>
849
 
850
+ <div class="status">
851
+ STATUS:
852
+ <b>{status}</b>
853
+ </div>
854
 
855
+ <div class="grid">
 
856
 
857
+ <div>
858
+ <span>DNS</span>
859
+ <b>{stats["dns"]}</b>
860
+ </div>
861
 
862
+ <div>
863
+ <span>HTTPS</span>
864
+ <b>{stats["https"]}</b>
865
+ </div>
866
 
867
+ <div>
868
+ <span>Gateway</span>
869
+ <b>{stats["gateway"]}</b>
870
+ </div>
871
 
872
+ <div>
873
+ <span>Token</span>
874
+ <b>{stats["token"]}</b>
875
+ </div>
876
 
877
+ <div>
878
+ <span>Attempts</span>
879
+ <b>{stats["attempts"]}</b>
880
+ </div>
881
 
882
+ <div>
883
+ <span>Successful</span>
884
+ <b>{stats["successful_connections"]}</b>
885
+ </div>
886
 
887
+ <div>
888
+ <span>Servers</span>
889
+ <b>{stats["guilds"]}</b>
890
+ </div>
891
 
892
+ <div>
893
+ <span>Reconnects</span>
894
+ <b>{stats["reconnects"]}</b>
895
+ </div>
896
 
897
+ </div>
898
 
899
+ <div class="bot">
900
+ <span>BOT</span>
901
+ <b>{stats["bot_user"]}</b>
902
+ </div>
903
 
904
+ <div class="error">
905
+ <span>LAST ERROR</span>
906
+ <b>{stats["last_error"]}</b>
907
+ </div>
908
 
909
+ </div>
910
+ """
911
 
 
 
 
 
 
 
 
 
912
 
913
+ # ============================================================
914
+ # GRADIO
915
+ # ============================================================
916
 
917
+ css = """
918
+ body {
919
+ background: #080808 !important;
920
  }
921
 
922
+ .dashboard {
923
+ padding: 20px;
 
 
 
924
  border-radius: 16px;
925
+ background: #111;
926
+ color: white;
927
+ font-family: monospace;
928
+ border: 1px solid #333;
 
 
 
 
929
  }
930
 
931
+ .title {
932
+ font-size: 25px;
933
+ font-weight: bold;
934
+ margin-bottom: 15px;
 
 
 
 
 
 
 
935
  }
936
 
937
+ .status {
938
+ padding: 12px;
939
+ background: #181818;
940
+ border-radius: 10px;
941
+ margin-bottom: 15px;
942
+ }
943
 
944
+ .grid {
945
+ display: grid;
946
+ grid-template-columns: repeat(4, 1fr);
947
+ gap: 10px;
 
 
 
 
948
  }
949
 
950
+ .grid div {
951
+ background: #181818;
952
+ padding: 14px;
953
+ border-radius: 10px;
954
+ }
955
 
956
+ .grid span,
957
+ .bot span,
958
+ .error span {
959
+ display: block;
960
+ color: #888;
961
+ font-size: 12px;
962
+ margin-bottom: 5px;
963
+ }
964
 
965
+ .grid b {
966
+ font-size: 17px;
967
+ }
968
 
969
+ .bot,
970
+ .error {
971
+ margin-top: 10px;
972
+ background: #181818;
973
+ padding: 14px;
974
+ border-radius: 10px;
975
  }
976
 
977
+ @media(max-width: 700px) {
978
+ .grid {
979
+ grid-template-columns: repeat(2, 1fr);
980
+ }
981
+ }
982
  """
983
 
984
 
 
 
 
 
985
  with gr.Blocks(
986
+ title="Discord Bot Control Center",
987
+ css=css
988
  ) as app:
989
 
990
+ gr.Markdown(
991
+ "# Discord Bot Control Center"
992
  )
993
 
994
+ status_html = gr.HTML(
995
+ dashboard
996
  )
997
 
998
+ logs_box = gr.Textbox(
999
+ label="LIVE CONSOLE",
1000
  value=get_logs(),
 
 
 
 
1001
  lines=30,
1002
+ max_lines=40,
 
 
 
 
 
 
 
 
 
 
 
 
1003
  interactive=False
1004
  )
1005
 
1006
+ refresh = gr.Timer(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1007
  value=1
1008
  )
1009
 
1010
+ refresh.tick(
1011
+ fn=lambda: (
1012
+ dashboard(),
1013
+ get_logs()
1014
+ ),
1015
+ outputs=[
1016
+ status_html,
1017
+ logs_box
1018
+ ]
 
 
 
 
 
 
 
 
1019
  )
1020
 
1021
 
1022
  # ============================================================
1023
+ # START
1024
  # ============================================================
1025
 
1026
+ start_discord_thread()
 
 
 
 
 
1027
 
1028
  add_log(
1029
  "SYSTEM",
1030
  "Starting Gradio web interface..."
1031
  )
1032
 
 
 
 
 
 
1033
  app.launch(
1034
  server_name="0.0.0.0",
1035
  server_port=7860,