/[sudobot]/branches/5.x/src/utils/utils.ts
ViewVC logotype

Contents of /branches/5.x/src/utils/utils.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 577 - (show annotations)
Mon Jul 29 18:52:37 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 6400 byte(s)
chore: add old version archive branches (2.x to 9.x-dev)
1 /**
2 * This file is part of SudoBot.
3 *
4 * Copyright (C) 2021-2023 OSN Developers.
5 *
6 * SudoBot is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * SudoBot is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with SudoBot. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20 import {
21 APIEmbedField,
22 Channel,
23 ChannelType,
24 ColorResolvable,
25 EmbedBuilder,
26 GuildMember,
27 NewsChannel,
28 PermissionOverwrites,
29 PermissionResolvable,
30 PermissionsBitField,
31 TextChannel,
32 ThreadChannel,
33 User,
34 escapeMarkdown
35 } from "discord.js";
36 import { mkdirSync } from "fs";
37 import path from "path";
38 import Client from "../core/Client";
39 import { ActionDoneName } from "../services/InfractionManager";
40
41 export function isSnowflake(input: string) {
42 return /^\d{16,22}$/.test(input);
43 }
44
45 export interface CreateModerationEmbedOptions {
46 user: User;
47 actionDoneName?: ActionDoneName;
48 reason?: string;
49 description?: string;
50 fields?:
51 | APIEmbedField[]
52 | ((fields: APIEmbedField[], id: string, reason?: string) => Promise<APIEmbedField[]> | APIEmbedField[]);
53 id: string | number;
54 color?: ColorResolvable;
55 }
56
57 export async function createModerationEmbed({
58 user,
59 actionDoneName,
60 reason,
61 description,
62 fields,
63 id,
64 color = 0xf14a60
65 }: CreateModerationEmbedOptions) {
66 return new EmbedBuilder({
67 author: {
68 name: user.tag,
69 icon_url: user.displayAvatarURL()
70 },
71 description: description ?? `**${escapeMarkdown(user.tag)}** has been ${actionDoneName}.`,
72 fields:
73 typeof fields === "function"
74 ? await fields(
75 [
76 {
77 name: "Reason",
78 value: reason ?? "*No reason provided*"
79 },
80 {
81 name: "Infraction ID",
82 value: `${id}`
83 }
84 ],
85 `${id}`,
86 reason
87 )
88 : [
89 {
90 name: "Reason",
91 value: reason ?? "*No reason provided*"
92 },
93 ...(fields ?? []),
94 {
95 name: "Infraction ID",
96 value: `${id}`
97 }
98 ],
99 footer: actionDoneName
100 ? {
101 text: actionDoneName[0].toUpperCase() + actionDoneName.substring(1)
102 }
103 : undefined
104 })
105 .setTimestamp()
106 .setColor(color);
107 }
108
109 export function getEmoji(client: Client, name: string) {
110 return (
111 client.configManager.systemConfig.emojis?.[name] ??
112 client.emojiMap.get(name)?.toString() ??
113 client.emojis.cache.find(e => e.name === name)?.toString() ??
114 ""
115 );
116 }
117
118 export function isTextableChannel(
119 channel: Channel | ThreadChannel,
120 DMs = false
121 ): channel is TextChannel | NewsChannel | ThreadChannel {
122 return [
123 ...(DMs ? [ChannelType.DM, ChannelType.GroupDM] : []),
124 ChannelType.GuildAnnouncement,
125 ChannelType.GuildText,
126 ChannelType.PrivateThread,
127 ChannelType.PublicThread
128 ].includes(channel.type);
129 }
130
131 export function developmentMode() {
132 return (
133 ["dev", "development"].includes(process.env.NODE_ENV?.toLowerCase()!) ||
134 ["dev", "development"].includes(process.env.SUDO_ENV?.toLowerCase()!)
135 );
136 }
137
138 export function isImmuneToAutoMod(
139 client: Client,
140 member: GuildMember,
141 permission?: PermissionResolvable[] | PermissionResolvable
142 ) {
143 return client.permissionManager.isImmuneToAutoMod(member, permission);
144 }
145
146 export function wait(time: number) {
147 return new Promise(resolve => setTimeout(resolve, time));
148 }
149
150 export function sudoPrefix(pathLike: string, createDirIfNotExists = false) {
151 const directoryOrFile = path.resolve(process.env.SUDO_PREFIX ?? __dirname, process.env.SUDO_PREFIX ? "" : "../..", pathLike);
152
153 if (createDirIfNotExists) mkdirSync(directoryOrFile, { recursive: true });
154
155 return directoryOrFile;
156 }
157
158 export function getPermissionNames(permissionsBit: bigint) {
159 const result = [];
160 const permissions = new PermissionsBitField(permissionsBit);
161
162 for (const permission of Object.keys(PermissionsBitField.Flags) as (keyof typeof PermissionsBitField.Flags)[]) {
163 if (permissions.has(PermissionsBitField.Flags[permission])) {
164 result.push(permission);
165 }
166 }
167
168 return result;
169 }
170
171 export function forceGetPermissionNames(permissions: PermissionResolvable[]) {
172 const strings: string[] = [];
173
174 for (const permission of permissions) {
175 if (typeof permission === "bigint") {
176 strings.push(...getPermissionNames(permission));
177 } else if (typeof permission === "string") {
178 strings.push(permission);
179 } else throw new Error("Unknown permission type");
180 }
181
182 return strings;
183 }
184
185 export function getChannelPermissionOverride(permission: PermissionResolvable, permissionOverwrites: PermissionOverwrites) {
186 return permissionOverwrites.allow.has(permission, true)
187 ? true
188 : permissionOverwrites.deny.has(permission, true)
189 ? true
190 : null;
191 }
192
193 export function chunkedString(str: string, chunkSize = 4000) {
194 let output = [];
195 let chunk = "";
196
197 for (let i = 0; i < str.length; i++) {
198 if (i !== 0 && i % chunkSize === 0) {
199 output.push(chunk);
200 chunk = str[i];
201 continue;
202 }
203
204 chunk += str[i];
205 }
206
207 if (chunk.length !== 0) {
208 output.push(chunk);
209 }
210
211 return output;
212 }
213
214 export function escapeRegex(string: string) {
215 return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&");
216 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26