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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 51 by rakin, Mon Jul 29 17:28:23 2024 UTC revision 256 by rakin, Mon Jul 29 17:29:14 2024 UTC
# Line 1  Line 1 
1  import fs from 'fs';  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';  import Axios, { AxiosRequestHeaders, HeadersDefaults } from 'axios';
5    import { formatDistance } from 'date-fns';
6    import { Snippet } from '../services/SnippetManager';
7    
8  export function timeProcess(seconds: number) {        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 formatDistance(new Date(), 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);      let interval = seconds / (60 * 60 * 24 * 30 * 365);
112    
113      if (interval >= 1) {      if (interval >= 1) {
# Line 42  export function escapeRegex(string: stri Line 148  export function escapeRegex(string: stri
148  }  }
149    
150  export function timeSince(date: number) {  export function timeSince(date: number) {
151      const seconds = Math.floor((Date.now() - date) / 1000);      // const seconds = Math.floor((Date.now() - date) / 1000);
152      return timeProcess(seconds) + ' ago';      // return timeProcess(seconds) + ' ago';
153        return formatDistance(new Date(), new Date(date), { addSuffix: true });
154  }  }
155    
156  export async function download(url: string, path: string, headers?: AxiosRequestHeaders) {    export async function download(url: string, path: string, headers?: AxiosRequestHeaders) {  
# Line 79  export async function deleteFile(path: s Line 186  export async function deleteFile(path: s
186  export function random(arr: Array <any>) {  export function random(arr: Array <any>) {
187      let index = Math.floor(Math.random() * arr.length);      let index = Math.floor(Math.random() * arr.length);
188      return arr[index];      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    }

Legend:
Removed from v.51  
changed lines
  Added in v.256

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26