Skip to content
This repository was archived by the owner on May 15, 2025. It is now read-only.

Commit cbb3491

Browse files
many changes, it should work now I hope...
1 parent f036375 commit cbb3491

File tree

5 files changed

+97
-176
lines changed

5 files changed

+97
-176
lines changed

src/commands/main/data.ts

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,58 @@
11
import { SlashCommandBuilder, EmbedBuilder, ChatInputCommandInteraction } from "discord.js";
22
import { KOGBot } from "index.js";
3-
3+
import knex, { Knex } from "knex";
44
class GetDataCommand implements SlashCommand {
55
name = "data";
6-
description = "Database command for KOG. ";
6+
description = "Database command for KOG.";
77
subcommands = [];
88
parameters = [];
9-
dev = true; // dev for now
9+
dev = true;
1010
kogBot: KOGBot;
11+
db: Knex;
1112

1213
constructor(kogBot: KOGBot) {
1314
this.kogBot = kogBot;
15+
16+
// Initialize knex with database configuration from this.environment.database
17+
this.db = knex({
18+
client: 'mysql',
19+
connection: {
20+
host: this.kogBot.environment.database.host,
21+
user: this.kogBot.environment.database.user,
22+
password: this.kogBot.environment.database.password,
23+
database: this.kogBot.environment.database.name
24+
}
25+
});
1426
}
1527

1628
async execute(interaction: ChatInputCommandInteraction): Promise<void> {
1729
try {
1830
const user = interaction.user;
1931
const userId = interaction.user.id; // Needed for DB
2032

21-
connection.query('SELECT * FROM KOGDB WHERE userid = ?', [userId], async (err, results) => {
22-
if (err) {
23-
console.error(err);
24-
const embedError = new EmbedBuilder()
25-
.setColor("#E73A3A")
26-
.setTitle("Database Error")
27-
.setDescription("An error occurred while trying to retrieve your data.");
28-
await interaction.reply({ embeds: [embedError] });
29-
return;
30-
}
33+
const results = await this.db('KOGDB').where({ userid: userId });
3134

32-
if (results.length > 0) {
33-
34-
const { eventsAttended, eventsHosted } = results[0];
35+
if (results.length > 0) {
36+
const { eventsAttended, eventsHosted } = results[0];
3537

36-
const embed = new EmbedBuilder()
37-
.setColor("#9033FF")
38-
.setTitle(`Information Retrieved on ${user.username}`)
39-
.addFields(
40-
{ name: "Events Attended", value: eventsAttended.toString() },
41-
{ name: "Events Hosted", value: eventsHosted.toString() }
42-
);
38+
const embed = new EmbedBuilder()
39+
.setColor("#9033FF")
40+
.setTitle(`Information Retrieved on ${user.username}`)
41+
.addFields(
42+
{ name: "Events Attended", value: eventsAttended.toString() },
43+
{ name: "Events Hosted", value: eventsHosted.toString() }
44+
);
4345

44-
await interaction.reply({ embeds: [embed] });
46+
await interaction.reply({ embeds: [embed] });
4547

46-
} else {
47-
const embedFail = new EmbedBuilder()
48-
.setColor("#E73A3A")
49-
.setTitle("No Data Found")
50-
.setDescription("You need to be logged for an event before you can retrieve your data.");
48+
} else {
49+
const embedFail = new EmbedBuilder()
50+
.setColor("#E73A3A")
51+
.setTitle("No Data Found")
52+
.setDescription("You need to be logged for an event before you can retrieve your data.");
5153

52-
await interaction.reply({ embeds: [embedFail] });
53-
}
54-
});
54+
await interaction.reply({ embeds: [embedFail] });
55+
}
5556

5657
} catch (error) {
5758
console.error(error);

src/commands/main/log.ts

Lines changed: 49 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,6 @@
1-
import { SlashCommandBuilder, EmbedBuilder, ChatInputCommandInteraction } from 'discord.js';
2-
import mysql from 'mysql';
3-
import { KOGBot } from 'index.ts';
4-
import { SlashCommand } from 'main.d.ts';
5-
import config from '../../config';
6-
7-
const allowedroleID = config.discord.mr_role; // Set this later when I have perms
8-
const logchannel = config.discord.log_channel; // log channel
9-
const connection = mysql.createConnection({
10-
host: config.database.host,
11-
port: config.database.port,
12-
user: config.database.user,
13-
password: config.database.password,
14-
database: config.database.schema,
15-
});
1+
import { EmbedBuilder, ChatInputCommandInteraction, GuildMemberRoleManager } from 'discord.js';
2+
import { KOGBot } from '../../index.js';
3+
import knex, { Knex } from "knex";
164

175
class LogEventCommand implements SlashCommand {
186
name = 'log';
@@ -21,15 +9,29 @@ class LogEventCommand implements SlashCommand {
219
parameters = [];
2210
dev = true;
2311
kogBot: KOGBot;
12+
db: Knex;
2413

2514
constructor(kogBot: KOGBot) {
2615
this.kogBot = kogBot;
27-
}
16+
this.db = knex({
17+
client: 'mysql',
18+
connection: {
19+
host: this.kogBot.environment.database.host,
20+
user: this.kogBot.environment.database.user,
21+
password: this.kogBot.environment.database.password,
22+
database: this.kogBot.environment.database.name
23+
}
24+
});
25+
}
2826

2927
async execute(interaction: ChatInputCommandInteraction): Promise<void> {
28+
const allowedroleID = this.kogBot.environment.discord.mr_role; // Set this later when I have perms
29+
const logChannel = this.kogBot.environment.discord.logChannel; // log channel
30+
const userId = interaction.user.id; // Needed for DB
31+
const DB = await this.db('KOGDB').where({ userid: userId });
3032
try {
3133
// Check for required role
32-
if (!interaction.member?.roles.cache.has(allowedroleID)) {
34+
if (!(interaction.member?.roles instanceof GuildMemberRoleManager) || !interaction.member.roles.cache.has(allowedroleID)) {
3335
const noperms = new EmbedBuilder()
3436
.setColor('#E73A3A')
3537
.setTitle('Error')
@@ -48,9 +50,14 @@ class LogEventCommand implements SlashCommand {
4850

4951
await interaction.reply({ embeds: [logStart], ephemeral: true });
5052

51-
const filter = (message: any) => message.author.id === interaction.user.id && message.channel.id === interaction.channel.id;
52-
const input = await interaction.channel.awaitMessages({ filter, max: 1, time: 60000, errors: ['time'] });
53-
const response = input.first()?.content;
53+
if (!interaction.channel) {
54+
await interaction.reply('Channel not found.');
55+
return;
56+
}
57+
58+
const filter = (response: any) => response.user.id === interaction.user.id;
59+
const collected = await interaction.channel?.awaitMessageComponent({ filter, time: 60000 }).catch(() => null);
60+
const response = collected?.isMessageComponent() ? collected.message.content : null;
5461

5562
const mentionRegexthing = /^<@\d+>(?:,\s?<@\d+>)*$/;
5663

@@ -64,11 +71,15 @@ class LogEventCommand implements SlashCommand {
6471
return;
6572
}
6673

67-
if (response instanceof Error && response.message === 'time') {
74+
if (response && typeof response === 'object' && 'message' in response && (response as any).message === 'time') {
6875
await interaction.reply(`<@${interaction.user.id}> you took too long to follow up, please try again.`);
6976
return;
7077
}
7178

79+
if (!response) {
80+
await interaction.followUp('No response received. Please try again.');
81+
return;
82+
}
7283
const mentions = response.split(',').map((id: string) => id.trim().replace('<@', '').replace('>', ''));
7384
const userIds: string[] = [];
7485

@@ -82,71 +93,47 @@ class LogEventCommand implements SlashCommand {
8293
return;
8394
}
8495

85-
8696
const host = interaction.user.id;
8797
userIds.push(host);
8898

89-
// Log the event in the log channel
9099
const timestamp = Math.floor(Date.now() / 1000);
91100
const logEmbed = new EmbedBuilder()
92101
.setColor('#9033FF')
93102
.setTitle('Event log')
94-
.setDescription(`A new event was logged.\n\nHost: <@${host}>\n\nTime: <t:${timestamp}:F>\n\nAttendees: ${mentions.map(id => `<@${id}>`).join(', ')}\n\nSquadron Rally: False`)
103+
.setDescription(`A new event was logged.\n\nHost: <@${host}>\n\nTime: <t:${timestamp}:F>\n\nAttendees: ${mentions.map((id: string) => `<@${id}>`).join(', ')}\n\nSquadron Rally: False`)
95104
.setTimestamp();
96105

97-
const logChannel = await interaction.client.channels.fetch(logchannel);
98-
if (logChannel?.isText()) {
106+
if (logChannel) {
99107
await logChannel.send({ embeds: [logEmbed] });
100108
}
101109

110+
const db = knex({ client: 'mysql', connection: this.kogBot.environment.database });
111+
102112
for (const userId of userIds) {
103-
connection.query('SELECT * FROM KOGDB WHERE userId = ?', [userId], async (err, results) => {
104-
if (err) {
105-
console.error(err);
106-
await interaction.followUp('There was an error querying the database.');
107-
return;
108-
}
113+
try {
114+
const results = await db('KOGDB').where({ userId });
109115

110116
if (results.length > 0) {
111-
112117
if (userId === host) {
113-
connection.query('UPDATE KOGDB SET eventsAttended = eventsAttended + 1, eventsHosted = eventsHosted + 1 WHERE userId = ?', [userId], async (updateErr) => {
114-
if (updateErr) {
115-
console.error(updateErr);
116-
await interaction.followUp('There was an error updating the database.');
117-
return;
118-
}
118+
await db('KOGDB').where({ userId }).update({
119+
eventsAttended: db.raw('eventsAttended + 1'),
120+
eventsHosted: db.raw('eventsHosted + 1')
119121
});
120122
} else {
121-
connection.query('UPDATE KOGDB SET eventsAttended = eventsAttended + 1 WHERE userId = ?', [userId], async (updateErr) => {
122-
if (updateErr) {
123-
console.error(updateErr);
124-
await interaction.followUp('There was an error updating the database.');
125-
return;
126-
}
123+
await db('KOGDB').where({ userId }).update({
124+
eventsAttended: db.raw('eventsAttended + 1')
127125
});
128126
}
129127
} else {
130-
131128
if (userId === host) {
132-
connection.query('INSERT INTO KOGDB (userId, eventsAttended, eventsHosted) VALUES (?, 1, 1)', [userId], async (insertErr) => {
133-
if (insertErr) {
134-
console.error(insertErr);
135-
await interaction.followUp('There was an error updating the database.');
136-
return;
137-
}
138-
});
129+
await db('KOGDB').insert({ userId, eventsAttended: 1, eventsHosted: 1 });
139130
} else {
140-
connection.query('INSERT INTO KOGDB (userId, eventsAttended, eventsHosted) VALUES (?, 1, 0)', [userId], async (insertErr) => {
141-
if (insertErr) {
142-
console.error(insertErr);
143-
await interaction.followUp('There was an error updating the database.');
144-
return;
145-
}
146-
});
131+
await db('KOGDB').insert({ userId, eventsAttended: 1, eventsHosted: 0 });
147132
}
148133
}
149-
});
134+
} catch (err) {
135+
console.error(err);
136+
}
150137
}
151138

152139
const dbEmbed = new EmbedBuilder()
@@ -172,4 +159,4 @@ class LogEventCommand implements SlashCommand {
172159
}
173160
}
174161

175-
export default LogEventCommand;
162+
export default LogEventCommand;

src/commands/main/mydata.ts

Lines changed: 0 additions & 56 deletions
This file was deleted.

src/commands/misc/kill.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { EmbedBuilder, ChatInputCommandInteraction } from "discord.js";
2-
import { KOGBot } from "index.js";
2+
import { KOGBot } from "../../index.js";
33

44
class KillCommand implements SlashCommand {
55
name = 'kill';

src/commands/misc/ping.ts

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,29 @@
1-
import { SlashCommandBuilder, EmbedBuilder, ChatInputCommandInteraction, Colors } from "discord.js";
2-
import { KOGBot } from "index.js";
1+
import { ChatInputCommandInteraction } from "discord.js";
2+
import { KOGBot } from "../../index.js"; // Adjust the path if necessary
33

44
class PingCommand implements SlashCommand {
5-
name = 'ping';
6-
description = "Check the bot's latency";
5+
name = "ping";
6+
description = "Checks the bot's latency.";
77
subcommands = [];
88
parameters = [];
9-
dev = true;
9+
dev = true;
1010
kogBot: KOGBot;
1111

1212
constructor(kogBot: KOGBot) {
1313
this.kogBot = kogBot;
1414
}
1515

1616
async execute(interaction: ChatInputCommandInteraction): Promise<void> {
17-
const ping = Math.floor(interaction.client.ws.ping);
17+
try {
18+
const sent = await interaction.reply({ content: "Ping!", fetchReply: true });
19+
const timeDiff = (sent.createdTimestamp - interaction.createdTimestamp);
20+
1821

19-
const message = await interaction.reply({
20-
embeds: [
21-
new EmbedBuilder()
22-
.setTitle("Pong!")
23-
.setDescription(`🏓**Client latency** \`${ping}\` ms\n🌐 **Round-trip** \`Calculating...\``)
24-
.setColor(Colors.Blue)
25-
]
26-
});
27-
28-
const round = Math.floor(message.interaction.createdTimestamp - interaction.createdTimestamp);
29-
30-
await interaction.editReply({
31-
embeds: [
32-
new EmbedBuilder()
33-
.setTitle("Pong!")
34-
.setDescription(`🏓**Client latency**: \`${ping}\` ms\n🌐 **Round-trip**: \`${round}\` ms`)
35-
.setColor(Colors.Green)
36-
]
37-
});
22+
await interaction.editReply(`Pong! Latency is ${timeDiff}ms.`);
23+
} catch (error) {
24+
console.error(error);
25+
await interaction.reply("An error occurred while trying to check the latency.");
26+
}
3827
}
3928
}
4029

0 commit comments

Comments
 (0)