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";
export class GreetingService {
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 channel = channels.cache.get(config.discord.channelId);
@ -16,6 +21,12 @@ export class GreetingService {
}
async sleep() {
client.user?.setActivity("zzzzZZ..", { type: 4 });
console.log("set activity: asleep");
client.user?.setPresence({
status: "dnd",
});
const channels = client.channels;
const channel = channels.cache.get(config.discord.channelId);

View File

@ -5,16 +5,16 @@ import client from "lib/client";
import {
ActionRowBuilder,
ButtonBuilder,
ButtonInteraction,
type ButtonInteraction,
ButtonStyle,
ChatInputCommandInteraction,
ModalSubmitInteraction,
type ChatInputCommandInteraction,
type ModalSubmitInteraction,
type CacheType,
type Interaction,
} from "discord.js";
import { yesButton, noButton } from "./medication.components";
import { db } from "db";
import { usersTable } from "db/schema"
import { usersTable } from "db/schema";
import { eq } from "drizzle-orm";
export class MedicationService {
@ -36,12 +36,17 @@ export class MedicationService {
const row = new ActionRowBuilder().addComponents(yesButton);
row.addComponents(noButton);
if (channel?.isTextBased &&
if (
channel?.isTextBased &&
channel?.isSendable() &&
this.tookMedication == false) {
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() {
@ -55,7 +60,7 @@ export class MedicationService {
// this.medication = input von user:in hier rein;
return {
reply,
}
};
}
getReply() {
@ -88,29 +93,36 @@ export class MedicationService {
async handleButton(interaction: ButtonInteraction<CacheType>) {
console.log("button interaction");
const result = this.setMedication();
const discordId = parseInt(interaction.user.id);
const id = this.getIdByDiscordId(discordId);
console.log("userid: " + discordId);
const discordId = Number.parseInt(interaction.user.id);
const name = interaction.user.displayName;
console.log(`userid: ${discordId}`);
try {
const userId = await this.ensureUserExists(discordId, name);
console.log(`userid: ${userId}`);
const tookMedication = interaction.customId === "yesMedication";
switch (interaction.customId) {
case "yesMedication":
interaction.reply({
content: "das hast du toll gemacht <3 mach weiter so :3",
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;
case "noMedication":
interaction.reply({
content: "das passiert mal... aber versuch sie heute noch zu nehmen, oki? :)",
});
return;
default:
break;
}
}
async handleChatInputCommand(interaction: ChatInputCommandInteraction<CacheType>) {
async handleChatInputCommand(
interaction: ChatInputCommandInteraction<CacheType>,
) {
const result = this.setMedication();
const row = new ActionRowBuilder().addComponents(yesButton);
@ -120,7 +132,6 @@ export class MedicationService {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
components: [row as any],
});
}
/**
@ -129,18 +140,22 @@ export class MedicationService {
* @param name name how the user wants to get called by avocadi
* @param tookMedication if user took medication
*/
async logMedication(discordId: string, name: string, tookMedication: boolean) {
async logMedication(id: number, tookMedication: boolean) {
try {
// Versuche, den Benutzer zu speichern oder zu aktualisieren
await db.insert(usersTable).values({
name: name,
discord_id: parseInt(discordId),
await db
.update(usersTable)
.set({
took_medication_today: Number(tookMedication),
});
})
.where(eq(usersTable.id, id));
console.log(
`Benutzer mit ID ${discordId} wurde in der Datenbank gespeichert.`
);
/* await db.insert(usersTable).values({
name: name,
discord_id: discordId,
took_medication_today: Number(tookMedication),
}); */
console.log(`Benutzer mit ID ${id} wurde in der Datenbank gespeichert.`);
} catch (error) {
console.error("Fehler beim Speichern in der Datenbank:", error);
}
@ -158,13 +173,13 @@ export class MedicationService {
if (result.length > 0) {
console.log("user found");
return result[0].name;
} else {
}
console.log("name not found");
return "";
}
}
async getIdByDiscordId(discordId: number): Promise<number | null> {
async findUserIdByDiscordId(discordId: number): Promise<number | null> {
try {
const result = await db
.select({
id: usersTable.id,
@ -174,14 +189,62 @@ export class MedicationService {
.limit(1);
if (result.length > 0) {
console.log("id found");
console.log(`ID für Discord-ID ${discordId} gefunden: ${result[0].id}`);
return result[0].id;
} else {
console.log("id not found");
}
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 newEntry(discordId: number) {
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();
new CronJob(
"0 0 0 */1 * *", // cronTime
"0 * * * * *", // cronTime
async () => {
console.log("isThirsty()");
await waterMeService.isThirsty();

View File

@ -25,7 +25,11 @@ export default class DiscordController extends EventEmitter {
this.medicationService = new MedicationService();
// log when running
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 channel = channels.cache.get(config.discord.channelId);
@ -36,6 +40,7 @@ export default class DiscordController extends EventEmitter {
});
}*/
});
// listen for interactions
client.on("interactionCreate", this.handleInteraction.bind(this));
}

View File

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