see_leaderboard_bot/index.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-07-01 10:30:52 +00:00
import { getAdvancements } from "./advancementAPI";
import { Client, Events, GatewayIntentBits } from "discord.js";
import { createCanvas, GlobalFonts } from "@napi-rs/canvas";
import config from "./config.json" assert { type: "json" };
GlobalFonts.registerFromPath("minecraft.otf", "Minecraft");
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
async function makeCanvas(): Promise<Buffer> {
const canvas = createCanvas(170, 255);
const ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, 200, 400);
ctx.fillStyle = "white";
ctx.font = "15px Minecraft";
{
const width = ctx.measureText("Advancements").width;
ctx.fillText("Advancements", canvas.width / 2 - width / 2, 15);
}
const advancements = [...(await getAdvancements()).entries()];
advancements.sort((a, b) => b[1] - a[1]);
for (let i = 0; i < Math.min(advancements.length, 15); i++) {
const n = advancements[i];
// render name
const firstOffset = (i + 2) * 15;
ctx.fillText(n[0], 5, firstOffset);
// render number
const secondOffset = ctx.measureText("" + n[1]).width;
ctx.fillStyle = "yellow";
ctx.fillText("" + n[1], canvas.width - secondOffset - 5, firstOffset);
ctx.fillStyle = "white";
}
return canvas.toBuffer("image/png");
}
client.once(Events.ClientReady, async (readyClient) => {
console.log(`DISCORD connected. ${readyClient.user.tag}`);
});
client.on("messageCreate", async (message) => {
if (message.content == ".lb") {
message.channel.send({
files: [await makeCanvas()],
});
}
});
client.login(config.token);