Skip to content

Commit

Permalink
feat(bot): add GuildDelete handler
Browse files Browse the repository at this point in the history
  • Loading branch information
GalvinPython committed Jul 16, 2024
1 parent b1b4efc commit 3b06833
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 10 deletions.
3 changes: 2 additions & 1 deletion api/db/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ export async function initTables() {
members INT,
cooldown INT DEFAULT 30000,
updates_enabled BOOLEAN DEFAULT FALSE,
updates_channel_id VARCHAR(255) DEFAULT NULL
updates_channel_id VARCHAR(255) DEFAULT NULL,
is_in_guild BOOLEAN DEFAULT TRUE
)
`;
const createUsersTable = `
Expand Down
22 changes: 18 additions & 4 deletions api/db/queries/guilds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface Guild {

export async function getGuild(guildId: string): Promise<[QueryError, null] | [null, Guild | null]> {
return new Promise((resolve, reject) => {
pool.query("SELECT * FROM guilds WHERE id = ?", [guildId], (err, results) => {
pool.query("SELECT * FROM guilds WHERE id = ? AND is_in_guild = ?", [guildId, true], (err, results) => {
if (err) {
reject([err, null]);
} else {
Expand All @@ -28,18 +28,20 @@ export async function updateGuild(guild: Omit<Guild, "cooldown" | "updates_enabl
return new Promise((resolve, reject) => {
pool.query(
`
INSERT INTO guilds (id, name, icon, members)
VALUES (?, ?, ?, ?)
INSERT INTO guilds (id, name, icon, members, is_in_guild)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
name = VALUES(name),
icon = VALUES(icon),
members = VALUES(members)
members = VALUES(members),
is_in_guild = VALUES(is_in_guild)
`,
[
guild.id,
guild.name,
guild.icon,
guild.members,
true,
],
(err, results) => {
if (err) {
Expand All @@ -52,6 +54,18 @@ export async function updateGuild(guild: Omit<Guild, "cooldown" | "updates_enabl
});
}

export async function removeGuild(guildId: string): Promise<[QueryError, null] | [null, true]> {
return new Promise((resolve, reject) => {
pool.query("UPDATE guilds SET is_in_guild = ? WHERE id = ?", [false, guildId], (err) => {
if (err) {
reject([err, null]);
} else {
resolve([null, true]);
}
});
});
}

export async function setCooldown(guildId: string, cooldown: number): Promise<[QueryError, null] | [null, Guild]> {
return new Promise((resolve, reject) => {
pool.query("UPDATE guilds SET cooldown = ? WHERE id = ?", [cooldown, guildId], (err, results) => {
Expand Down
15 changes: 13 additions & 2 deletions api/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express, { type NextFunction, type Request, type Response } from "express";
import cors from "cors";
import path from "path";
import { getBotInfo, getGuild, getUser, getUsers, initTables, pool, updateGuild, enableUpdates, disableUpdates, setCooldown, setUpdatesChannel, setXP, setLevel } from "./db";
import { getBotInfo, getGuild, getUser, getUsers, initTables, pool, updateGuild, enableUpdates, disableUpdates, setCooldown, setUpdatesChannel, setXP, setLevel, removeGuild } from "./db";

const app = express();
const PORT = 18103;
Expand Down Expand Up @@ -43,6 +43,17 @@ app.post("/post/:guild", authMiddleware, async (req, res) => {
}
});

app.post('/post/:guild/remove', authMiddleware, async (req, res) => {
const { guild } = req.params;
const [err, results] = await removeGuild(guild);

if (err) {
res.status(500).json({ message: "Internal server error" });
} else {
res.status(200).json(results);
}
})

app.post("/post/:guild/:user", authMiddleware, async (req, res) => {
const { guild, user } = req.params;
const { name, pfp, xp, nickname } = req.body;
Expand Down Expand Up @@ -339,7 +350,7 @@ app.get("/leaderboard/:guild", async (req, res) => {
const [usersErr, usersData] = await getUsers(guild);

if (!guildData) {
return res.status(404).render("error", { error: { status: 404, message: "The guild does not exist" } });
return res.status(404).render("error", { error: { status: 404, message: "The guild does not exist. If Chatr is no longer in this server, the data for this guild has been locked from public access" } });
}

if (guildErr) {
Expand Down
4 changes: 2 additions & 2 deletions api/views/error.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
<div class="user">
<div class="userInfo">
<h1 class="userName">Message</h1>
<h1>
<p>
<%= error.message %>
</h1>
</p>
</div>
</div>
</div>
Expand Down
12 changes: 12 additions & 0 deletions bot/events/guildRemove.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Events } from "discord.js";
import client from "../index";
import { removeGuild } from "../utils/requestAPI";

client.on(Events.GuildDelete, async (guild) => {
try {
await removeGuild(guild.id);
console.log(`Left guild ${guild.name} with ${guild.memberCount} members. The database has been locked`);
} catch (e) {
console.error(e);
}
})
2 changes: 1 addition & 1 deletion bot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.MessageContent
]
});

Expand Down
10 changes: 10 additions & 0 deletions bot/utils/requestAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ export async function updateGuildInfo(guild: string, name: string, icon: string,
})
}

export async function removeGuild(guild: string) {
await fetch(`http://localhost:18103/post/${guild}/remove`, {
headers: {
'Content-Type': 'application/json',
'Authorization': process.env.AUTH as string,
},
method: 'POST',
})
}

export async function setXP(guild: string, user: string, xp: number) {
const response = await fetch(`http://localhost:18103/admin/set/${guild}/xp`, {
"headers": {
Expand Down

0 comments on commit 3b06833

Please sign in to comment.