/[sudobot]/trunk/src/services/AFKEngine.ts
ViewVC logotype

Diff of /trunk/src/services/AFKEngine.ts

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

revision 226 by rakin, Mon Jul 29 17:29:06 2024 UTC revision 304 by rakin, Mon Jul 29 17:29:27 2024 UTC
# Line 1  Line 1 
1  import { CommandInteraction, GuildMember, Message, User } from "discord.js";  import { formatDistanceToNowStrict } from "date-fns";
2    import { CommandInteraction, GuildMember, Message, User, Util } from "discord.js";
3  import DiscordClient from "../client/Client";  import DiscordClient from "../client/Client";
4  import MessageEmbed from "../client/MessageEmbed";  import MessageEmbed from "../client/MessageEmbed";
5  import { notAFK } from "../commands/utils/AFKCommand";  import AFKCommand from "../commands/utils/AFKCommand";
6    import AFK from "../models/AFK";
7  import Service from "../utils/structures/Service";  import Service from "../utils/structures/Service";
8    
9    export interface MentionSchema {
10        date: number;
11        user: string;
12    }
13    
14  export default class AFKEngine extends Service {  export default class AFKEngine extends Service {
15      mention(msg: Message, user: GuildMember, cb: (data: any) => void, msg1?: any) {      list: AFK[] = [];
16          this.client.db.get('SELECT * FROM afk WHERE user_id = ?', [user.id], (err: any, data: any) => {  
17              if (data) {      constructor(client: DiscordClient) {
18                  if (msg1 === undefined) {          super(client);
19                      msg.channel!.send({          AFK.findAll().then(models => this.list = models).catch(console.error);
20                          embeds: [      }
21                              new MessageEmbed()  
22                              .setDescription(`**${user.user.tag}** is AFK right now${data.reason.trim() == '' ? '.' : (' for reason: **' + data.reason.replace(/\*/g, '\\*') + '**')}`)      findUsers(ids: string[], guild: string) {
23                          ]          return this.list.filter(afk => ids.includes(afk.get("user") as string) && afk.get("guild_id") as string === guild);
24                      });      }
25    
26        async removeUser(id: string, guild: string) {
27            let index = 0;
28    
29            for await (const afk of this.list) {
30                if (afk.get('user') === id && afk.get("guild_id") === guild) {
31                    await afk.destroy();
32                    this.list.splice(index, 1);
33                }
34    
35                index++;
36            }
37        }
38        
39        async toggle(message: Message | CommandInteraction, enable: boolean = false, status?: string) {
40            const afk = this.findUsers([message.member!.user.id], message.guild!.id);
41    
42            if (afk.length > 0) {
43                const mentions = afk[0].get("mentions")! as Array<MentionSchema>;
44                let count = 0, text = '';
45    
46                for await (const m of mentions) {
47                    if (count >= 3) {
48                        break;
49                  }                  }
50    
51                  this.client.db.get('UPDATE afk SET mentions = ? WHERE id = ?', [parseInt(data.mentions) + 1, data.id], (err: any) => {});                  let member: GuildMember | undefined;
52    
53                  cb(data);                  try {
54                        member = await message.guild!.members.fetch(m.user);
55    
56                        if (!member) {
57                            throw new Error("user not found");
58                        }
59                    }
60                    catch (e) {
61                        console.log(e);
62                        continue;                    
63                    }
64                    
65                    text += `\nFrom ${member.toString()}, ${formatDistanceToNowStrict(m.date, { addSuffix: true })}`;
66                    count++;
67              }              }
         });  
68    
69                await this.client.afkEngine.removeUser(message.member!.user.id, message.guild!.id);
70    
71                await message.reply({
72                    embeds: [
73                        new MessageEmbed({
74                            description: `You're no longer AFK. You had ${mentions.length ?? 0} mentions in the server(s) where SudoBot is in.${mentions.length > 0 ? `\n\n**Mentions**:${text}` : ''}`,
75                        })
76                    ]
77                });
78            }
79            else if (enable) {
80                this.client.afkEngine.list.push(await AFK.create({
81                    user: message.member!.user.id,
82                    guild_id: message.guild!.id,
83                    mentions: [],
84                    reason: status ?? undefined
85                }));
86    
87                await message.reply({
88                    embeds: [
89                        new MessageEmbed({
90                            description: `You're AFK now${status ? `, for reason: **${Util.escapeMarkdown(status)}**` : ''}.`
91                        })
92                    ]
93                });
94            }
95      }      }
96    
97      start(msg: Message) {      async start(msg: Message) {
98          if (msg.author.bot)          if (msg.author.bot)
99              return;              return;
100    
101            const selfAFK = this.findUsers([msg.author.id], msg.guild!.id);
102    
103            if (selfAFK.length > 0) {
104                this.toggle(msg, false);
105            }
106                    
107          const mention = msg.mentions.members!.first();          const mention = msg.mentions.members?.first();
108    
109          if (mention) {          if (mention) {
110              this.mention(msg, msg.member!, data => {              const afkRecords: AFK[] = this.findUsers([...msg.mentions.members!.keys()].slice(0, 3), msg.guild!.id);
111                  if (msg.author.id === data.user_id) {  
112                      notAFK(this.client, msg, data);              if (!afkRecords || afkRecords.length < 1) {
113                  }                  return;
114              }, true);              }
115                
116              msg.mentions.members!.forEach((member) => {              for (const record of afkRecords) {
117                  this.mention(msg, member, data => {                  const mentions = record.get("mentions") as MentionSchema[];
118                      if (msg.author.id === data.user_id) {  
119                          notAFK(this.client, msg, data);                  mentions.push({
120                      }                      date: Date.now(),
121                        user: msg.author.id
122                  });                  });
123              });  
124          }                  record.set("mentions", mentions).save();
125          else {              }
126              this.client.db.get('SELECT * FROM afk WHERE user_id = ?', [msg.author.id], (err: any, data: any) => {  
127                  if (data) {              let text = `The following users are AFK right now:`;
128                      notAFK(this.client, msg, data);  
129                if (afkRecords.length > 1) {
130                    for await (const afkRecord of afkRecords) {
131                        text += `\n**${msg.mentions.members!.get(afkRecord.get("user") as string)!.user.tag}**${afkRecord.get("reason") as (null | string) ? `\n**Reason**: ${Util.escapeMarkdown(afkRecord.get("reason") as string)}` : ""}`;
132                  }                  }
133                }
134                else {
135                    text = `${msg.mentions.members!.get(afkRecords[0].get("user") as string)!.user.tag} is AFK right now${afkRecords[0].get("reason") as (null | string) ? `, for reason **${Util.escapeMarkdown(afkRecords[0].get("reason") as string)}**` : ""}.`;
136                }
137    
138                await msg.reply({
139                    embeds: [
140                        new MessageEmbed({
141                            description: text
142                        })
143                    ]
144              });              });
145          }          }
146      }      }

Legend:
Removed from v.226  
changed lines
  Added in v.304

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26