botAccounts.ts

1import AppDB from '../classes/AppDB';
2import bcrypt from 'bcrypt';
3import { picDir } from './fileUtils';
4import fs from 'fs';
5import { join } from 'path';
6
7interface BotAccount {
8	username: string;
9	password: string;
10	bio: string;
11	avatar?: string;
12}
13
14export async function makeBot(options: BotAccount): Promise<void> {
15	try {
16		const db = AppDB.getInstance();
17
18		const hashedPassword = await bcrypt.hash(options.password, 10);
19
20		const userExists = await db.statement(
21			`SELECT * FROM Admins WHERE Username = ?`,
22			[options.username],
23		);
24
25		if (userExists.length > 0) {
26			console.error(`Bot account already exists.`);
27			return;
28		}
29
30		await db.statement(
31			`INSERT INTO Admins (Username, Password, Bio, ProfilePicture, IsBot) VALUES (?, ?, ?, ?, ?)`,
32			[options.username, hashedPassword, options.bio, 'default.jpg', 1],
33		);
34	} catch (error) {
35		console.error(`Issue creating bot account: ${error}`);
36	}
37}
38
39export async function deleteBot(username: string): Promise<void> {
40	try {
41		const db = AppDB.getInstance();
42
43		await db.statement(`DELETE FROM Admins WHERE Username = ?`, [username]);
44	} catch (error) {
45		console.error(`Issue deleting bot account: ${error}`);
46	}
47}
48
49export async function checkIfBotExists(username: string): Promise<boolean> {
50	try {
51		const db = AppDB.getInstance();
52
53		const userExists = await db.statement(
54			`SELECT * FROM Admins WHERE Username = ?`,
55			[username],
56		);
57
58		return userExists.length > 0;
59	} catch (error) {
60		console.error(`Issue checking if bot account exists: ${error}`);
61		return false;
62	}
63}
64
65export async function makeBotAvatar(
66	username: string,
67	uuid: string,
68	dir: string,
69): Promise<boolean> {
70	try {
71		// Copy the avatar from the default avatar directory to the bot avatar directory
72		const avatarDir = join(picDir.avatar);
73		const defaultAvatarFile = join(dir);
74		const avatarFile = `${uuid}.${dir.split('.').pop()}`;
75
76		fs.copyFileSync(defaultAvatarFile, join(avatarDir, avatarFile));
77
78		// Update the avatar in the database
79		const db = AppDB.getInstance();
80
81		await db.statement(
82			`UPDATE Admins SET ProfilePicture = ? WHERE Username = ?`,
83			[`${uuid}.${dir.split('.').pop()}`, username],
84		);
85
86		return true;
87	} catch (error) {
88		console.error(`Issue creating bot avatar: ${error}`);
89		return false;
90	}
91}
92