/[sudobot]/trunk/src/utils/util.ts
ViewVC logotype

Annotation of /trunk/src/utils/util.ts

Parent Directory Parent Directory | Revision Log Revision Log


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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26