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

Annotation of /branches/2.x/src/utils/util.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 577 - (hide annotations)
Mon Jul 29 18:52:37 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 5702 byte(s)
chore: add old version archive branches (2.x to 9.x-dev)
1 rakinar2 577 import fs from 'fs';
2     import DiscordClient from '../client/Client';
3     import { GuildMember, Message, CommandInteraction, MessageEmbed, ContextMenuInteraction, Interaction } from 'discord.js';
4     import Axios, { AxiosRequestHeaders, HeadersDefaults } from 'axios';
5     import { formatDistanceToNowStrict } from 'date-fns';
6     import { Snippet } from '../services/SnippetManager';
7    
8     export function parseEmbedsInString(content: string) {
9     const embedExpressions = content.matchAll(/embed\:(\{[^\n]+\})/g);
10     const newContent = content.replace(/embed\:(\{[^\n]+\})/g, '');
11     let embeds: MessageEmbed[] = [];
12    
13     for (const expr of [...embedExpressions]) {
14     const parsed = JSON.parse(expr[1]);
15    
16     try {
17     embeds.push(new MessageEmbed(parsed).setColor(parsed.color));
18     }
19     catch (e) {
20     console.log(e);
21     }
22     }
23    
24     return { embeds, content: newContent };
25     }
26    
27     export function splitMessage(message: string, limit: number = 1000, maxIterationCount: number = 100) {
28     const splitted: string[] = [];
29     let content = message;
30     let { length } = content;
31    
32     if (length >= limit) {
33     let i = 0;
34    
35     while (length !== 0 && content !== '') {
36     splitted.push(content.substring(0, limit));
37     content = content.substring(limit);
38     length = content.length;
39     i++;
40    
41     if (i >= maxIterationCount) {
42     console.log('Break loop');
43     break;
44     }
45     }
46     }
47     else {
48     splitted.push(message);
49     }
50    
51     return splitted;
52     }
53    
54     export function getHomeGuild(client: DiscordClient) {
55     return client.guilds.cache.get(client.config.props.global.id);
56     }
57    
58     export function shouldNotModerate(client: DiscordClient, member: GuildMember) {
59     if (!client.config.props[member.guild.id].admin) {
60     return false;
61     }
62    
63     const role = client.config.props[member.guild.id].admin;
64    
65     return member.roles.cache.has(role);
66     }
67    
68     export async function hasPermission(client: DiscordClient, member: GuildMember, msg: Message | CommandInteraction | ContextMenuInteraction, mod: GuildMember | null, error: string = "You don't have permission to moderate this user") {
69     let m = mod;
70    
71     if (!m) {
72     m = msg.member! as GuildMember;
73     }
74    
75     if (member.id !== m.id && member.roles.highest?.position >= m.roles.highest?.position) {
76     if (msg instanceof Interaction && msg.deferred) {
77     await msg.editReply({
78     embeds: [
79     new MessageEmbed()
80     .setColor('#f14a60')
81     .setDescription(`:x: ${error}`)
82     ]
83     });
84    
85     return false;
86     }
87    
88     await msg.reply({
89     embeds: [
90     new MessageEmbed()
91     .setColor('#f14a60')
92     .setDescription(`:x: ${error}`)
93     ]
94     });
95    
96     return false;
97     }
98    
99     return true;
100     }
101    
102     export function timeProcess(seconds: number) {
103     return formatDistanceToNowStrict(new Date(seconds));
104     }
105    
106    
107     /**
108     * @deprecated
109     */
110     export function timeProcessOld(seconds: number) {
111     let interval = seconds / (60 * 60 * 24 * 30 * 365);
112    
113     if (interval >= 1) {
114     return Math.floor(interval) + " year" + (Math.floor(interval) === 1 ? '' : 's');
115     }
116    
117     interval = seconds / (60 * 60 * 24 * 30);
118    
119     if (interval >= 1) {
120     return Math.floor(interval) + " month" + (Math.floor(interval) === 1 ? '' : 's');
121     }
122    
123     interval = seconds / (60 * 60 * 24);
124    
125     if (interval >= 1) {
126     return Math.floor(interval) + " day" + (Math.floor(interval) === 1 ? '' : 's');
127     }
128    
129     interval = seconds / (60 * 60);
130    
131     if (interval >= 1) {
132     return Math.floor(interval) + " hour" + (Math.floor(interval) === 1 ? '' : 's');
133     }
134    
135     interval = seconds / 60;
136    
137     if (interval >= 1) {
138     return Math.floor(interval) + " minute" + (Math.floor(interval) === 1 ? '' : 's');
139     }
140    
141     interval = seconds;
142    
143     return Math.floor(interval) + " second" + (Math.floor(interval) === 1 ? '' : 's');
144     }
145    
146     export function escapeRegex(string: string) {
147     return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
148     }
149    
150     export function timeSince(date: number) {
151     // const seconds = Math.floor((Date.now() - date) / 1000);
152     // return timeProcess(seconds) + ' ago';
153     return formatDistanceToNowStrict(new Date(date), { addSuffix: true });
154     }
155    
156     export async function download(url: string, path: string, headers?: AxiosRequestHeaders) {
157     const writer = fs.createWriteStream(path);
158    
159     const response = await Axios({
160     url,
161     method: 'GET',
162     responseType: 'stream',
163     headers
164     });
165    
166     response.data.pipe(writer);
167    
168     return new Promise((resolve, reject) => {
169     if (response.status !== 200) {
170     reject();
171     }
172    
173     writer.on('finish', resolve);
174     writer.on('error', reject);
175     });
176     }
177    
178     export async function deleteFile(path: string) {
179     fs.rm(path, (err: any) => {
180     if (err) {
181     throw new Error(err);
182     }
183     });
184     }
185    
186     export function random(arr: Array <any>) {
187     let index = Math.floor(Math.random() * arr.length);
188     return arr[index];
189     }
190    
191     export function fill(length: number, string: string, token: string = ' ') {
192     let safe = 0;
193    
194     if (length < string.length)
195     return string;
196    
197     const diff = length - string.length;
198    
199     for (let i = 1; i <= diff; i++, safe++) {
200     if (safe >= 500)
201     break;
202    
203     string += ' ';
204     }
205    
206     return string;
207     }
208    
209     export function green(string: string) {
210     return '\u001b[1;32m' + string + '\u001b[0m';
211     }
212    
213     export function yellow(string: string) {
214     return '\u001b[1;33m' + string + '\u001b[0m';
215     }
216    
217     export function red(string: string) {
218     return '\u001b[1;31m' + string + '\u001b[0m';
219     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26