-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBot.py
More file actions
2116 lines (1830 loc) · 75.6 KB
/
Bot.py
File metadata and controls
2116 lines (1830 loc) · 75.6 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
"""
GitTracker Bot - A Telegram Bot For Tracking GitHub Repository Events.
Production-Grade Implementation With Comprehensive Error Handling And Logging.
"""
import threading
import requests
import asyncio
import hmac
import hashlib
import time
import re
import signal
import sys
import textwrap
from flask import Flask, request, jsonify, render_template
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
from typing import Optional
from werkzeug.middleware.proxy_fix import ProxyFix
import DataBase
import Config
from Logging_Config import logger
# ---------------- Initialize Database ----------------
try:
if not DataBase.Init_Db():
logger.error("Failed To Initialize Database")
exit(1)
logger.info("Database Initialized Successfully")
except Exception as e:
logger.critical(f"Critical Error During Database Initialization: {e}")
exit(1)
# ---------------- Config ----------------
try:
telegram_token = Config.config.telegram.token
github_client_id = Config.config.github.client_id
github_client_secret = Config.config.github.client_secret
webhook_url = Config.config.server.webhook_url
logger.info("Configuration Loaded Successfully")
except ValueError as e:
logger.critical(f"Configuration Error: {e}")
exit(1)
# ---------------- Globals ----------------
App = Flask(__name__, template_folder="Templates")
App.wsgi_app = ProxyFix(App.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)
ApplicationInstance = None
BotApp = None
BotLoop = None # Store Telegram Bot Loop
BotThread = None
BotStartupError = None
BotReady = False
BotStartTime = time.time()
# ---------------- Helper Functions ----------------
def build_public_url(path: str) -> str:
"""Build An Absolute Public URL From The Configured Base URL."""
if not webhook_url:
raise ValueError("WEBHOOK_URL Environment Variable Is Required For Webhook Mode")
normalized_path = path if path.startswith("/") else f"/{path}"
return f"{webhook_url}{normalized_path}"
def telegram_bot_is_ready() -> bool:
"""Return Whether The Telegram Application Is Ready To Process Webhooks."""
return (
BotReady
and BotApp is not None
and BotLoop is not None
and not BotLoop.is_closed()
and BotLoop.is_running()
)
def verify_webhook_signature(payload: bytes, signature: str, secret: str) -> bool:
"""
Verify GitHub Webhook Signature For security.
Args:
payload: Raw Request Payload
signature: GitHub Signature Header
secret: Webhook Secret
Returns:
bool: True If Signature Is Valid
"""
if not secret or not signature:
return False
expected_signature = hmac.new(
secret.encode(),
payload,
hashlib.sha256
).hexdigest()
expected_signature = f"sha256={expected_signature}"
return hmac.compare_digest(expected_signature, signature)
def GetCommitTag(message: str) -> str:
"""Return Emoji Based On Commit Message Keywords."""
msg = message.lower()
if "fix" in msg or "bug" in msg:
return "🐛"
if "feat" in msg or "add" in msg or "new" in msg:
return "✨"
if "doc" in msg or "readme" in msg:
return "📝"
if "style" in msg or "ui" in msg:
return "🎨"
if "hotfix" in msg or "urgent" in msg:
return "🔥"
return "🔨"
# ---------------- Input Validation ----------------
def validate_github_repo(repo_input: str) -> Optional[str]:
"""
Validate And Normalize GitHub Repository Input.
Args:
repo_input: Repository In Format "owner/repo" Or Full GitHub URL
Returns:
Normalized "owner/repo" Format Or None If Invalid
"""
if not repo_input or not isinstance(repo_input, str):
return None
repo_input = repo_input.strip()
# Handle Full GitHub URLs
if repo_input.startswith("http"):
if "github.com/" not in repo_input:
return None
try:
repo = repo_input.rstrip("/").split("github.com/")[1]
except IndexError:
return None
else:
repo = repo_input
# Validate owner/repo Format
if "/" not in repo or repo.count("/") > 1:
return None
owner, repo_name = repo.split("/")
if not owner or not repo_name:
return None
# Basic Validation For Allowed Characters
import re
if not re.match(r"^[a-zA-Z0-9._-]+$", owner) or not re.match(r"^[a-zA-Z0-9._-]+$", repo_name):
return None
return f"{owner}/{repo_name}"
def validate_issue_number(issue_str: str) -> Optional[int]:
"""
Validate Issue/PR Number.
Args:
issue_str: String Representation Of Issue Number
Returns:
Integer Issue Number Or None If Invalid
"""
try:
issue_num = int(issue_str)
if issue_num <= 0:
return None
return issue_num
except ValueError:
return None
def validate_comment_text(text: str) -> bool:
"""
Validate Comment Text For Basic Security.
Args:
text: Comment Text To Validate
Returns:
True If Valid, False Otherwise
"""
if not text or not isinstance(text, str):
return False
text = text.strip()
if len(text) == 0 or len(text) > 65536: # GitHub's Comment Limit
return False
# Check For Potentially Malicious Content
dangerous_patterns = [
"<script", "</script>", "javascript:", "data:", "vbscript:"
]
text_lower = text.lower()
for pattern in dangerous_patterns:
if pattern in text_lower:
return False
return True
# ---------------- Telegram Handlers ----------------
async def Start(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
welcome_message = build_message_card(
"Welcome to GitTracker Bot!",
[
"🚀 Your GitHub Repository Monitor In Telegram.",
"",
"📋 Available commands:",
"🔗 <code>/connect</code> — Link Your GitHub Account",
"📌 <code>/setrepo Owner/Repo</code> — Add Repository Tracking",
"📥 <code>/getrepo</code> — Show Connected Repositories",
"💬 <code>/comment Owner/Repo #ID Message</code> — Post a Comment",
"📊 <code>/stats Owner/Repo</code> — Repository Overview",
"📋 <code>/listwebhooks</code> — View Repository Webhooks",
"🗑 <code>/removerepo Owner/Repo</code> — Stop Notifications",
"",
"✨ Features:",
"• Real-time GitHub Activity Alerts",
"• Multi-Chat Repository Support",
"• Issue, PR, Push, Release Tracking",
"• Secure Webhook Integration",
"",
"🌟 Version: Production v2.0"
],
emoji="🎉"
)
await Update.message.reply_text(welcome_message, parse_mode="HTML")
async def Connect(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
"""Handle GitHub OAuth Connection Setup."""
try:
telegram_id = Update.effective_user.id
auth_url = (
f"https://github.com/login/oauth/authorize"
f"?client_id={github_client_id}&scope=repo"
f"&state={telegram_id}"
)
connect_msg = build_message_card(
"Connect Your GitHub Account",
[
"Click The Link Below To Authorize GitTracker Bot.",
f"🔗 <a href='{auth_url}'>Authorize GitHub Access</a>",
"",
"📋 Permissions Requested:",
"• Read Access To Your Repositories",
"• Create Webhooks For Notifications",
"",
"🔒 Your Data Is Handled Securely And Privately."
],
emoji="🔗"
)
await Update.message.reply_text(connect_msg, parse_mode="HTML")
logger.info(f"Generated GitHub Auth URL For User {telegram_id}")
except Exception as e:
error_msg = build_error_card(
"Connection Error",
[
"Unable To Generate The GitHub Authorization Link.",
"Please Try Again Later Or Contact Support If This Continues."
]
)
await Update.message.reply_text(error_msg, parse_mode="HTML")
logger.error(f"Error Generating Connection Link For User {Update.effective_user.id}: {e}")
async def Help(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
"""Show A Friendly Help Menu."""
help_message = build_message_card(
"Bot Help",
[
"Use Any Of The Commands Below To Manage Your GitHub Tracking:",
"",
"🔗 <code>/connect</code> — Link Your GitHub Account",
"📌 <code>/setrepo Owner/Repo</code> — Add Repository Tracking",
"📥 <code>/getrepo</code> — Show Connected Repositories",
"🗑 <code>/removerepo Owner/Repo</code> — Remove A Repository Connection",
"💬 <code>/comment Owner/Repo #ID Message</code> — Post Issue Or PR Comments",
"📊 <code>/stats Owner/Repo</code> — Show Repository Statistics",
"🕒 <code>/recent Owner/Repo</code> — Show Recent Commits",
"🌿 <code>/branches Owner/Repo</code> — Show Repository Branches",
"👥 <code>/contributors Owner/Repo</code> — Show Top Contributors",
"📈 <code>/status</code> — Show Bot And Service Status",
"ℹ️ <code>/about</code> — About GitTracker Bot"
],
emoji="📘"
)
await Update.message.reply_text(help_message, parse_mode="HTML")
async def About(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
"""Show Bot About Information."""
about_message = build_message_card(
"About GitTracker Bot",
[
"GitTracker Bot Sends GitHub Repository Events Directly To Telegram.",
"",
"• Real-Time Push, Pull Request, Issue, And Release Tracking",
"• Secure GitHub Webhook Integration",
"• Clean And Consistent Message Formatting",
"• Multi-Chat And Topic Support",
"",
f"• Domain: <code>{Config.config.server.webhook_url or 'Not Configured'}</code>"
],
emoji="🤖"
)
await Update.message.reply_text(about_message, parse_mode="HTML")
async def Status(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
"""Show Bot Status And Health Metrics."""
try:
uptime_seconds = int(time.time() - BotStartTime)
uptime_hours = uptime_seconds // 3600
uptime_minutes = (uptime_seconds % 3600) // 60
uptime_seconds = uptime_seconds % 60
TelegramId = Update.effective_user.id
Connections = DataBase.Get_User_Repo_Connections(TelegramId)
connection_count = len(Connections) if Connections else 0
status_message = build_message_card(
"Bot Status",
[
f"🟢 Bot Status : Running",
f"⏱ Uptime: {uptime_hours}h {uptime_minutes}m {uptime_seconds}s",
f"📦 Connected Repositories: {connection_count}",
f"🌐 Webhook Domain: <code>{Config.config.server.webhook_url or 'Not Configured'}</code>",
f"🖥 Server Host: <code>{Config.config.server.host}:{Config.config.server.port}</code>"
],
emoji="📈"
)
await Update.message.reply_text(status_message, parse_mode="HTML")
except Exception as e:
logger.error(f"Error Generating Status For User {Update.effective_user.id}: {e}")
await Update.message.reply_text(
build_error_card(
"Status Error",
["Unable To Generate Status Right Now.", "Please Try Again Later."]
),
parse_mode="HTML"
)
async def SetRepo(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
if not Context.args:
await Update.message.reply_text(
build_warning_card(
"Set Repository",
["Usage: <code>/setrepo Owner/Repo</code> Or A Full GitHub URL"]
),
parse_mode="HTML"
)
return
RepoInput = Context.args[0]
# Validate Repository Input
Repo = validate_github_repo(RepoInput)
if not Repo:
await Update.message.reply_text(
build_error_card(
"Invalid Repository",
["Use Owner/Repo Format Or A GitHub URL Like <code>https://github.com/owner/repo</code>"]
),
parse_mode="HTML"
)
return
TelegramId = Update.effective_user.id
ChatId = Update.effective_chat.id
ChatType = Update.effective_chat.type
TopicId = getattr(Update.effective_message, 'message_thread_id', None) if ChatType == 'supergroup' else None
Token = DataBase.Get_Token(TelegramId)
if not Token:
await Update.message.reply_text(
build_warning_card(
"Account Not Connected",
["Please Use <code>/connect</code> Before Adding A Repository."]
),
parse_mode="HTML"
)
return
# Check If Repository Connection Already Exists For This Chat
existing_connections = DataBase.get_user_repo_connections(TelegramId)
for conn in existing_connections:
if conn['Repo_Name'] == Repo and conn['Chat_Id'] == ChatId and conn['Topic_Id'] == TopicId:
await Update.message.reply_text(
build_warning_card(
"Already Connected",
[f"Repository <code>{Repo}</code> Is Already Connected For This Chat."]
),
parse_mode="HTML"
)
return
# Add The Repo Connection
DataBase.Add_Repo_Connection(TelegramId, Repo, ChatId, ChatType, TopicId)
HookUrl = f"{webhook_url}/webhook"
ApiUrl = f"https://api.github.com/repos/{Repo}/hooks"
Headers = {"Authorization": f"token {Token}"}
Data = {
"name": "web",
"active": True,
"events": ["push", "pull_request", "issues", "delete", "create", "release"],
"config": {"url": HookUrl, "content_type": "json", "insecure_ssl": "0"},
}
# Add Webhook Secret If Configured
if Config.config.github.webhook_secret:
Data["config"]["secret"] = Config.config.github.webhook_secret
Response = requests.post(ApiUrl, json=Data, headers=Headers, timeout=10)
if Response.status_code in [200, 201]:
success_msg = build_success_card(
"Repository Connected",
[
f"📦 Repository: <code>{Repo}</code>",
f"🔗 Webhook: Installed And Active",
f"📱 Chat: {ChatType.capitalize()}",
"",
"You Will Now Receive Updates For:",
"• Pushes And Commits",
"• Pull Request Activity",
"• Issues And Comments",
"• Branch/Tag Creations And Deletions",
"• Releases"
]
)
await Update.message.reply_text(success_msg, parse_mode="HTML")
logger.info(f"Repository {Repo} Connected For User {TelegramId} In Chat {ChatId}")
else:
error_msg = build_warning_card(
"Repository Added With Warnings",
[
f"📦 Repository: <code>{Repo}</code>",
"🔗 Webhook Installation Failed",
"",
f"GitHub Response: <code>{Response.text}</code>",
"",
"The Repository Is Saved, But Webhook Delivery May Not Be Active.",
"Please Verify The Webhook Settings On GitHub If Needed."
]
)
await Update.message.reply_text(error_msg, parse_mode="HTML")
logger.warning(f"Failed To Create Webhook For {Repo}: {Response.text}")
except requests.exceptions.RequestException as e:
logger.error(f"Network Error Setting Repo For User {Update.effective_user.id}: {e}")
await Update.message.reply_text(
build_error_card(
"Network Error",
["Unable To Connect To GitHub At This Time.", "Please Try Again In A Few Minutes."]
),
parse_mode="HTML"
)
except Exception as e:
logger.error(f"Unexpected Error Setting Repo For User {Update.effective_user.id}: {e}")
await Update.message.reply_text(
build_error_card(
"Unexpected Error",
["An Unexpected Error Occurred While Setting The Repository.", "Please Try Again Later."]
),
parse_mode="HTML"
)
async def GetRepo(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
TelegramId = Update.effective_user.id
Connections = DataBase.Get_User_Repo_Connections(TelegramId)
if Connections:
lines = [
"Here Are The Repositories Currently Connected To This Account:",
""
]
for i, Conn in enumerate(Connections, 1):
ChatType = Conn['Chat_Type']
TopicInfo = f" (Topic: {Conn['Topic_Id']})" if Conn['Topic_Id'] else ""
chat_emoji = {
'private': '👤',
'group': '👥',
'supergroup': '🏢'
}.get(ChatType, '💬')
lines.append(f"{i}. {chat_emoji} <code>{Conn['Repo_Name']}</code>")
lines.append(f" • {ChatType.capitalize()}{TopicInfo}")
lines.append("")
message = build_message_card("Connected Repositories", lines)
await Update.message.reply_text(message, parse_mode="HTML")
else:
no_connections_msg = build_warning_card(
"No Repository Connections",
[
"You Haven't Connected Any Repositories Yet.",
"",
"To Get Started:",
"• Use <code>/connect</code> To Link Your GitHub Account.",
"• Use <code>/setrepo Owner/Repo</code> To Add A Repository."
]
)
await Update.message.reply_text(no_connections_msg, parse_mode="HTML")
except Exception as e:
await Update.message.reply_text(
build_error_card(
"Error Retrieving Connections",
[
"An Unexpected Error Occurred While Fetching Your Repository Connections.",
"Please Try Again Later."
]
),
parse_mode="HTML"
)
async def RemoveRepo(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
if not Context.args:
await Update.message.reply_text(
build_warning_card(
"Remove Repository",
["Usage: <code>/removerepo Owner/Repo</code>"]
),
parse_mode="HTML"
)
return
Repo = Context.args[0]
TelegramId = Update.effective_user.id
ChatId = Update.effective_chat.id
TopicId = getattr(Update.effective_message, 'message_thread_id', None) if Update.effective_chat.type == 'supergroup' else None
DataBase.Remove_Repo_Connection(TelegramId, Repo, ChatId, TopicId)
success_msg = build_success_card(
"Repository Removed",
[
f"📦 Repository: <code>{Repo}</code>",
f"📱 Chat: {Update.effective_chat.type.capitalize()}",
"",
"The Repository Connection Has Been Removed For This Chat.",
"You Will No Longer Receive Notifications Here."
]
)
await Update.message.reply_text(success_msg, parse_mode="HTML")
except Exception as e:
await Update.message.reply_text(
build_error_card(
"Removal Failed",
["An Error Occurred While Removing The Repository Connection.", "Please Try Again Later."]
),
parse_mode="HTML"
)
async def Comment(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
if len(Context.args) < 3:
await Update.message.reply_text(
build_warning_card(
"Post Comment",
["Usage: <code>/comment Owner/Repo Issue_Number Message</code>"]
),
parse_mode="HTML"
)
return
RepoInput = Context.args[0]
IssueNumberStr = Context.args[1]
CommentText = " ".join(Context.args[2:])
# Validate Inputs
Repo = validate_github_repo(RepoInput)
if not Repo:
await Update.message.reply_text(
build_error_card(
"Invalid Repository",
["Use A Valid Owner/Repo Format."]
),
parse_mode="HTML"
)
return
IssueNumber = validate_issue_number(IssueNumberStr)
if not IssueNumber:
await Update.message.reply_text(
build_error_card(
"Invalid Issue Number",
["Issue Number Must Be A Positive Integer."]
),
parse_mode="HTML"
)
return
if not validate_comment_text(CommentText):
await Update.message.reply_text(
build_warning_card(
"Invalid Comment",
["Please Provide A Valid Comment Message Without Unsafe Content."]
),
parse_mode="HTML"
)
return
TelegramId = Update.effective_user.id
Token = DataBase.Get_Token(TelegramId)
if not Token:
await Update.message.reply_text(
build_warning_card(
"Not Connected",
["Please Use <code>/connect</code> To Link Your GitHub Account First."]
),
parse_mode="HTML"
)
return
Url = f"https://api.github.com/repos/{Repo}/issues/{IssueNumber}/comments"
Headers = {"Authorization": f"token {Token}"}
Response = requests.post(Url, json={"body": CommentText}, headers=Headers, timeout=10)
if Response.status_code == 201:
success_msg = build_success_card(
"Comment Posted",
[
f"📦 Repository: <code>{Repo}</code>",
f"🔢 Issue/PR: #{IssueNumber}",
"",
f"💬 Comment: <code>{CommentText[:100]}{'...' if len(CommentText) > 100 else ''}</code>"
]
)
await Update.message.reply_text(success_msg, parse_mode="HTML")
logger.info(f"Comment Posted By User {TelegramId} on {Repo}#{IssueNumber}")
else:
error_msg = build_error_card(
"Comment Failed",
[
f"📦 Repository: <code>{Repo}</code>",
f"🔢 Issue/PR: #{IssueNumber}",
"",
"Unable To Post Your Comment.",
f"GitHub Response: <code>{Response.text}</code>"
]
)
await Update.message.reply_text(error_msg, parse_mode="HTML")
logger.warning(f"Failed To Post Comment On {Repo}#{IssueNumber}: {Response.text}")
except requests.exceptions.RequestException as e:
logger.error(f"Network Error Posting Comment For User {Update.effective_user.id}: {e}")
await Update.message.reply_text(
build_error_card(
"Network Error",
["Unable To Reach GitHub Right Now.", "Please Try Again Later."]
),
parse_mode="HTML"
)
except Exception as e:
logger.error(f"Unexpected Error Posting Comment For User {Update.effective_user.id}: {e}")
await Update.message.reply_text(
build_error_card(
"Unexpected Error",
["An Unexpected Error Occurred While Posting The Comment.", "Please Try Again Later."]
),
parse_mode="HTML"
)
async def ListWebhooks(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
TelegramId = Update.effective_user.id
Repo = DataBase.Get_Default_Repo(TelegramId)
if not Repo:
Connections = DataBase.Get_User_Repo_Connections(TelegramId)
Repo = Connections[0]['Repo_Name'] if Connections else None
Token = DataBase.Get_Token(TelegramId)
if not Repo or not Token:
await Update.message.reply_text(
build_warning_card(
"List Webhooks",
["Please Connect A Repository First With <code>/setrepo</code> And <code>/connect</code>."]
),
parse_mode="HTML"
)
return
Url = f"https://api.github.com/repos/{Repo}/hooks"
Headers = {"Authorization": f"token {Token}"}
Response = requests.get(Url, headers=Headers, timeout=10)
if Response.status_code != 200:
await Update.message.reply_text(
build_error_card(
"Fetch Failed",
[f"Unable To Fetch Webhooks For <code>{Repo}</code>.", f"GitHub Response: <code>{Response.text}</code>"]
),
parse_mode="HTML"
)
return
Hooks = Response.json()
if not Hooks:
await Update.message.reply_text(
build_message_card(
"No Webhooks Found",
[f"No webhooks are currently installed for <code>{Repo}</code>."]
),
parse_mode="HTML"
)
return
lines = [f"Webhooks for <code>{Repo}</code>:", ""]
for H in Hooks:
lines.append(f"• Id: {H['id']} — <code>{H['config']['url']}</code>")
await Update.message.reply_text(
build_message_card("Repository Webhooks", lines),
parse_mode="HTML"
)
except requests.exceptions.RequestException as e:
await Update.message.reply_text(
build_error_card(
"Network Error",
["Unable To Reach GitHub Right Now.", "Please Try Again Later."]
),
parse_mode="HTML"
)
except KeyError as e:
await Update.message.reply_text(
build_error_card(
"Invalid Data",
["Received Unexpected Webhook Data From GitHub.", "Try Again Later."]
),
parse_mode="HTML"
)
except Exception as e:
await Update.message.reply_text(
build_error_card(
"Error Listing Webhooks",
["An Unexpected Error Occurred While Listing Webhooks.", "Please Try Again Later."]
),
parse_mode="HTML"
)
async def DelWebhook(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
if not Context.args:
await Update.message.reply_text(
build_warning_card(
"Delete Webhook",
["Usage: <code>/delwebhook HookId</code>"]
),
parse_mode="HTML"
)
return
HookId = Context.args[0]
TelegramId = Update.effective_user.id
Repo = DataBase.Get_Default_Repo(TelegramId)
if not Repo:
Connections = DataBase.Get_User_Repo_Connections(TelegramId)
Repo = Connections[0]['Repo_Name'] if Connections else None
Token = DataBase.Get_Token(TelegramId)
if not Repo or not Token:
await Update.message.reply_text(
build_warning_card(
"Webhook Delete",
["Please Use <code>/setrepo</code> And <code>/connect</code> Before Modifying Webhooks."]
),
parse_mode="HTML"
)
return
Url = f"https://api.github.com/repos/{Repo}/hooks/{HookId}"
Headers = {"Authorization": f"token {Token}"}
Response = requests.delete(Url, headers=Headers, timeout=10)
if Response.status_code == 204:
await Update.message.reply_text(
build_success_card(
"Webhook Deleted",
[f"Webhook <code>{HookId}</code> Has Been Removed From <code>{Repo}</code>."]
),
parse_mode="HTML"
)
else:
await Update.message.reply_text(
build_error_card(
"Delete Failed",
[f"Unable To Delete Webhook <code>{HookId}</code>.", f"GitHub Response: <code>{Response.text}</code>"]
),
parse_mode="HTML"
)
except requests.exceptions.RequestException as e:
await Update.message.reply_text(
build_error_card(
"Network Error",
["Unable To Reach GitHub Right Now.", "Please Try Again Later."]
),
parse_mode="HTML"
)
except Exception as e:
await Update.message.reply_text(
build_error_card(
"Unexpected Error",
["An Unexpected Error Occurred While Deleting The Webhook.", "Please Try Again Later."]
),
parse_mode="HTML"
)
async def Stats(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
if not Context.args:
await Update.message.reply_text(
build_warning_card(
"Repository Stats",
["Usage: <code>/stats Owner/Repo</code>"]
),
parse_mode="HTML"
)
return
RepoInput = Context.args[0]
Repo = validate_github_repo(RepoInput)
if not Repo:
await Update.message.reply_text(
build_error_card(
"Invalid Repository",
["Use Owner/Repo or a GitHub URL like <code>https://github.com/owner/repo</code>."]
),
parse_mode="HTML"
)
return
TelegramId = Update.effective_user.id
Token = DataBase.Get_Token(TelegramId)
if not Token:
await Update.message.reply_text(
build_warning_card(
"Not Connected",
["Please Use <code>/connect</code> Before Requesting Repository Stats."]
),
parse_mode="HTML"
)
return
Url = f"https://api.github.com/repos/{Repo}"
Headers = {"Authorization": f"token {Token}"}
Response = requests.get(Url, headers=Headers, timeout=10)
if Response.status_code != 200:
await Update.message.reply_text(
build_error_card(
"Fetch Failed",
[f"Unable To Fetch Stats For <code>{Repo}</code>.", f"GitHub Response: <code>{Response.text}</code>"]
),
parse_mode="HTML"
)
return
Data = Response.json()
# Extract Stats
name = Data.get('name', 'Unknown')
full_name = Data.get('full_name', Repo)
description = Data.get('description', 'No Description')
stars = Data.get('stargazers_count', 0)
forks = Data.get('forks_count', 0)
issues = Data.get('open_issues_count', 0)
language = Data.get('language', 'Unknown')
created = Data.get('created_at', 'Unknown')[:10]
updated = Data.get('updated_at', 'Unknown')[:10]
size = Data.get('size', 0)
stats_message = build_message_card(
"Repository Statistics",
[
f"📦 Name: <code>{name}</code>",
f"🔗 Full Name: <code>{full_name}</code>",
f"📝 Description: {description}",
"",
f"⭐ Stars: {stars:,}",
f"🍴 Forks: {forks:,}",
f"🐛 Open Issues: {issues:,}",
f"💻 Language: {language}",
f"📅 Created: {created}",
f"🔄 Last Updated: {updated}",
f"💾 Size: {size:,} KB"
]
)
await Update.message.reply_text(stats_message, parse_mode="HTML")
except requests.exceptions.RequestException as e:
logger.error(f"Network Error Fetching Stats For User {Update.effective_user.id}: {e}")
await Update.message.reply_text(
build_error_card(
"Network Error",
["Unable To Reach GitHub Right Now.", "Please Try Again Later."]
),
parse_mode="HTML"
)
except Exception as e:
logger.error(f"Unexpected Error Fetching Stats For User {Update.effective_user.id}: {e}")
await Update.message.reply_text(
build_error_card(
"Unexpected Error",
["An Unexpected Error Occurred While Fetching Repository Statistics.", "Please Try Again Later."]
),
parse_mode="HTML"
)
async def Recent(Update: Update, Context: ContextTypes.DEFAULT_TYPE):
try:
if not Context.args:
await Update.message.reply_text(
build_warning_card(
"Recent Commits",
["Usage: <code>/recent Owner/Repo</code>"]
),
parse_mode="HTML"
)
return
RepoInput = Context.args[0]
Repo = validate_github_repo(RepoInput)
if not Repo:
await Update.message.reply_text(
build_error_card(
"Invalid Repository",
["Use Owner/Repo Or A GitHub URL Like <code>https://github.com/owner/repo</code>."]
),
parse_mode="HTML"
)
return
TelegramId = Update.effective_user.id
Token = DataBase.Get_Token(TelegramId)
if not Token:
await Update.message.reply_text(
build_warning_card(
"Not Connected",
["Please Use <code>/connect</code> Before Fetching Recent Commits."]
),
parse_mode="HTML"
)
return
Url = f"https://api.github.com/repos/{Repo}/commits?per_page=10"
Headers = {"Authorization": f"token {Token}"}
Response = requests.get(Url, headers=Headers, timeout=10)
if Response.status_code != 200:
await Update.message.reply_text(
build_error_card(
"Fetch Failed",
[f"Unable To Retrieve Commits For <code>{Repo}</code>.", f"GitHub Response: <code>{Response.text}</code>"]
),
parse_mode="HTML"
)
return
Commits = Response.json()
if not Commits:
await Update.message.reply_text(
build_message_card(
"No Recent Commits",
[f"No Recent Commits Were Found For <code>{Repo}</code>."]
),
parse_mode="HTML"
)
return
lines = [f"Recent Commits For <code>{Repo}</code>:", ""]
for i, commit in enumerate(Commits[:10], 1):
sha = commit.get('sha', '')[:7]
author = commit.get('commit', {}).get('author', {}).get('name', 'Unknown')
message_commit = commit.get('commit', {}).get('message', '').split('\n')[0]
date = commit.get('commit', {}).get('author', {}).get('date', '')[:10]
url = commit.get('html_url', '')
tag = GetCommitTag(message_commit)
commit_line = f"{i}. {tag} <code>{sha}</code> — {message_commit}"
lines.append(commit_line)
lines.append(f" 👤 {author} | 📅 {date}")
if url:
lines.append(f" 🔗 <a href='{url}'>View Commit</a>")
lines.append("")