-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithubber.py
More file actions
713 lines (597 loc) · 40.1 KB
/
githubber.py
File metadata and controls
713 lines (597 loc) · 40.1 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
import base64
import io
import math
import random
import traceback
from typing import Callable
import aiohttp
import nextcord
from nextcord.ext import commands, tasks, application_checks
from github_api import GitHubAPI
from pagination import PaginationView, EmbedCreator
from utils import LinksButton, get_guild_embed, load_json, save_json, format_datetime, send_response, LinkButton, Options, Logger, RateLimiter
bot = commands.Bot(intents=nextcord.Intents.default())
blacklist = load_json(file_path="blacklist.json")
config = load_json(file_path="config.json")
github_api = GitHubAPI(config["github_tokens"])
logger = Logger(config["webhook_url"])
rate_limiter = RateLimiter()
async def perform_list(interaction: nextcord.Interaction, endpoint: str, items_per_page: int, embed_creator: Callable, error_message: str, visible: bool, **kwargs):
await interaction.response.defer(ephemeral=not visible)
items_per_fetch = 100
data_fetcher = lambda page: github_api.fetch_github_page(endpoint, page, items_per_fetch, **kwargs)
initial_data, total_pages = await data_fetcher(1)
if not initial_data:
await interaction.send(error_message)
return
max_page = math.ceil(total_pages * len(initial_data) / items_per_page)
if len(initial_data) >= items_per_fetch:
max_page -= (items_per_fetch // items_per_page - 1)
embed = embed_creator(initial_data[:items_per_page], 1, max_page)
if len(initial_data) <= items_per_page:
await interaction.send(embed=embed)
return
await interaction.send(embed=embed, view=PaginationView(interaction, initial_data, max_page, items_per_page, items_per_fetch, data_fetcher, embed_creator, rate_limiter))
class GitHubUserCog(commands.Cog):
@nextcord.slash_command(name="user", description="Commands about GitHub users")
async def user_cmds(self, interaction: nextcord.Interaction):
pass
@user_cmds.subcommand(name="info", description="Get information about a GitHub user")
async def user_info(self, interaction: nextcord.Interaction, username: str = Options.username, visible: bool = Options.visible):
user_data = await (await github_api.get_user(username)).json()
embed = nextcord.Embed(
title=f'User Info | {user_data["login"]}',
description=user_data["bio"] if user_data["bio"] else "",
color=nextcord.Color.dark_blue()
)
embed.set_thumbnail(url=user_data["avatar_url"])
fields = [
{
"Username": user_data["login"],
"Name": user_data.get("name", "N/A"),
"ID": user_data["id"],
"Email": user_data["email"],
},
{
"Company": user_data["company"],
"Location": user_data["location"],
"Twitter": f'[@{user_data["twitter_username"]}](https://twitter.com/{user_data["twitter_username"]})' if user_data.get("twitter_username") else None,
"Website": f'[Click Here]({user_data["blog"]})' if user_data["blog"] and user_data["blog"].startswith("http") else None,
},
{
"Public Repos": user_data["public_repos"],
"Public Gists": user_data["public_gists"],
},
{
"Followers": user_data["followers"],
"Following": user_data["following"],
},
{
"Created At": format_datetime(user_data["created_at"]),
"Updated At": format_datetime(user_data["updated_at"]),
}
]
for field in fields:
description = "\n".join([f"**{field_name}**: {field_value}" for field_name, field_value in field.items() if field_value or field_value == 0])
if description:
embed.description += f"\n\n{description}"
await interaction.response.send_message(embed=embed, ephemeral=not visible, view=LinkButton("View on GitHub", user_data["html_url"]))
@user_cmds.subcommand(name="followers", description="List followers of a GitHub user")
async def followers(self, interaction: nextcord.Interaction, username: str = Options.username, visible: bool = Options.visible):
items_per_page = 25
endpoint = f"/users/{username}/followers"
embed_creator = lambda users, page, maximum_page: EmbedCreator.create_user_list(users, page, maximum_page, items_per_page, f"{username}'s followers")
error_message = f"No followers found for {username}."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible)
@user_cmds.subcommand(name="following", description="List users followed by a GitHub user")
async def following(self, interaction: nextcord.Interaction, username: str = Options.username, visible: bool = Options.visible):
items_per_page = 25
endpoint = f"/users/{username}/following"
embed_creator = lambda users, page, maximum_page: EmbedCreator.create_user_list(users, page, maximum_page, items_per_page, f"Users followed by {username}")
error_message = f"{username} is not following anyone."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible)
@user_cmds.subcommand(name="stars", description="List repositories starred by a GitHub user")
async def stars(self, interaction: nextcord.Interaction, username: str = Options.username, visible: bool = Options.visible):
items_per_page = 8
endpoint = f"/users/{username}/starred"
embed_creator = lambda stars, page, maximum_page: EmbedCreator.create_star_list(stars, page, maximum_page, items_per_page, f"Repositories starred by {username}")
error_message = f"{username} did not star any repositories."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible, headers={"Accept": "application/vnd.github.star+json"})
@user_cmds.subcommand(name="repositories", description="List repositories of a GitHub User")
async def repositories(self, interaction: nextcord.Interaction, username: str = Options.username, visible: bool = Options.visible):
items_per_page = 8
endpoint = f"/users/{username}/repos"
embed_creator = lambda repos, page, maximum_page: EmbedCreator.create_repo_list(repos, page, maximum_page, items_per_page, f"{username}'s repositories")
error_message = f"{username} has no repositories."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible)
@user_cmds.subcommand(name="gists", description="List gists of a GitHub user")
async def gists(self, interaction: nextcord.Interaction, username: str = Options.username, visible: bool = Options.visible):
items_per_page = 6
endpoint = f"/users/{username}/gists"
embed_creator = lambda gists, page, maximum_page: EmbedCreator.create_gist_list(gists, page, maximum_page, items_per_page, f"Gists of {username}")
error_message = f"No gists found for {username}."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible)
@user_cmds.subcommand(name="organizations", description="List organizations of a GitHub user")
async def organizations(self, interaction: nextcord.Interaction, username: str = Options.username, visible: bool = Options.visible):
items_per_page = 25
endpoint = f"/users/{username}/orgs"
embed_creator = lambda orgs, page, maximum_page: EmbedCreator.create_org_list(orgs, page, maximum_page, items_per_page, f"Organizations of {username}")
error_message = f"{username} is not part of any organizations."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible)
class GitHubRepositoryCog(commands.Cog):
@nextcord.slash_command(name="repository", description="Commands about GitHub repositories")
async def repository_cmds(self, interaction: nextcord.Interaction):
pass
@repository_cmds.subcommand(name="info", description="Get information about a GitHub repository")
async def repository_info(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository, visible: bool = Options.visible):
repo_data = await (await github_api.get_repository(owner, repo)).json()
embed = nextcord.Embed(
title=f'Repository Info | {repo_data["full_name"]}',
description=repo_data["description"] if repo_data["description"] else "",
color=nextcord.Color.blurple()
)
embed.set_thumbnail(url=repo_data["owner"]["avatar_url"])
fields = [
{
"Owner": repo_data["owner"]["login"],
"Main Language": repo_data["language"],
"Archived": "Yes" if repo_data["archived"] else "No",
},
{
"Stars": repo_data["stargazers_count"],
"Forks": repo_data["forks_count"],
"Watchers": repo_data["subscribers_count"],
"Open Issues": repo_data["open_issues_count"],
},
{
"Created At": format_datetime(repo_data["created_at"]),
"Updated At": format_datetime(repo_data["updated_at"]),
"Pushed At": format_datetime(repo_data["pushed_at"]),
},
{
"Default Branch": repo_data["default_branch"],
"Homepage": repo_data["homepage"],
"License": repo_data["license"]["name"] if repo_data["license"] else "N/A",
"Topics": ", ".join([f"`{x}`" for x in repo_data.get("topics", [])]),
}
]
for field in fields:
description = "\n".join([f"- **{field_name}**: {field_value}" for field_name, field_value in field.items() if field_value or field_value == 0])
if description:
embed.description += f"\n\n{description}"
await interaction.response.send_message(embed=embed, ephemeral=not visible, view=LinkButton("View on GitHub", repo_data["html_url"]))
@repository_cmds.subcommand(name="tree", description="Get the tree of files in a GitHub repository")
async def repository_tree(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
path: str = nextcord.SlashOption(description="The path to the directory", required=False, default=""), visible: bool = Options.visible):
await interaction.response.defer(ephemeral=not visible)
contents = await (await github_api.get_repository_contents(owner, repo, path)).json()
if isinstance(contents, dict):
await interaction.followup.send("You provided a file path. Please provide a directory path.")
return
tree = self.format_tree(f"{repo}/{path}", contents)
formatted_tree = "\n".join(tree)
await send_response(interaction, formatted_tree, f"Repository Tree | {owner}/{repo}/{path}", "repository_tree.txt")
@repository_cmds.subcommand(name="file", description="Get the content of a file in a GitHub repository")
async def repository_file(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
path: str = nextcord.SlashOption(description="The path to the file", required=True), visible: bool = Options.visible):
await interaction.response.defer(ephemeral=not visible)
file_data = await (await github_api.get_repository_contents(owner, repo, path)).json()
content = file_data["content"]
content = base64.b64decode(content).decode("utf-8")
if "```" not in content:
await send_response(interaction, content, f"File Content | {owner}/{repo}/{path}", path)
else:
file = nextcord.File(filename=path, fp=io.BytesIO(content.encode()))
await interaction.send(file=file)
@repository_cmds.subcommand(name="issues", description="List issues of a GitHub repository")
async def issues(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
state: str = Options.state, sort: str = Options.sort_issues, direction: str = Options.direction, visible: bool = Options.visible):
items_per_page = 6
endpoint = f"/repos/{owner}/{repo}/issues"
embed_creator = lambda issues, page, maximum_page: EmbedCreator.create_issue_list(issues, page, maximum_page, items_per_page, f"Issues in {owner}/{repo}")
error_message = f"No issues found for {owner}/{repo}."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible, params={"state": state, "sort": sort, "direction": direction})
@repository_cmds.subcommand(name="pull_requests", description="List pull requests of a GitHub repository")
async def pull_requests(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
state: str = Options.state, sort: str = Options.sort_prs, direction: str = Options.direction, visible: bool = Options.visible):
items_per_page = 8
endpoint = f"/repos/{owner}/{repo}/pulls"
embed_creator = lambda prs, page, maximum_page: EmbedCreator.create_pr_list(prs, page, maximum_page, items_per_page, f"Pull Requests in {owner}/{repo}")
error_message = f"No pull requests found for {owner}/{repo}."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible, params={"state": state, "sort": sort, "direction": direction})
@repository_cmds.subcommand(name="commits", description="List commits of a GitHub repository")
async def commits(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository, author: str = Options.author_filter, visible: bool = Options.visible):
items_per_page = 6
endpoint = f"/repos/{owner}/{repo}/commits"
embed_creator = lambda commits, page, maximum_page: EmbedCreator.create_commit_list(commits, page, maximum_page, items_per_page, f"Commits for {repo}")
error_message = f"No commits found for {repo}."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible, params={"author": author} if author else {})
@repository_cmds.subcommand(name="releases", description="List releases of a GitHub repository")
async def releases(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository, visible: bool = Options.visible):
items_per_page = 6
endpoint = f"/repos/{owner}/{repo}/releases"
embed_creator = lambda releases, page, maximum_page: EmbedCreator.create_release_list(releases, page, maximum_page, items_per_page, f"Releases for {repo}")
error_message = f"No releases found for {repo}."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible)
@repository_cmds.subcommand(name="stargazers", description="List users who starred a GitHub repository")
async def stargazers(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository, visible: bool = Options.visible):
items_per_page = 25
endpoint = f"/repos/{owner}/{repo}/stargazers"
embed_creator = lambda stargazers, page, maximum_page: EmbedCreator.create_user_list(stargazers, page, maximum_page, items_per_page, f"Stargazers of {owner}/{repo}")
error_message = f"No stargazers found for {owner}/{repo}."
await perform_list(interaction, endpoint, items_per_page, embed_creator, error_message, visible)
@repository_cmds.subcommand(name="languages", description="List languages used in a GitHub repository")
async def languages(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository, visible: bool = Options.visible):
await interaction.response.defer(ephemeral=not visible)
languages_data = await (await github_api.get_repository_languages(owner, repo)).json()
if not languages_data:
await interaction.followup.send(f"No languages found for {owner}/{repo}.")
return
total_bytes = sum(languages_data.values())
languages_percentage = {lang: (bytes / total_bytes) * 100 for lang, bytes in languages_data.items()}
embed = nextcord.Embed(title=f"Languages used in {owner}/{repo}", color=nextcord.Color.green(), description="")
sorted_languages = sorted(languages_percentage.items(), key=lambda x: x[1], reverse=True)
for language, percentage in sorted_languages:
embed.description += f"**{language}** | {percentage:.2f}%\n"
await interaction.followup.send(embed=embed)
def format_tree(self, name: str, contents: list) -> list:
dirs = [item for item in contents if item['type'] == 'dir']
files = [item for item in contents if item['type'] == 'file']
dirs.sort(key=lambda x: x['name'].lower())
files.sort(key=lambda x: x['name'].lower())
sorted_contents = dirs + files
tree = [f"📁 {name}"]
for i, item in enumerate(sorted_contents):
prefix = '└── ' if i == len(sorted_contents) - 1 else '├── '
icon = '📁 ' if item['type'] == 'dir' else '📄 '
tree.append(f"{prefix}{icon}{item['name']}")
return tree
class GitHubInfoCog(commands.Cog):
@nextcord.slash_command(name="info", description="Commands to get information about GitHub entities")
async def info_cmds(self, interaction: nextcord.Interaction):
pass
@info_cmds.subcommand(name="gist", description="Get information about a GitHub Gist")
async def gist_info(self, interaction: nextcord.Interaction, gist_id: str = Options.gist_id, visible: bool = Options.visible):
gist_data = await (await github_api.get_gist(gist_id)).json()
embed = nextcord.Embed(
title=f'Gist Info | {gist_data["id"]}',
description=gist_data["description"] if gist_data["description"] else "",
color=nextcord.Color.blurple()
)
embed.set_thumbnail(url=gist_data["owner"]["avatar_url"])
fields = [
{
"Owner": gist_data["owner"]["login"],
"Files": ", ".join(gist_data["files"].keys()),
"Language(s)": ", ".join([f"`{lang['language']}`" for lang in gist_data["files"].values()]),
"Size": f'{round(sum([lang["size"] for lang in gist_data["files"].values()]) / 1024, 3)} ko',
},
{
"Comments": gist_data["comments"],
"Forks": len(gist_data["forks"]),
},
{
"Created At": format_datetime(gist_data["created_at"]),
"Updated At": format_datetime(gist_data["updated_at"]),
}
]
for field in fields:
description = "\n".join([f"- **{field_name}**: {field_value}" for field_name, field_value in field.items() if field_value or field_value == 0])
if description:
embed.description += f"\n\n{description}"
await interaction.response.send_message(embed=embed, ephemeral=not visible, view=LinkButton("View on GitHub", gist_data["html_url"]))
@info_cmds.subcommand(name="release", description="Get information about a GitHub repository release")
async def release_info(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
tag: str = nextcord.SlashOption(description="The tag of the release", required=False, default="latest"), visible: bool = Options.visible):
if tag == "latest":
release_data = await (await github_api.get_latest_release(owner, repo)).json()
else:
release_data = await (await github_api.get_release_by_tag(owner, repo, tag)).json()
embed = nextcord.Embed(
title=f'Release Info | {owner}/{repo} | {release_data["tag_name"]}',
description="",
color=nextcord.Color.blurple()
)
embed.set_thumbnail(url=release_data["author"]["avatar_url"])
fields = [
{
"Name": release_data["name"],
"Author": f'[{release_data["author"]["login"]}]({release_data["author"]["html_url"]})',
"Pre-release": "Yes" if release_data["prerelease"] else "No",
},
{
"Created At": format_datetime(release_data["created_at"]),
"Published At": format_datetime(release_data["published_at"]),
},
{
"Download Count": sum(asset["download_count"] for asset in release_data["assets"]),
"Assets": ", ".join([f'[{asset["name"]}]({asset["browser_download_url"]})' for asset in release_data["assets"]]),
}
]
for field in fields:
description = "\n".join([f"- **{field_name}**: {field_value}" for field_name, field_value in field.items() if field_value or field_value == 0])
if description:
embed.description += f"\n\n{description}"
embed.description += f"\n\n**Notes:**\n{release_data['body']}"
await interaction.response.send_message(embed=embed, ephemeral=not visible, view=LinkButton("View on GitHub", release_data["html_url"]))
@info_cmds.subcommand(name="commit", description="Get information about a specific commit in a GitHub repository")
async def commit_info(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
commit_sha: str = nextcord.SlashOption(description="The SHA of the commit", required=True), visible: bool = Options.visible):
commit_data = await (await github_api.get_commit(owner, repo, commit_sha)).json()
embed = nextcord.Embed(
title=f'Commit Info | {owner}/{repo}',
description=commit_data["commit"]["message"],
color=nextcord.Color.blurple()
)
embed.set_thumbnail(url=commit_data["author"]["avatar_url"] if commit_data["author"] else None)
fields = [
{
"SHA": commit_data["sha"],
"Author": f'[{commit_data["commit"]["author"]["name"]}]({commit_data["author"]["html_url"]})',
"Created At": format_datetime(commit_data["commit"]["author"]["date"]),
},
{
"Files Changed": len(commit_data["files"]),
"Additions": sum(file["additions"] for file in commit_data["files"]),
"Deletions": sum(file["deletions"] for file in commit_data["files"]),
"Total Changes": commit_data["stats"]["total"],
}
]
for field in fields:
description = "\n".join([f"- **{field_name}**: {field_value}" for field_name, field_value in field.items() if field_value or field_value == 0])
if description:
embed.description += f"\n\n{description}"
await interaction.response.send_message(embed=embed, ephemeral=not visible, view=LinkButton("View on GitHub", commit_data["html_url"]))
@info_cmds.subcommand(name="pull_request", description="Get information about a GitHub pull request")
async def pull_request_info(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
pr_number: int = nextcord.SlashOption(description="The number of the pull request", required=True), visible: bool = Options.visible):
pr_data = await (await github_api.get_pull_request(owner, repo, pr_number)).json()
embed = nextcord.Embed(
title=f'Pull Request Info | {owner}/{repo} | #{pr_number}',
description="",
color=nextcord.Color.blurple()
)
embed.set_thumbnail(url=pr_data["user"]["avatar_url"])
fields = [
{
"Title": pr_data["title"],
"Author": f'[{pr_data["user"]["login"]}]({pr_data["user"]["html_url"]})',
"State": pr_data["state"],
"Locked": "Yes" if pr_data["locked"] else "No",
},
{
"Comments": pr_data["comments"],
"Commits": pr_data["commits"],
"Changed Files": pr_data["changed_files"],
},
{
"Created At": format_datetime(pr_data["created_at"]),
"Updated At": format_datetime(pr_data["updated_at"]),
"Closed At": format_datetime(pr_data["closed_at"]) if pr_data["closed_at"] else "",
"Merged At": format_datetime(pr_data["merged_at"]) if pr_data["merged_at"] else "",
"Merge Commit SHA": pr_data["merge_commit_sha"] if pr_data["merge_commit_sha"] else "N/A",
},
{
"Additions": pr_data["additions"],
"Deletions": pr_data["deletions"],
"Changed Files": pr_data["changed_files"],
"Commits": pr_data["commits"]
}
]
for field in fields:
description = "\n".join([f"- **{field_name}**: {field_value}" for field_name, field_value in field.items() if field_value or field_value == 0])
if description:
embed.description += f"\n\n{description}"
embed.description += "\n\n**Description**: \n" + pr_data["body"][:1000] + ("..." if len(pr_data["body"]) > 1000 else "") if pr_data["body"] else ""
await interaction.response.send_message(embed=embed, ephemeral=not visible, view=LinkButton("View on GitHub", pr_data["html_url"]))
@info_cmds.subcommand(name="issue", description="Get information about a GitHub issue")
async def issue_info(self, interaction: nextcord.Interaction, owner: str = Options.repo_owner, repo: str = Options.repository,
issue_number: int = nextcord.SlashOption(description="The number of the issue", required=True), visible: bool = Options.visible):
issue_data = await (await github_api.get_issue(owner, repo, issue_number)).json()
embed = nextcord.Embed(
title=f'Issue Info | {owner}/{repo} | #{issue_number}',
description="",
color=nextcord.Color.blurple()
)
embed.set_thumbnail(url=issue_data["user"]["avatar_url"])
fields = [
{
"Title": issue_data["title"],
"Author": issue_data["user"]["login"],
"State": issue_data["state"],
"Locked": "Yes" if issue_data["locked"] else "No",
},
{
"Comments": issue_data["comments"],
"Labels": ", ".join([label["name"] for label in issue_data["labels"]]) if issue_data["labels"] else "None",
},
{
"Created At": format_datetime(issue_data["created_at"]),
"Updated At": format_datetime(issue_data["updated_at"]),
"Closed At": format_datetime(issue_data["closed_at"]) if issue_data["closed_at"] else "",
},
]
for field in fields:
description = "\n".join([f"- **{field_name}**: {field_value}" for field_name, field_value in field.items() if field_value or field_value == 0])
if description:
embed.description += f"\n\n{description}"
embed.description += "\n\n**Description**: \n" + issue_data["body"][:1000] + ("..." if len(issue_data["body"]) > 1000 else "") if issue_data["body"] else ""
await interaction.response.send_message(embed=embed, ephemeral=not visible, view=LinkButton("View on GitHub", issue_data["html_url"]))
class GitHubSearchCog(commands.Cog):
@nextcord.slash_command(name="search", description="Commands for searching GitHub")
async def search_cmds(self, interaction: nextcord.Interaction):
pass
async def perform_search(self, interaction: nextcord.Interaction, endpoint: str, query: str, sort: str, order: str, visible: bool, items_per_page: int, embed_creator_fn: callable, pages_to_subtract: int):
await interaction.response.defer(ephemeral=not visible)
items_per_fetch = 100
params = {"q": query} | {k: v for k, v in {"sort": sort, "order": order}.items() if v}
data_fetcher = lambda page: github_api.search_github_page(endpoint, page, items_per_fetch, params=params)
initial_data, total_pages = await data_fetcher(1)
if not initial_data:
await interaction.send(f"No results found for query: {query}.")
return
max_page = math.ceil(total_pages * len(initial_data) / items_per_page)
if len(initial_data) >= items_per_fetch:
max_page -= pages_to_subtract
embed = embed_creator_fn(initial_data[:items_per_page], 1, max_page)
if len(initial_data) <= items_per_page:
await interaction.send(embed=embed)
return
await interaction.send(embed=embed, view=PaginationView(interaction, initial_data, max_page, items_per_page, items_per_fetch, data_fetcher, embed_creator_fn, rate_limiter))
@search_cmds.subcommand(name="repositories", description="Search GitHub repositories")
async def search_repositories(self, interaction: nextcord.Interaction, query: str = Options.search_query, sort: str = Options.search_repositories_sort, order: str = Options.direction, visible: bool = Options.visible):
embed_creator = lambda repos, page, max_page: EmbedCreator.create_repo_list(repos, page, max_page, 6, f"Search Results for '{query}'", show_owner=True)
await self.perform_search(interaction, "/search/repositories", query, sort, order, visible, 6, embed_creator, 1)
@search_cmds.subcommand(name="users", description="Search GitHub users")
async def search_users(self, interaction: nextcord.Interaction, query: str = Options.search_query, sort: str = Options.search_users_sort, order: str = Options.direction, visible: bool = Options.visible):
embed_creator = lambda users, page, max_page: EmbedCreator.create_user_list(users, page, max_page, 25, f"Search Results for '{query}'")
await self.perform_search(interaction, "/search/users", query, sort, order, visible, 25, embed_creator, 0)
@search_cmds.subcommand(name="code", description="Search GitHub code")
async def search_code(self, interaction: nextcord.Interaction, query: str = Options.search_query, order: str = Options.direction, visible: bool = Options.visible):
embed_creator = lambda code_results, page, max_page: EmbedCreator.create_code_list(code_results, page, max_page, 8, f"Code Search Results for '{query}'")
await self.perform_search(interaction, "/search/code", query, None, order, visible, 8, embed_creator, 1)
@search_cmds.subcommand(name="commits", description="Search GitHub commits")
async def search_commits(self, interaction: nextcord.Interaction, query: str, sort: str = Options.search_commits_sort, order: str = Options.direction, visible: bool = Options.visible):
embed_creator = lambda commits, page, max_page: EmbedCreator.create_commit_list(commits, page, max_page, 8, f"Search Results for '{query}'")
await self.perform_search(interaction, "/search/commits", query, sort, order, visible, 8, embed_creator, 1)
class AdminCog(commands.Cog):
@nextcord.slash_command(name="admin", guild_ids=config["admin_guilds"] or None)
@application_checks.check(lambda i: i.user.id in config["admins"])
async def admin_cmds(self, interaction: nextcord.Interaction):
pass
@admin_cmds.subcommand(name="rate_limits", description="Display current GitHub rate limit statistics")
async def github_rate_limits(self, interaction: nextcord.Interaction):
rate_limit_data = await (await github_api.get_rate_limit()).json()
core_limit = rate_limit_data.get('resources', {}).get('core', {})
search_limit = rate_limit_data.get('resources', {}).get('search', {})
embed = nextcord.Embed(title="GitHub Rate Limits", color=0x2ECC71)
description = (
"**Core API**\n"
f"Limit: {core_limit.get('limit', 'N/A')}\n"
f"Remaining: {core_limit.get('remaining', 'N/A')}\n"
f"Reset: <t:{core_limit.get('reset', 0)}:R>\n\n"
"**Search API**\n"
f"Limit: {search_limit.get('limit', 'N/A')}\n"
f"Remaining: {search_limit.get('remaining', 'N/A')}\n"
f"Reset: <t:{search_limit.get('reset', 0)}:R>"
)
embed.description = description
await interaction.response.send_message(embed=embed)
@admin_cmds.subcommand(name="blacklist_user", description="Add a user to the blacklist")
async def blacklist_user(self, interaction: nextcord.Interaction, user_id: str):
blacklist["users"].append(int(user_id))
save_json(blacklist, "blacklist.json")
await interaction.response.send_message(f"User {user_id} has been added to the blacklist.")
@admin_cmds.subcommand(name="blacklist_server", description="Add a server to the blacklist")
async def blacklist_server(self, interaction: nextcord.Interaction, server_id: str):
blacklist["servers"].append(int(server_id))
save_json(blacklist, "blacklist.json")
await interaction.response.send_message(f"Server {server_id} has been added to the blacklist.")
@admin_cmds.subcommand(name="unblacklist_user", description="Remove a user of the blacklist")
async def unblacklist_user(self, interaction: nextcord.Interaction, user_id: str):
if int(user_id) not in blacklist["users"]:
return await interaction.response.send_message(f"User {user_id} is not in the blacklist.", ephemeral=True)
blacklist["users"].remove(int(user_id))
save_json(blacklist, "blacklist.json")
await interaction.response.send_message(f"User {user_id} has been removed of the blacklist.")
@admin_cmds.subcommand(name="unblacklist_server", description="Remove a server of the blacklist")
async def unblacklist_server(self, interaction: nextcord.Interaction, server_id: str):
if int(server_id) not in blacklist["servers"]:
return await interaction.response.send_message(f"Server {server_id} is not in the blacklist.", ephemeral=True)
blacklist["servers"].remove(int(server_id))
save_json(blacklist, "blacklist.json")
await interaction.response.send_message(f"Server {server_id} has been removed of the blacklist.")
@bot.slash_command(name="help", description="Display the help message")
async def help_command(interaction: nextcord.Interaction):
embed = nextcord.Embed(title="Help", color=0x2ECC71)
command_list = []
for cog in bot.cogs.values():
if cog.__class__.__name__ == "AdminCog":
continue
for command in cog.application_commands:
if command.children:
command_group = f"**{command.name.title()}** - {command.description}\n"
subcommands = [f"{subcommand.get_mention(interaction.guild)} - {subcommand.description}" for subcommand in command.children.values()]
command_group += "\n".join(subcommands)
command_list.append(command_group)
embed.description = "List of available commands:\n\n" + "\n\n".join(command_list)
bot_invite = f"https://discord.com/api/oauth2/authorize?client_id={bot.user.id}"
await interaction.response.send_message(embed=embed, view=LinksButton({"Support server": config["support_server"], "Invite me": bot_invite}))
@tasks.loop(minutes=5)
async def log_task():
await logger.send_logs()
@tasks.loop(seconds=20)
async def change_status():
match random.randint(1, 8):
case 1:
await bot.change_presence(activity=nextcord.Game(name="/help"))
case 2 | 8:
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name=f"{len(bot.guilds)} servers"))
case 3 | 7:
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name=f"{sum([guild.member_count or 1 for guild in bot.guilds])} users"))
case 4:
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name="GitHub repositories"))
case 5:
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name="GitHub users"))
case 6:
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.listening, name="your commands"))
@bot.event
async def on_ready():
log_task.start()
change_status.start()
print(f"Logged in as {bot.user}")
@bot.event
async def on_guild_join(guild: nextcord.Guild):
embed = get_guild_embed(guild, f"Bot Added to {guild.name}", nextcord.Color.green())
await bot.get_channel(config["guilds_channel"]).send(embed=embed)
@bot.event
async def on_guild_remove(guild: nextcord.Guild):
embed = get_guild_embed(guild, f"Bot Removed from {guild.name}", nextcord.Color.red())
await bot.get_channel(config["guilds_channel"]).send(embed=embed)
@bot.event
async def on_application_command_error(interaction: nextcord.Interaction, error: BaseException):
if isinstance(error, nextcord.errors.ApplicationCheckFailure):
return await interaction.send("You don't have enough permissions to run this command!", ephemeral=True)
if isinstance(error, nextcord.errors.ApplicationInvokeError):
error = error.original
if isinstance(error, nextcord.Forbidden):
return await interaction.send("I don't have enough permissions to perform this action.", ephemeral=True)
elif isinstance(error, aiohttp.ClientResponseError):
if error.status == 404:
return await interaction.send("Resource not found.", ephemeral=True)
elif error.status in (403, 429):
return await interaction.send("Github API rate limit exceeded. Please wait a while before trying again.", ephemeral=True)
elif error.status == 401:
return await interaction.send("Unauthorized. GitHub may have revoked the token or it may have expired.", ephemeral=True)
else:
return await interaction.send(f"Failed to fetch the resource: {error.message}", ephemeral=True, allowed_mentions=nextcord.AllowedMentions(everyone=False, users=False, roles=False, replied_user=False))
try:
await interaction.send(f"Unknown error:\n`{error.__class__.__name__}: {error}`", ephemeral=True, allowed_mentions=nextcord.AllowedMentions(everyone=False, users=False, roles=False, replied_user=False))
except nextcord.errors.NotFound:
pass
finally:
with open("errors.log", 'a', encoding='utf-8') as f:
f.write("".join(traceback.format_exception(type(error), error, error.__traceback__)))
@bot.event
async def on_interaction(interaction: nextcord.Interaction):
if interaction.type is nextcord.InteractionType.application_command:
if interaction.guild_id and interaction.guild_id in blacklist["servers"]:
return await interaction.response.send_message("This server is blacklisted.", ephemeral=True)
elif interaction.user.id in blacklist["users"]:
return await interaction.response.send_message("You are blacklisted from using this bot.", ephemeral=True)
command_name = interaction.data.get("name", "unknown")
if await rate_limiter.check_command_limit(interaction.user.id, command_name):
command_full_name = "/" + command_name + " " + interaction.data.get("options", [{}])[0].get("name", "")
command_options = {option["name"]: option["value"] for option in interaction.data.get("options", [{}])[0].get("options", [])}
logger.add_log(interaction.user.id, interaction.user.name, command_full_name, command_options, interaction.guild_id, interaction.channel_id)
else:
limit_type = "search commands" if command_name == "search" else "general commands"
await interaction.send(f"You've reached the rate limit for {limit_type}. Please try again later.", ephemeral=True)
return
await bot.process_application_commands(interaction)
bot.add_cog(GitHubUserCog())
bot.add_cog(GitHubRepositoryCog())
bot.add_cog(GitHubInfoCog())
bot.add_cog(GitHubSearchCog())
bot.add_cog(AdminCog())
bot.run(config["bot_token"])