Skip to content

Commit

Permalink
add: levels
Browse files Browse the repository at this point in the history
  • Loading branch information
maamokun committed Aug 12, 2024
1 parent dbdf88e commit 9073dc6
Show file tree
Hide file tree
Showing 15 changed files with 152 additions and 78 deletions.
17 changes: 0 additions & 17 deletions prisma/migrations/20240624082848_new/migration.sql

This file was deleted.

8 changes: 0 additions & 8 deletions prisma/migrations/20240624083257_new2/migration.sql

This file was deleted.

8 changes: 0 additions & 8 deletions prisma/migrations/20240624084700_new3/migration.sql

This file was deleted.

10 changes: 0 additions & 10 deletions prisma/migrations/20240625124929_mew4/migration.sql

This file was deleted.

3 changes: 0 additions & 3 deletions prisma/migrations/20240625125401_new5/migration.sql

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,22 @@ CREATE TABLE "User" (
"id" TEXT NOT NULL,
"premium" BOOLEAN NOT NULL DEFAULT false,
"premiumUntil" TIMESTAMP(3),
"levelCard" TEXT NOT NULL,
"rankColor" TEXT NOT NULL,
"mdUID" TEXT NOT NULL,

CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "guildLvl" (
"id" TEXT NOT NULL,
"level" TEXT NOT NULL,
"xp" TEXT NOT NULL,

CONSTRAINT "guildLvl_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "server" (
"id" TEXT NOT NULL,
Expand All @@ -20,6 +32,8 @@ CREATE TABLE "server" (
"autoRoleChannel" TEXT NOT NULL,
"verificationRole" TEXT NOT NULL,
"verificationChannel" TEXT NOT NULL,
"levelsEnabled" BOOLEAN NOT NULL,
"levelsMessage" TEXT NOT NULL,

CONSTRAINT "server_pkey" PRIMARY KEY ("id")
);
4 changes: 4 additions & 0 deletions prisma/migrations/20240812135218_defaults/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- AlterTable
ALTER TABLE "User" ALTER COLUMN "levelCard" SET DEFAULT 'https://cdn.mikn.dev/mikan-bg.png',
ALTER COLUMN "rankColor" SET DEFAULT '#FF7700',
ALTER COLUMN "mdUID" SET DEFAULT 'unlinked';
12 changes: 12 additions & 0 deletions prisma/migrations/20240812140433_numberfy/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
Warnings:
- Changed the type of `level` on the `guildLvl` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
- Changed the type of `xp` on the `guildLvl` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
*/
-- AlterTable
ALTER TABLE "guildLvl" DROP COLUMN "level",
ADD COLUMN "level" INTEGER NOT NULL,
DROP COLUMN "xp",
ADD COLUMN "xp" INTEGER NOT NULL;
2 changes: 2 additions & 0 deletions prisma/migrations/20240812141624_cooldown/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "guildLvl" ADD COLUMN "cooldown" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
12 changes: 7 additions & 5 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,23 @@ generator client {
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

model User {
id String @id
premium Boolean @default(false)
premiumUntil DateTime?
levelCard String
rankColor String
mdUID String
levelCard String @default("https://cdn.mikn.dev/mikan-bg.png")
rankColor String @default("#FF7700")
mdUID String @default("unlinked")
}

model guildLvl {
id String @id
level String
xp String
level Int
xp Int
cooldown DateTime @default(now())
}

model server {
Expand Down
53 changes: 40 additions & 13 deletions src/api/server.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,51 @@
import { Elysia } from "elysia";
import { dmUser } from "..";

const app = new Elysia();

app.post("/accLink", async ({ query, body }) => {
const key = query.key
const json = body
const key = query.key;
const json = body as { uid: string; acc: string };

const uid = json.uid
const acc = json.acc
const uid = json.uid;
const acc = json.acc;

if(!key) return { status: 400, message: "No key provided" }
if(!uid) return { status: 400, message: "No uid provided" }
if(!acc) return { status: 400, message: "No acc provided" }
if (!key) return new Response("No key provided", { status: 400 });
if (!uid || !acc)
return new Response("Missing uid or account information", {
status: 400,
});

if(key !== process.env.API_SIGNING_KEY) return { status: 401, message: "Invalid key" }
if (key !== process.env.API_SIGNING_KEY)
return new Response("Invalid key", { status: 401 });
});

})
app.post("/dm", async ({ query, body }) => {
const key = query.key;
const json = body as { provider: string; uid: string; message: string };

export function start () {
if (!json) return new Response("No JSON body provided", { status: 400 });

const provider = json.provider;
const uid = json.uid;
const message = json.message;

if (!key) return new Response("No key provided", { status: 400 });
if (key !== process.env.API_SIGNING_KEY)
return new Response("Invalid key", { status: 401 });
if (!provider || !uid || !message)
return new Response("Missing provider, uid, or message", {
status: 400,
});

const response = await dmUser(uid, provider, message);
if (response instanceof Error)
return { status: 500, message: response.message };
return new Response("Message sent", { status: 200 });
});

export function start() {
app.listen(process.env.API_PORT || 3000, () => {
console.log(`Server started on port ${process.env.API_PORT || 3000}`)
})
}
console.log(`Server started on port ${process.env.API_PORT || 3000}`);
});
}
2 changes: 1 addition & 1 deletion src/commands/ping.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CommandInteraction } from "discord.js";
import type { CommandInteraction } from "discord.js";

export default {
name: "ping",
Expand Down
2 changes: 1 addition & 1 deletion src/commands/premping.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CommandInteraction } from "discord.js";
import type { CommandInteraction } from "discord.js";

export default {
name: "premping",
Expand Down
53 changes: 44 additions & 9 deletions src/handlers/lvl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,25 @@ import { PrismaClient } from "@prisma/client";
import type { Message } from "discord.js";

const prisma = new PrismaClient();
const messageLimit = new Map();

const cooldown = 5000;

function getLevelFromXP(xp: number): number {
let level = 1;
let xpRequired = 50; // XP required for level 2
let totalXP = 0;

while (xp >= totalXP + xpRequired) {
totalXP += xpRequired;
xpRequired *= 2; // Double the XP required for the next level
level++;
}

return level;
}

export async function handleLevel(message: Message) {
const lvlDB = prisma.guildLvl.findUnique({
const lvlDB = await prisma.guildLvl.findUnique({
where: {
id: `${message.guild?.id}-${message.author.id}`,
},
Expand All @@ -15,14 +30,34 @@ export async function handleLevel(message: Message) {
await prisma.guildLvl.create({
data: {
id: `${message.guild?.id}-${message.author.id}`,
xp: "0",
level: "0",
xp: 1,
level: 1,
},
});
}

//@ts-ignore
const xp = lvlDB?.xp;
//@ts-ignore
const lvl = lvlDB?.level;
}
const increment = Math.floor(Math.random() * 10) + 15;

if (lvlDB) {
const newXP = lvlDB.xp + increment;
const currentCooldown = lvlDB.cooldown;
if (currentCooldown > new Date()) return;
const cooldownTime = new Date(Date.now() + cooldown);
const level = getLevelFromXP(newXP);
if (lvlDB.level < level) {
message.channel.send(
`Congratulations ${message.author}, you have leveled up to level ${level}!`,
);
}
await prisma.guildLvl.update({
where: {
id: `${message.guild?.id}-${message.author.id}`,
},
data: {
xp: newXP,
level: level,
cooldown: cooldownTime,
},
});
}
}
30 changes: 27 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,34 @@ import { start } from "./api/server";
import { deployCommands } from "./deploy";
import { setPresence } from "./presence";
import { handleCommand } from "./handlers/command";
import { Client, GatewayIntentBits } from "discord.js";
import { handleLevel } from "./handlers/lvl";
import { Client, GatewayIntentBits, EmbedBuilder } from "discord.js";

const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.DirectMessages, GatewayIntentBits.GuildMessages],
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildMessages,
],
});

export async function dmUser(id: string, provider: string, message: string) {
const user = client.users.cache.get(id);
if (!user) return;

const embed = new EmbedBuilder()
.setTitle(`System Message from ${provider}`)
.setDescription(message)
.setColor("#FF7700")
.setTimestamp();

try {
await user.send({ embeds: [embed] });
} catch (e) {
return e;
}
}

client.on("ready", () => {
console.log(`Logged in as ${client.user?.tag}!`);
deployCommands();
Expand All @@ -22,9 +45,10 @@ client.on("interactionCreate", async (interaction) => {
client.on("messageCreate", async (message) => {
if (message.author.bot) return;
console.log("Received message!");
await handleLevel(message);
});

client.on("guildCreate", async (guild) => {});

client.login(process.env.BOT_TOKEN);
start();
start();

0 comments on commit 9073dc6

Please sign in to comment.