This commit is contained in:
moriese 2024-12-30 22:45:41 +01:00
parent 182ce5af6b
commit 8935e141d2
6 changed files with 232 additions and 154 deletions

Binary file not shown.

View File

@ -4,8 +4,13 @@ import { getRandomInt } from "lib/utils";
import { greetContent, sleepContent } from "./greeting.components.ts"; import { greetContent, sleepContent } from "./greeting.components.ts";
export class GreetingService { export class GreetingService {
async greet() { async greet() {
client.user?.setActivity("guten morgen! :3", { type: 4 });
console.log("set activity: awake");
client.user?.setPresence({
status: "online",
});
const channels = client.channels; const channels = client.channels;
const channel = channels.cache.get(config.discord.channelId); const channel = channels.cache.get(config.discord.channelId);
@ -16,6 +21,12 @@ export class GreetingService {
} }
async sleep() { async sleep() {
client.user?.setActivity("zzzzZZ..", { type: 4 });
console.log("set activity: asleep");
client.user?.setPresence({
status: "dnd",
});
const channels = client.channels; const channels = client.channels;
const channel = channels.cache.get(config.discord.channelId); const channel = channels.cache.get(config.discord.channelId);

View File

@ -3,185 +3,248 @@ import { getRandomInt } from "lib/utils";
import config from "config"; import config from "config";
import client from "lib/client"; import client from "lib/client";
import { import {
ActionRowBuilder, ActionRowBuilder,
ButtonBuilder, ButtonBuilder,
ButtonInteraction, type ButtonInteraction,
ButtonStyle, ButtonStyle,
ChatInputCommandInteraction, type ChatInputCommandInteraction,
ModalSubmitInteraction, type ModalSubmitInteraction,
type CacheType, type CacheType,
type Interaction, type Interaction,
} from "discord.js"; } from "discord.js";
import { yesButton, noButton } from "./medication.components"; import { yesButton, noButton } from "./medication.components";
import { db } from "db"; import { db } from "db";
import { usersTable } from "db/schema" import { usersTable } from "db/schema";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
export class MedicationService { export class MedicationService {
medication: string; medication: string;
tookMedication: boolean; tookMedication: boolean;
constructor() { constructor() {
this.medication = ""; this.medication = "";
this.tookMedication = false; this.tookMedication = false;
} }
async askMedication() { async askMedication() {
const channels = client.channels; const channels = client.channels;
const channel = channels.cache.get(config.discord.channelId); const channel = channels.cache.get(config.discord.channelId);
// funkt noch nicht, beides // funkt noch nicht, beides
const row = new ActionRowBuilder().addComponents(yesButton); const row = new ActionRowBuilder().addComponents(yesButton);
row.addComponents(noButton); row.addComponents(noButton);
if (channel?.isTextBased && if (
channel?.isSendable() && channel?.isTextBased &&
this.tookMedication == false) { channel?.isSendable() &&
await channel.send({ content: "hast du schon deine medis genommen? :)", components: [row as any] }); this.tookMedication === false
} ) {
await channel.send({
content: "hast du schon deine medis genommen? :)",
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
components: [row as any],
});
}
}
} getMedication() {
throw new Error("Method not implemented.");
}
getMedication() { setMedication() {
throw new Error("Method not implemented."); const reply = this.getReply();
} console.log("medication");
setMedication() { // this.medication = input von user:in hier rein;
const reply = this.getReply(); return {
console.log("medication"); reply,
};
}
// this.medication = input von user:in hier rein; getReply() {
return { return "medication reminder";
reply, }
}
}
getReply() { async handleInteraction(interaction: Interaction<CacheType>) {
return "medication reminder"; if (interaction.isModalSubmit()) {
} await this.handleModalSubmit(interaction);
return;
}
async handleInteraction(interaction: Interaction<CacheType>) { if (interaction.isChatInputCommand()) {
if (interaction.isModalSubmit()) { await this.handleChatInputCommand(interaction);
await this.handleModalSubmit(interaction); return;
return; }
} if (interaction.isButton()) {
await this.handleButton(interaction);
return;
}
}
if (interaction.isChatInputCommand()) { async handleModalSubmit(interaction: ModalSubmitInteraction<CacheType>) {
await this.handleChatInputCommand(interaction); switch (interaction.customId) {
return; default:
} break;
if (interaction.isButton()) { }
await this.handleButton(interaction); }
return;
}
}
async handleModalSubmit(interaction: ModalSubmitInteraction<CacheType>) { async handleButton(interaction: ButtonInteraction<CacheType>) {
switch (interaction.customId) { console.log("button interaction");
default:
break;
}
}
async handleButton(interaction: ButtonInteraction<CacheType>) { const discordId = Number.parseInt(interaction.user.id);
console.log("button interaction"); const name = interaction.user.displayName;
const result = this.setMedication(); console.log(`userid: ${discordId}`);
const discordId = parseInt(interaction.user.id);
const id = this.getIdByDiscordId(discordId);
console.log("userid: " + discordId);
try {
const userId = await this.ensureUserExists(discordId, name);
console.log(`userid: ${userId}`);
switch (interaction.customId) { const tookMedication = interaction.customId === "yesMedication";
case "yesMedication":
interaction.reply({
content: "das hast du toll gemacht <3 mach weiter so :3",
});
return;
case "noMedication":
interaction.reply({
content: "das passiert mal... aber versuch sie heute noch zu nehmen, oki? :)",
});
return;
default:
break;
}
}
async handleChatInputCommand(interaction: ChatInputCommandInteraction<CacheType>) { interaction.reply({
const result = this.setMedication(); content: tookMedication
? "das hast du toll gemacht <3 mach weiter so :3"
: "das passiert mal... aber versuch sie heute noch zu nehmen, oki? :)",
});
await this.logMedication(userId, tookMedication);
} catch (error) {
console.error("error ensuring user exists:", error);
await interaction.reply({
content:
"es gab einen fehler beim verarbeiten deiner anfrage :( versuch es bitte spaeter nochmal, oki? c:",
});
return;
}
}
const row = new ActionRowBuilder().addComponents(yesButton); async handleChatInputCommand(
row.addComponents(noButton); interaction: ChatInputCommandInteraction<CacheType>,
await interaction.reply({ ) {
content: result.reply, const result = this.setMedication();
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
components: [row as any],
});
} const row = new ActionRowBuilder().addComponents(yesButton);
row.addComponents(noButton);
await interaction.reply({
content: result.reply,
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
components: [row as any],
});
}
/** /**
* Methode, um die Benutzerdaten in die Datenbank zu schreiben. * Methode, um die Benutzerdaten in die Datenbank zu schreiben.
* @param discordId unique user id * @param discordId unique user id
* @param name name how the user wants to get called by avocadi * @param name name how the user wants to get called by avocadi
* @param tookMedication if user took medication * @param tookMedication if user took medication
*/ */
async logMedication(discordId: string, name: string, tookMedication: boolean) { async logMedication(id: number, tookMedication: boolean) {
try { try {
// Versuche, den Benutzer zu speichern oder zu aktualisieren await db
await db.insert(usersTable).values({ .update(usersTable)
name: name, .set({
discord_id: parseInt(discordId), took_medication_today: Number(tookMedication),
took_medication_today: Number(tookMedication), })
}); .where(eq(usersTable.id, id));
console.log( /* await db.insert(usersTable).values({
`Benutzer mit ID ${discordId} wurde in der Datenbank gespeichert.` name: name,
); discord_id: discordId,
} catch (error) { took_medication_today: Number(tookMedication),
console.error("Fehler beim Speichern in der Datenbank:", error); }); */
}
}
async getNameByDiscordId(discordId: number): Promise<string | null> { console.log(`Benutzer mit ID ${id} wurde in der Datenbank gespeichert.`);
const result = await db } catch (error) {
.select({ console.error("Fehler beim Speichern in der Datenbank:", error);
name: usersTable.name, }
}) }
.from(usersTable)
.where(eq(usersTable.discord_id, discordId))
.limit(1);
if (result.length > 0) { async getNameByDiscordId(discordId: number): Promise<string | null> {
console.log("user found"); const result = await db
return result[0].name; .select({
} else { name: usersTable.name,
console.log("name not found"); })
return ""; .from(usersTable)
} .where(eq(usersTable.discord_id, discordId))
} .limit(1);
async getIdByDiscordId(discordId: number): Promise<number | null> { if (result.length > 0) {
const result = await db console.log("user found");
.select({ return result[0].name;
id: usersTable.id, }
}) console.log("name not found");
.from(usersTable) return "";
.where(eq(usersTable.discord_id, discordId)) }
.limit(1);
if (result.length > 0) { async findUserIdByDiscordId(discordId: number): Promise<number | null> {
console.log("id found"); try {
return result[0].id; const result = await db
} else { .select({
console.log("id not found"); id: usersTable.id,
return null; })
} .from(usersTable)
} .where(eq(usersTable.discord_id, discordId))
.limit(1);
async newEntry(discordId: number) { if (result.length > 0) {
} console.log(`ID für Discord-ID ${discordId} gefunden: ${result[0].id}`);
} return result[0].id;
}
console.log(`Keine ID für Discord-ID ${discordId} gefunden.`);
return null;
} catch (error) {
console.error(
`Fehler beim Abrufen der ID für Discord-ID ${discordId}:`,
error,
);
return null;
}
}
async ensureUserExists(discordId: number, name: string): Promise<number> {
try {
const userId = await this.findUserIdByDiscordId(discordId);
if (userId !== null) {
console.log(`entry for discordID ${discordId} already exists`);
return userId;
}
console.log(
`found no entry for discordID ${discordId}. creating new entry.`,
);
const result = await db
.insert(usersTable)
.values({
name: name,
discord_id: discordId,
})
.onConflictDoNothing()
.returning({
id: usersTable.id,
});
if (result.length > 0) {
const newUserId = result[0].id;
console.log(
`new user with discordId ${discordId} and name ${name} created. id: ${newUserId}`,
);
return newUserId;
}
// check again if user is now existing
const newUserId = await this.findUserIdByDiscordId(discordId);
if (newUserId !== null) {
console.log(`user created in parallel. fetched id: ${newUserId}`);
return newUserId;
}
throw new Error(`creating a new user for discordId ${discordId} failed`);
} catch (error) {
console.error("error while creating or calling the user:", error);
throw error;
}
}
}

View File

@ -4,7 +4,7 @@ import { WaterMeService } from "actions/waterMe/waterMe.service";
const waterMeService = new WaterMeService(); const waterMeService = new WaterMeService();
new CronJob( new CronJob(
"0 0 0 */1 * *", // cronTime "0 * * * * *", // cronTime
async () => { async () => {
console.log("isThirsty()"); console.log("isThirsty()");
await waterMeService.isThirsty(); await waterMeService.isThirsty();

View File

@ -25,7 +25,11 @@ export default class DiscordController extends EventEmitter {
this.medicationService = new MedicationService(); this.medicationService = new MedicationService();
// log when running // log when running
client.once("ready", async () => { client.once("ready", async () => {
console.log("hello :)"); client.user?.setActivity("HALLOOO HOERT IHR MICH?", { type: 4 });
console.log("set activity");
client.user?.setPresence({
status: "idle",
});
/*const channels = client.channels; /*const channels = client.channels;
const channel = channels.cache.get(config.discord.channelId); const channel = channels.cache.get(config.discord.channelId);
@ -36,6 +40,7 @@ export default class DiscordController extends EventEmitter {
}); });
}*/ }*/
}); });
// listen for interactions // listen for interactions
client.on("interactionCreate", this.handleInteraction.bind(this)); client.on("interactionCreate", this.handleInteraction.bind(this));
} }

View File

@ -1,10 +1,10 @@
import "actions/waterMe/waterMe.task"; import "actions/waterMe/waterMe.task";
import "actions/greeting/greeting.task"; import "actions/greeting/greeting.task";
import "actions/medication/medication.task" import "actions/medication/medication.task";
import "actions/drink/drink.task"; import "actions/drink/drink.task";
import DiscordController from "controllers/discord.controller"; import DiscordController from "controllers/discord.controller";
import 'dotenv/config'; import "dotenv/config";
/*import { drizzle } from 'drizzle-orm/bun-sqlite'; /*import { drizzle } from 'drizzle-orm/bun-sqlite';
import { eq } from 'drizzle-orm'; import { eq } from 'drizzle-orm';
import { usersTable } from './db/schema'; import { usersTable } from './db/schema';
@ -49,6 +49,5 @@ main();*/
// = main file // = main file
// bootstrap application // bootstrap application
const discordController = new DiscordController(); const discordController = new DiscordController();
discordController.init(); discordController.init();