-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
188 lines (143 loc) · 8.18 KB
/
utils.py
File metadata and controls
188 lines (143 loc) · 8.18 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
import io
import json
from collections import defaultdict
from datetime import datetime, timedelta
import aiohttp
import nextcord
def load_json(file_path: str) -> dict:
with open(file_path, "r", encoding="utf-8") as file:
return json.load(file)
def save_json(data: dict, file_path: str) -> None:
with open(file_path, "w", encoding="utf-8") as file:
json.dump(data, file, indent=4)
def format_datetime(date_str: str) -> str:
if date_str.endswith("Z"):
parsed_date = datetime.fromisoformat(date_str[:-1]).timestamp()
else:
parsed_date = datetime.fromisoformat(date_str[:-6]).timestamp()
return f"<t:{round(parsed_date)}>"
async def send_response(interaction: nextcord.Interaction, content: str, title: str, file_name: str) -> None:
file_extension = file_name.split(".")[-1]
if len(content) <= 2000:
await interaction.send(f"```{file_extension}\n{content}```", allowed_mentions=nextcord.AllowedMentions(everyone=False, users=False, roles=False, replied_user=False))
elif len(content) <= 4000:
embed = nextcord.Embed(title=title[:256], description=f"```{file_extension}\n{content}```", color=nextcord.Color.blurple())
await interaction.send(embed=embed)
else:
file = nextcord.File(filename=file_name, fp=io.BytesIO(content.encode()))
await interaction.send(file=file)
async def send_webhook(webhook_url: str, content: str, extension: str) -> None:
content = f"```{extension}\n{content}```"
async with aiohttp.ClientSession() as session:
if len(content) < 2000:
payload = {"content": content, "username": "Logs"}
await session.post(webhook_url, json=payload)
elif len(content) < 4096:
payload = {
"embeds": [{
"description": content,
"color": 3447003
}],
"username": "Logs"
}
await session.post(webhook_url, json=payload)
else:
content = content.replace(f"```{extension}\n", "").replace("```", "").strip()
file = io.StringIO(content)
payload = aiohttp.FormData()
payload.add_field('file', file, filename=f'content.{extension}')
payload.add_field('username', 'Logs')
await session.post(webhook_url, data=payload)
def get_guild_embed(guild: nextcord.Guild, title: str, color: nextcord.Color) -> nextcord.Embed:
embed = nextcord.Embed(title=title, color=color)
embed.add_field(name="Server ID", value=guild.id, inline=False)
embed.add_field(name="Owner", value=f"ID: {guild.owner_id}", inline=False)
embed.add_field(name="Member Count", value=guild.member_count, inline=False)
embed.add_field(name="Created At", value=f"<t:{round(guild.created_at.timestamp())}>", inline=False)
if guild.icon:
embed.set_thumbnail(url=guild.icon.url)
return embed
class LinkButton(nextcord.ui.View):
def __init__(self, label: str, url: str, emoji: str = "🔗"):
super().__init__()
self.add_item(nextcord.ui.Button(label=label, url=url, emoji=emoji))
class LinksButton(nextcord.ui.View):
def __init__(self, links: dict):
super().__init__()
for label, url in links.items():
self.add_item(nextcord.ui.Button(label=label, url=url, emoji="🔗"))
class Options:
visible = nextcord.SlashOption(description="Whether the response should be visible to everyone", required=False, default=True)
username = nextcord.SlashOption(description="The GitHub username of the user", required=True, max_length=39)
repo_owner = nextcord.SlashOption(description="The owner of the repository", required=True, max_length=39)
repository = nextcord.SlashOption(description="The name of the repository", required=True, max_length=100)
gist_id = nextcord.SlashOption(description="The ID of the gist", required=True, max_length=32)
state = nextcord.SlashOption(description="Indicates the state of the issues to return", required=False, choices=["open", "closed", "all"], default="open")
sort_issues = nextcord.SlashOption(description="The sort order of the issues", required=False, choices=["created", "updated", "comments"], default="created")
sort_prs = nextcord.SlashOption(description="The sort order of the pull requests", required=False, choices=["created", "updated", "popularity", "long-running"], default="created")
direction = nextcord.SlashOption(description="The direction to sort the results by", required=False, choices={"asc": "ascending", "desc": "descending"}, default="desc")
author_filter = nextcord.SlashOption(description="GitHub username or email address to use to filter by author", required=False)
search_query = nextcord.SlashOption(description="The query to search for", required=True, max_length=256)
search_repositories_sort = nextcord.SlashOption(description="The sort order of the repositories", required=False, choices=["stars", "forks", "help-wanted-issues", "updated"])
search_users_sort = nextcord.SlashOption(description="The sort order of the users", required=False, choices=["followers", "repositories", "joined"])
search_commits_sort = nextcord.SlashOption(description="The sort order of the commits", required=False, choices=["author-date", "committer-date"])
class RateLimiter:
def __init__(self):
self.command_limits = {"general": [], "search": []}
self.command_limits = defaultdict(lambda: defaultdict(list))
self.button_limits = defaultdict(list)
self.last_cleanup = datetime.now()
def cleanup_old_data(self):
current_time = datetime.now()
if current_time - self.last_cleanup < timedelta(minutes=5):
return
one_hour_ago = current_time - timedelta(hours=1)
for user_id in list(self.command_limits.keys()):
self.command_limits[user_id]["general"] = [t for t in self.command_limits[user_id]["general"] if t > one_hour_ago]
self.command_limits[user_id]["search"] = [t for t in self.command_limits[user_id]["search"] if t > one_hour_ago]
if not self.command_limits[user_id]["general"] and not self.command_limits[user_id]["search"]:
del self.command_limits[user_id]
for user_id in list(self.button_limits.keys()):
self.button_limits[user_id] = [t for t in self.button_limits[user_id] if t > one_hour_ago]
if not self.button_limits[user_id]:
del self.button_limits[user_id]
self.last_cleanup = current_time
async def check_command_limit(self, user_id, command_name):
self.cleanup_old_data()
if command_name == "search":
user_commands = self.command_limits[user_id]["search"]
limit = 20
global_limit = 25
else:
user_commands = self.command_limits[user_id]["general"]
limit = 100
global_limit = 150
if len(user_commands) >= limit:
return False
if sum(len(data[command_name]) for data in self.command_limits.values()) >= global_limit:
return False
user_commands.append(datetime.now())
return True
async def check_button_limit(self, user_id):
self.cleanup_old_data()
user_buttons = self.button_limits[user_id]
if len(user_buttons) >= 500:
return False
user_buttons.append(datetime.now())
return True
class Logger:
def __init__(self, webhook_url):
self.logs = []
self.webhook_url = webhook_url
def add_log(self, user_id: int, username: str, command: str, options: dict, guild_id: int, channel_id: int):
formatted_options = ', '.join([f"{k}={v}" for k, v in options.items()])
formatted_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_message = f"[{formatted_date}] {user_id} ({username}) used command {command} with options {formatted_options} on guild {guild_id} in channel {channel_id}"
self.logs.append(log_message)
async def send_logs(self):
if not self.logs:
return
await send_webhook(self.webhook_url, "\n".join(self.logs), "log")
with open("logs.txt", "a") as f:
f.write("\n".join(self.logs) + "\n")
self.logs.clear()