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

Contents of /trunk/src/services/SnippetManager.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 244 - (show annotations)
Mon Jul 29 17:29:11 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 2411 byte(s)
refactor: improve channel locking systems
1 import { readFile, writeFile } from "fs";
2 import path from "path";
3 import DiscordClient from "../client/Client";
4 import Service from "../utils/structures/Service";
5 import { deleteFile } from "../utils/util";
6
7 export type Snippet = {
8 name: string;
9 content: string;
10 files: string[]
11 };
12
13 export type SnippetContainer = {
14 [guildID: string]: Snippet[];
15 };
16
17 export default class SnippetManager extends Service {
18 snippets: SnippetContainer = {};
19
20 constructor(client: DiscordClient) {
21 super(client);
22 this.load();
23 }
24
25 load() {
26 readFile(path.resolve(__dirname, '../..', 'config/snippets.json'), (err, data) => {
27 if (err) {
28 console.log(err);
29 }
30
31 this.snippets = JSON.parse(data.toString());
32 });
33 }
34
35 write() {
36 writeFile(path.resolve(__dirname, '../..', 'config/snippets.json'), JSON.stringify(this.snippets), () => null);
37 }
38
39 set(guildID: string, name: string, content: string, files: string[] = []): void {
40 this.snippets[guildID].push({
41 name,
42 content,
43 files
44 });
45 }
46
47 get(guildID: string, name: string): Snippet | null {
48 if (!this.snippets[guildID]) {
49 return null;
50 }
51
52 for (const s of this.snippets[guildID]) {
53 if (s.name === name) {
54 return s;
55 }
56 }
57
58 return null;
59 }
60
61 async delete(guildID: string, name: string): Promise<void> {
62 for (const i in this.snippets[guildID]) {
63 if (this.snippets[guildID][i].name === name) {
64 for await (const file of this.snippets[guildID][i].files) {
65 try {
66 await deleteFile(path.resolve(__dirname, '../../storage', file));
67 }
68 catch (e) {
69 console.log(e);
70 }
71 }
72
73 await this.snippets[guildID].splice(parseInt(i), 1);
74
75 return;
76 }
77 }
78 }
79
80 async deleteData(guildID: string, name: string): Promise<void> {
81 for (const i in this.snippets[guildID]) {
82 if (this.snippets[guildID][i].name === name) {
83 await this.snippets[guildID].splice(parseInt(i), 1);
84 return;
85 }
86 }
87 }
88 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26