This commit is contained in:
cirroskais 2024-02-12 02:43:32 -05:00
commit a43b20180f
37 changed files with 865 additions and 0 deletions

1
.env.example Normal file
View file

@ -0,0 +1 @@
TOKEN=

177
.gitignore vendored Normal file
View file

@ -0,0 +1,177 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Caches
.cache
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store
data

15
README.md Normal file
View file

@ -0,0 +1,15 @@
# bun-terry
To install dependencies:
```bash
bun install
```
To run:
```bash
bun run src/index.js
```
This project was created using `bun init` in bun v1.0.26. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

19
bin/delete.js Normal file
View file

@ -0,0 +1,19 @@
import { logger } from "@discordeno/utils"
import REST from "../src/lib/handlers/RESTHandler"
import CommandHandler from "../src/lib/handlers/CommandHandler"
const SlashCommandHandler = new CommandHandler()
const commands = await SlashCommandHandler.load()
const registered = await REST.getGlobalApplicationCommands()
for (let { id, name, type } of registered) {
const cmd = commands.get(name)
if (cmd && cmd.type == type) continue
await REST.deleteGlobalApplicationCommand(id)
console.log(`Deleted ${name}(${id})`)
}
process.exit()

21
bin/list.js Normal file
View file

@ -0,0 +1,21 @@
import { logger } from "@discordeno/utils"
import REST from "../src/lib/handlers/RESTHandler"
import CommandHandler from "../src/lib/handlers/CommandHandler"
const TYPES = ["CHAT_INPUT", "USER", "MESSAGE"]
const SlashCommandHandler = new CommandHandler()
const registered = await REST.getGlobalApplicationCommands()
console.log("┌" + "-".repeat(58) + "┐")
console.log("| " + "ID".padEnd(24, " ") + " | " + "NAME".padEnd(16, " ") + " | " + "TYPE".padEnd(10, " ") + " |")
console.log("├" + "-".repeat(58) + "┤")
for (let { id, name, type } of registered) {
console.log("| " + id.padEnd(24, " ") + " | " + name.padEnd(16, " ") + " | " + TYPES[type - 1].padEnd(10, " ") + " |")
}
console.log("└" + "-".repeat(58) + "┘")
process.exit()

21
bin/update.js Normal file
View file

@ -0,0 +1,21 @@
import { logger } from "@discordeno/utils"
import REST from "../src/lib/handlers/RESTHandler"
import CommandHandler from "../src/lib/handlers/CommandHandler"
const SlashCommandHandler = new CommandHandler()
const commands = await SlashCommandHandler.load()
for (let [key, value] of commands.entries()) {
const command = await REST.createGlobalApplicationCommand({
name: key,
type: value.type,
description: value?.description || "",
options: value?.options,
nsfw: value?.nsfw,
}).catch((e) => console.log(e))
console.log(`Registered ${command.name}(${command.id})`)
}
process.exit()

BIN
bun.lockb Executable file

Binary file not shown.

22
jsconfig.json Normal file
View file

@ -0,0 +1,22 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
/* Linting */
"skipLibCheck": true,
"strict": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true
}
}

24
package.json Normal file
View file

@ -0,0 +1,24 @@
{
"name": "bun-terry",
"module": "src/index.js",
"devDependencies": {
"@types/bun": "latest",
"@discordeno/types": "^19.0.0-next.d81b28a"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"scripts": {
"dev": "NODE_ENV=development bun --watch ./src/index.js",
"start": "bun ./src/index.js",
"bot:delete": "bun ./bin/delete.js",
"bot:update": "bun ./bin/update.js",
"bot:list": "bun ./bin/list.js"
},
"type": "module",
"dependencies": {
"@discordeno/bot": "^19.0.0-next.d81b28a",
"@discordeno/rest": "^19.0.0-next.d81b28a",
"@discordeno/utils": "^19.0.0-next.d81b28a"
}
}

24
src/commands/changes.js Normal file
View file

@ -0,0 +1,24 @@
import BaseCommand from "../lib/classes/BaseCommand"
import { staged } from "../lib/modpack"
export default class Command extends BaseCommand {
static type = 1
static name = "changes"
static description = "Get staged changes to the modpack"
constructor(data) {
super(data)
}
async run(interaction) {
let text = ""
if (!staged.size) return interaction.respond("No changes to the modpack have been staged.")
for (let [key, value] of staged.entries()) {
text += (value.action == "add" ? "+" : "-") + " " + key + " " + value.url
}
interaction.respond("```diff\n" + text + "\n```")
}
}

56
src/commands/meta.js Normal file
View file

@ -0,0 +1,56 @@
import BaseCommand from "../lib/classes/BaseCommand"
const META_CHOICES = [
{ name: "loader", value: "loader" },
{ name: "minecraft_version", value: "minecraft_version" },
]
export default class Command extends BaseCommand {
static type = 1
static name = "meta"
static description = "Modify modpack metadata"
static options = [
{
type: 1,
name: "set",
description: "Set an attribute",
options: [
{
type: 3,
name: "name",
description: "Attribute name",
required: true,
choices: META_CHOICES,
},
{
type: 3,
name: "value",
description: "Attribute value",
required: true,
},
],
},
{
type: 1,
name: "get",
description: "Get an attribute",
options: [
{
type: 3,
name: "name",
description: "Attribute name",
required: true,
choices: META_CHOICES,
},
],
},
]
constructor(data) {
super(data)
}
async run(interaction) {
console.log("meta.js")
}
}

77
src/commands/mod.js Normal file
View file

@ -0,0 +1,77 @@
import { ButtonStyles, InteractionResponseTypes } from "@discordeno/types"
import BaseCommand from "../lib/classes/BaseCommand"
import * as curseforge from "../lib/curseforge"
import REST from "../lib/handlers/RESTHandler"
export default class Command extends BaseCommand {
static type = 1
static name = "mod"
static description = "Get information about a mod"
static options = [
{
type: 3,
name: "url",
description: "A link to a Modrinth/Curseforge mod",
required: true,
},
]
constructor(data) {
super(data)
}
async run(interaction) {
const { data } = interaction
const url = data.options.find((_) => _.name == "url").value
const parsedUrl = new URL(url)
if (parsedUrl.host.includes("curseforge.com")) {
const mod = await curseforge.getMod(url)
if (!mod) return interaction.respond("Mod not found.")
const file = await curseforge.getModFiles(mod.id)
const customId = new URLSearchParams()
customId.append("name", "addMod")
customId.append("modId", mod.id)
customId.append("fileId", file.id)
customId.append("provider", "curseforge")
return await REST.sendInteractionResponse(interaction.id, interaction.token, {
type: InteractionResponseTypes.ChannelMessageWithSource,
data: {
embeds: [
{
title: mod.name,
description: mod.summary,
url: mod.links.websiteUrl,
thumbnail: { url: mod.logo.url },
footer: { text: `Curseforge | ModId ${mod.id} | FileId ${file.id}` },
},
],
components: [
{
type: 1,
components: [
{
type: 2,
style: ButtonStyles.Primary,
label: "Add to Modpack",
customId: customId.toString(),
},
{
type: 2,
style: ButtonStyles.Link,
label: "Download",
url: file.downloadUrl,
},
],
},
],
},
})
} else if (parsedUrl.host.includes("modrinth.com")) {
console.log("Modrinth mod detected")
}
}
}

49
src/commands/modify.js Normal file
View file

@ -0,0 +1,49 @@
import BaseCommand from "../lib/classes/BaseCommand"
export default class Command extends BaseCommand {
static type = 1
static name = "modify"
static description = "Modify the modpack"
static options = [
{
type: 1,
name: "add",
description: "Add a mod",
options: [
{
type: 3,
name: "url",
description: "A link to a Modrinth/Curseforge mod",
required: true,
},
],
},
{
type: 1,
name: "remove",
description: "Remove a mod",
options: [
{
type: 3,
name: "name",
description: "The name of the mod",
autocomplete: true,
required: true,
},
{
type: 5,
name: "from_modpack",
description: "Toggle removal from staging or the modpack",
},
],
},
]
constructor(data) {
super(data)
}
async run(interaction) {
console.log("modify.js")
}
}

21
src/commands/ping.js Normal file
View file

@ -0,0 +1,21 @@
import BaseCommand from "../lib/classes/BaseCommand"
export default class Command extends BaseCommand {
static type = 1
static name = "ping"
static description = "A test command that responds with the gateway latency"
constructor(data) {
super(data)
}
async run(interaction) {
const { data } = interaction
const then = Date.now()
await interaction.respond("Pinging...")
const ping = Date.now() - then
return interaction.edit(`${ping}ms`)
}
}

15
src/commands/publish.js Normal file
View file

@ -0,0 +1,15 @@
import BaseCommand from "../lib/classes/BaseCommand"
export default class Command extends BaseCommand {
static type = 1
static name = "publish"
static description = "Publish the changes from staging"
constructor(data) {
super(data)
}
async run(interaction) {
console.log("publish.js")
}
}

36
src/components/addMod.js Normal file
View file

@ -0,0 +1,36 @@
import { InteractionResponseTypes } from "@discordeno/types"
import * as curseforge from "../lib/curseforge"
import REST from "../lib/handlers/RESTHandler"
import { staged } from "../lib/modpack"
import { cache } from "../lib/cache"
export default class Command {
static name = "addMod"
constructor(data) {}
async run(interaction) {
const params = new URLSearchParams(interaction.data.customId)
const modId = params.get("modId")
const fileId = params.get("fileId")
const provider = params.get("provider")
if (provider == "curseforge") {
const mod = await curseforge.getModFromId(modId)
if (staged.get(mod.data.name)) return interaction.respond(`**${mod.data.name}** is already in the modpack.`, { isPrivate: true })
staged.set(mod.data.name, {
modId,
fileId,
provider,
url: mod.data.links.websiteUrl,
action: "add",
})
interaction.respond(`Added **${mod.data.name}** to the modpack.`)
} else {
interaction.respond("Not implemented for provider " + provider)
}
}
}

33
src/discord.js Normal file
View file

@ -0,0 +1,33 @@
import { createBot, Intents, logger } from "@discordeno/bot"
import EventHandler from "./lib/handlers/EventHandler"
export default async function discord() {
const client = createBot({
token: import.meta.env.DISCORD_TOKEN,
// intents: [],
})
client.events = await new EventHandler(client).load()
client.transformers.desiredProperties.message.content = true
client.transformers.desiredProperties.message.author = true
client.transformers.desiredProperties.user.id = true
client.transformers.desiredProperties.user.username = true
client.transformers.desiredProperties.user.avatar = true
client.transformers.desiredProperties.member.user = true
client.transformers.desiredProperties.member.roles = true
client.transformers.desiredProperties.member.permissions = true
client.transformers.desiredProperties.interaction.id = true
client.transformers.desiredProperties.interaction.type = true
client.transformers.desiredProperties.interaction.data = true
client.transformers.desiredProperties.interaction.token = true
client.transformers.desiredProperties.interaction.guildId = true
client.transformers.desiredProperties.interaction.channelId = true
client.transformers.desiredProperties.interaction.member = true
client.start()
}

View file

@ -0,0 +1,19 @@
import { logger } from "@discordeno/utils"
import CommandHandler from "../lib/handlers/CommandHandler"
import ComponentHandler from "../lib/handlers/ComponentHandler"
const Commands = new CommandHandler()
await Commands.load((cmd) => {
console.log("Loaded command " + cmd.name)
})
const Components = new ComponentHandler()
await Components.load((comp) => {
console.log("Loaded component response " + comp.name)
})
export default async function (client, interaction) {
if (interaction.type == 2) Commands.check(client, interaction)
if (interaction.type == 3) Components.check(client, interaction)
}

5
src/events/ready.js Normal file
View file

@ -0,0 +1,5 @@
import { logger } from "@discordeno/utils"
export default async function (client, payload) {
console.log(`Logged into ${payload.user.username} on shard ${payload.shardId}`)
}

8
src/index.js Normal file
View file

@ -0,0 +1,8 @@
import discord from "./discord"
import server from "./server"
discord()
server()
process.on("SIGINT", process.exit)
process.on("SIGTERM", process.exit)

2
src/lib/cache.js Normal file
View file

@ -0,0 +1,2 @@
//lol
export const cache = new Map()

View file

@ -0,0 +1,8 @@
import CommandResponse from "./CommandResponse"
export default class BaseCommand extends CommandResponse {
constructor(data) {
super(data)
this.client = data?.client
}
}

View file

@ -0,0 +1 @@
export default class CommandResponse {}

1
src/lib/classes/Embed.js Normal file
View file

@ -0,0 +1 @@
export default class Embed {}

52
src/lib/curseforge.js Normal file
View file

@ -0,0 +1,52 @@
const BASE_URL = "https://api.curseforge.com"
const SEARCH_MODS = "/v1/mods/search"
const GET_FILES = "/v1/mods/{modId}/files"
const GET_MOD = "/v1/mods/{modId}"
const GAME_ID = 432
export async function getMod(url, gameVersion = "1.18.2", modLoaderType = 1) {
url = url.split("/")
const slug = url[url.length - 1]
const query = new URLSearchParams()
query.append("gameId", GAME_ID)
query.append("slug", slug)
query.append("pageSize", 1)
if (gameVersion) query.append("gameVersion", gameVersion)
if (modLoaderType) query.append("modLoaderType", modLoaderType)
const response = await fetch(BASE_URL + SEARCH_MODS + "?" + query.toString(), {
headers: {
"x-api-key": import.meta.env.CURSEFORGE_API,
},
}).catch((e) => console.log(e))
return (await response.json()).data[0]
}
export async function getModFromId(modId) {
const response = await fetch(BASE_URL + GET_MOD.replace("{modId}", modId), {
headers: {
"x-api-key": import.meta.env.CURSEFORGE_API,
},
}).catch((e) => console.log(e))
return await response.json()
}
export async function getModFiles(modId, gameVersion = "1.18.2", modLoaderType = 1) {
const query = new URLSearchParams()
if (gameVersion) query.append("gameVersion", gameVersion)
if (modLoaderType) query.append("modLoaderType", modLoaderType)
const response = await fetch(BASE_URL + GET_FILES.replace("{modId}", modId) + "?" + query.toString(), {
headers: {
"x-api-key": import.meta.env.CURSEFORGE_API,
},
}).catch((e) => console.log(e))
return (await response.json()).data[0]
}
export async function downloadMod(id, fileId) {}

10
src/lib/database.js Normal file
View file

@ -0,0 +1,10 @@
import { Database } from "bun:sqlite"
const database = new Database("data/database.sqlite")
database.run(`CREATE TABLE IF NOT EXISTS attributes (key INTEGER PRIMARY KEY, value INTEGER NOT NULL);`)
database.run(`CREATE TABLE IF NOT EXISTS mods (url INTEGER PRIMARY KEY);`)
process.on("exit", () => {
database.close()
})

View file

@ -0,0 +1,40 @@
import { readdir } from "node:fs/promises"
export default class CommandHandler {
constructor() {
this.cache = new Map()
}
async load(postLoad = () => {}) {
const dir = await readdir("src/commands")
for (let file of dir) {
const cmd = (await this.loadCommand(file)).default
this.cache.set(cmd.name, cmd)
postLoad(cmd)
}
return this.cache
}
async loadCommand(path) {
return await import(process.cwd() + "/src/commands/" + path)
}
reloadCommand(name) {}
unloadCommand(name) {}
check(client, data) {
if (data.type !== 2) return false
this.run(client, data)
}
run(client, interaction) {
const cmd = this.cache.get(interaction.data.name)
if (!cmd) return false
const Command = new cmd(client)
return Command.run(interaction)
}
}

View file

@ -0,0 +1,42 @@
import { readdir } from "node:fs/promises"
export default class ComponentHandler {
constructor() {
this.cache = new Map()
}
async load(postLoad = () => {}) {
const dir = await readdir("src/components")
for (let file of dir) {
const cmd = (await this.loadCommand(file)).default
this.cache.set(cmd.name, cmd)
postLoad(cmd)
}
return this.cache
}
async loadCommand(path) {
return await import(process.cwd() + "/src/components/" + path)
}
reloadCommand(name) {}
unloadCommand(name) {}
check(client, data) {
if (data.type !== 3) return false
this.run(client, data)
}
run(client, interaction) {
const params = new URLSearchParams(interaction.data.customId)
const cmd = this.cache.get(params.get("name"))
if (!cmd) return false
const Command = new cmd(client)
return Command.run(interaction)
}
}

View file

@ -0,0 +1,22 @@
import { readdir } from "node:fs/promises"
export default class EventHandler {
constructor(client) {
this.client = client
this.cache = {}
}
async load() {
const dir = await readdir("src/events")
for (let path of dir) {
const cmd = await this.loadEvent(path)
this.cache[path.replace(".js", "")] = cmd.default.bind(null, this.client)
}
return this.cache
}
async loadEvent(path) {
return await import(process.cwd() + "/src/events/" + path)
}
}

View file

@ -0,0 +1,7 @@
import { createRestManager } from "@discordeno/rest"
const REST = createRestManager({
token: import.meta.env.DISCORD_TOKEN,
})
export default REST

9
src/lib/modpack.js Normal file
View file

@ -0,0 +1,9 @@
import * as modrinth from "./modrinth"
import * as curseforge from "./curseforge"
export let staged = new Map()
export let cache = new Map()
export async function publishChanges() {}
export async function getChanges(x, y) {}

3
src/lib/modrinth.js Normal file
View file

@ -0,0 +1,3 @@
export async function getMod(id) {}
export async function downloadMod(id) {}

1
src/routes/getAllMods.js Normal file
View file

@ -0,0 +1 @@
export default async function route(req) {}

1
src/routes/getMod.js Normal file
View file

@ -0,0 +1 @@
export default async function route(req) {}

1
src/routes/getUpdates.js Normal file
View file

@ -0,0 +1 @@
export default async function route(req) {}

1
src/routes/index.js Normal file
View file

@ -0,0 +1 @@
export default async function route(req) {}

21
src/server.js Normal file
View file

@ -0,0 +1,21 @@
import index from "./routes/index"
const ROUTES = {
"/": index,
}
export default async function server() {
const http = Bun.serve({
fetch(req) {
const url = new URL(req.url)
const route = ROUTES[url.pathname]
if (route) return route()
throw new Error(404)
},
error(error) {
return new Response(error)
},
})
console.log(`Listening on ${http.hostname}:${http.port}`)
}