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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26