12 Commits
19 changed files with 252 additions and 100 deletions
+2
View File
@@ -13,3 +13,5 @@ dist/
# OS
.DS_Store
Thumbs.db
data.json
+12 -3
View File
@@ -7,11 +7,20 @@ WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile --production
FROM oven/bun:1-alpine AS runner
FROM oven/bun:1-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY tsconfig.json ./
COPY package.json tsconfig.json ./
COPY src ./src
RUN bun run build
FROM oven/bun:1-alpine AS runner
WORKDIR /app
COPY --from=builder /app/dist ./dist
RUN mkdir -p /app/data && chown -R bun:bun /app/data
VOLUME ["/app/data"]
USER bun
CMD ["bun", "src/index.ts"]
CMD ["bun", "dist/index.js"]
+50 -5
View File
@@ -1,15 +1,60 @@
# kaczynski-bot-2.0
To install dependencies:
A Discord bot built with [Bun](https://bun.com).
## Setup
Install dependencies:
```bash
bun install
```
To run:
Create a `.env.development` file with:
```bash
bun run
```
DISCORD_TOKEN=your-bot-token
```
This project was created using `bun init` in bun v1.3.0. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
## Development
```bash
bun run dev
```
## Commands
Commands live in `src/cmd/registry/` and are loaded automatically at startup — drop a file default-exporting a `Command` in that folder to register it, no manual wiring required.
## Data persistence
Bot state (e.g. limbo mode) is persisted to `data/data.json` via `DataService`. That path is gitignored.
## Production build
```bash
bun run build
```
Bundles `src/index.ts` and every file in `src/cmd/registry/` into `dist/`. Run the result with:
```bash
bun dist/index.js
```
## Docker
Build the image:
```bash
docker build -t kaczynski-bot .
```
Run it, mounting a volume so `data/data.json` survives container restarts:
```bash
docker run -d \
-e DISCORD_TOKEN=your-bot-token \
-v kaczynski-bot-data:/app/data \
kaczynski-bot
```
Executable
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
fly secrets import --stage < .env.production
fly deploy
+7 -2
View File
@@ -1,11 +1,16 @@
# fly.toml app configuration file generated for kaczynski-bot-2-0 on 2026-05-16T14:37:01-04:00
# fly.toml app configuration file generated for kaczynski-bot on 2026-08-22T19:58:11-04:00
#
# See https://fly.io/docs/reference/configuration/ for information about how to use this file.
#
app = 'kaczynski-bot-2-0'
app = 'kaczynski-bot'
primary_region = 'iad'
[build]
[[mounts]]
source = 'data'
destination = '/app/data'
[http_service]
internal_port = 8080
force_https = true
+4 -2
View File
@@ -1,12 +1,14 @@
{
"name": "kaczynski-bot-2.0",
"name": "@dominicferrando/kaczynski-bot",
"version": "1.0.0",
"private": true,
"devDependencies": {
"@types/bun": "latest",
"@types/node": "^25.9.5"
},
"scripts": {
"dev": "bun run src/index.ts"
"dev": "bun run src/index.ts",
"build": "bun build ./src/index.ts $(find src/cmd/registry -name \"*.ts\") --target bun --minify --splitting --root src --outdir ./dist"
},
"peerDependencies": {
"typescript": "^5.9.3"
+4 -4
View File
@@ -1,6 +1,6 @@
import type { Message } from "discord.js";
import type { Command } from "../service";
import Chan from "../../util/chan";
import ChanService from "../../services/chan";
import type { Command } from "../../models";
export default {
name: "chan",
@@ -14,11 +14,11 @@ export default {
return;
};
if (Chan.isNsfwBoard(board)) {
if (ChanService.isNsfwBoard(board)) {
await message.reply("Fuck off nigger")
return;
};
await message.reply(await Chan.getMediaLink(board, search));
await message.reply(await ChanService.getMediaLink(board, search));
}
} satisfies Command;
+3 -3
View File
@@ -1,6 +1,6 @@
import type { Message } from "discord.js";
import type { Command } from "../service";
import Chan from "../../util/chan";
import ChanService from "../../services/chan";
import type { Command } from "../../models";
export default {
name: "comfy",
@@ -9,6 +9,6 @@ export default {
execute: async (message: Message) => {
const boards = ["wsg", "wg"];
const board = boards[Math.floor(Math.random() * boards.length)] ?? "wsg";
await message.reply(await Chan.getMediaLink(board, "comfy"));
await message.reply(await ChanService.getMediaLink(board, "comfy"));
}
} satisfies Command;
+39
View File
@@ -0,0 +1,39 @@
import { ChannelType, type Message } from "discord.js";
import type { Command } from "../../models";
import RoleService from "../../services/role";
import DataService from "../../services/data";
const LIMBO_CHANNEL_NAME = "limbo";
export default {
name: "limbo",
description: "Toggles on/off limbo mode. When limbo mode is on, new members will be placed in #limbo. When off, new members will be placed in #chat-and-shitpost.",
usage: ".limbo [on|off]",
execute: async (message: Message) => {
const ogState = RoleService.limboMode;
if (message.content.includes("on"))
RoleService.limboMode = true;
else if (message.content.includes("off"))
RoleService.limboMode = false;
else
RoleService.limboMode = !RoleService.limboMode;
// update system channel
if (RoleService.limboMode) {
if (!ogState)
DataService.data = { ...DataService.data, prevSystemChannelId: message.guild?.systemChannel?.id };
const limboChannel = message.guild?.channels.cache.find((ch) => ch.name.toLowerCase() === LIMBO_CHANNEL_NAME);
if (limboChannel && limboChannel.type === ChannelType.GuildText)
await message.guild?.setSystemChannel(limboChannel);
}
else {
const prevSystemChannel = message.guild?.channels.cache.find((ch) => ch.id === DataService.data.prevSystemChannelId);
if (prevSystemChannel && prevSystemChannel.type === ChannelType.GuildText)
await message.guild?.setSystemChannel(prevSystemChannel);
}
await message.reply(`*${ogState}* -> **${RoleService.limboMode}**`);
}
} satisfies Command;
-10
View File
@@ -1,10 +0,0 @@
import type { Message } from "discord.js";
import type { Command } from "../service";
export default {
name: "limbo",
description: "Toggles on/off limbo mode. When limbo mode is on, new members will be placed in #limbo. When off, new members will be placed in #chat-and-shitpost.",
usage: ".limbo [on|off]",
execute: async (message: Message) => {
}
} satisfies Command;
+1 -1
View File
@@ -1,5 +1,5 @@
import type { Message } from "discord.js";
import type { Command } from "../service";
import type { Command } from "../../models";
export default {
name: "redpillme",
+15
View File
@@ -0,0 +1,15 @@
import type { Message } from "discord.js";
import type { Command } from "../../models";
import RoleService from "../../services/role";
export default {
name: "roleinit",
description: "Creates all of the required roles, if they do not exist yet.",
usage: ".roleinit",
execute: async (message: Message) => {
if (!message.guild) return;
const reply = await message.reply("Initializing roles...");
await RoleService.createRolesIfNotExist(message.guild, Object.values(RoleService.ROLES));
await reply.edit("Finished initializing roles.");
}
} satisfies Command;
-34
View File
@@ -1,34 +0,0 @@
import type { Client, Message } from "discord.js";
import { readdir } from "fs/promises";
const CMD_PREFIX = ".";
export interface Command {
name: string,
description: string,
usage: string,
execute: (message: Message) => void | Promise<void>
}
export class CommandService {
private client: Client
private registry: Record<string, Command> = {}
constructor(client: Client) {
this.client = client;
}
async init() {
const commands = await Promise.all(
(await readdir(`${import.meta.dir}/registry`)).map(async file => (await import(`./registry/${file}`)).default as Command)
);
for (const command of commands)
this.registry[command.name] = command;
};
parse(message: Message): Command | undefined {
if (!message.content.startsWith(CMD_PREFIX)) return;
const name = message.content.slice(CMD_PREFIX.length).split(/\s+/)[0];
return this.registry[name ?? ""];
}
}
+18 -13
View File
@@ -1,36 +1,41 @@
import { Client, Events, GatewayIntentBits } from 'discord.js';
import { CommandService } from './cmd/service';
import RoleService from './services/role';
import CommandService from './services/command';
import DataService from './services/data';
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
// Services
const commandService = new CommandService(client);
const roleService = new RoleService(client);
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});
client.once(Events.ClientReady, async (readyClient) => {
// Initialize & validate
await commandService.init();
roleService.validate(client.guilds.cache);
// Initialize services
await DataService.init();
await CommandService.init();
await RoleService.init(client.guilds.cache);
// Ready!
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
client.on("guildMemberAdd", async (guildMember) => {
await roleService.giveStarterRoles(guildMember);
await RoleService.giveStarterRoles(guildMember);
});
client.on("messageCreate", async (message) => {
if (message.author.bot) return;
const command = commandService.parse(message);
if (command) command.execute(message);
try {
const command = CommandService.parse(message);
if (command) await command.execute(message);
}
catch (err) {
console.error(err);
}
});
Bun.cron("0 */6 * * *", async () => {
for (const guild of client.guilds.cache.values()) {
const lurkerRole = roleService.getRoleByName(guild, RoleService.ROLES["LURKER"]?.name);
const lurkerRole = RoleService.getRoleByName(guild, RoleService.ROLES["LURKER"]?.name);
if (!lurkerRole) continue;
await guild.members.prune({ days: 5, roles: [lurkerRole] });
+10
View File
@@ -0,0 +1,10 @@
import type { Message } from "discord.js";
// COMMANDS
export interface Command {
name: string,
description: string,
usage: string,
execute: (message: Message) => void | Promise<void>
}
+1 -1
View File
@@ -1,4 +1,4 @@
export default class Chan {
export default abstract class ChanService {
private static readonly nsfwBoards = new Set([
"b", "d", "e", "h", "hc", "hr", "gif", "s", "t", "u", "r9k", "soc", "vr", "w",
"i", "ic", "r", "p", "cgl", "cm", "n", "vip", "qa", "y", "trash", "hm", "aco", "lgbt"
+25
View File
@@ -0,0 +1,25 @@
import type { Message } from "discord.js";
import { readdir } from "fs/promises";
import { dirname } from "path";
import type { Command } from "../models";
const CMD_PREFIX = ".";
const CMD_REGISTRY_DIR = `${dirname(Bun.main)}/cmd/registry`;
export default abstract class CommandService {
private static registry: Record<string, Command> = {}
static async init() {
const commands = await Promise.all(
(await readdir(CMD_REGISTRY_DIR)).map(async file => (await import(`${CMD_REGISTRY_DIR}/${file}`)).default satisfies Command)
);
for (const command of commands)
CommandService.registry[command.name] = command;
};
static parse(message: Message): Command | undefined {
if (!message.content.startsWith(CMD_PREFIX)) return;
const name = message.content.slice(CMD_PREFIX.length).split(/\s+/)[0];
return this.registry[name ?? ""];
}
}
+33
View File
@@ -0,0 +1,33 @@
interface Data {
limboMode: boolean,
prevSystemChannelId?: string
}
export default class DataService {
private static readonly DATA_PATH = "./data/data.json";
private static file: Bun.BunFile | undefined;
private static _data: Data = {
// default values (will be overwritten)
limboMode: false,
prevSystemChannelId: undefined
};
static async init() {
if (!(await Bun.file(this.DATA_PATH).exists()))
await Bun.write(Bun.file(this.DATA_PATH), JSON.stringify(this._data, null, 2));
this.file = Bun.file(this.DATA_PATH);
this._data = { ...this._data, ...(await this.file.json()) };
}
static set data(data: Data) {
if (!this.file) throw new Error("DataService is not initialized. Please call DataService.init()");
this._data = data;
void Bun.write(this.file, JSON.stringify(this._data, null, 2));
}
static get data() {
if (!this.file) throw new Error("DataService is not initialized. Please call DataService.init()");
return this._data
}
}
+21 -22
View File
@@ -1,81 +1,74 @@
import type { Client, Guild, GuildMember, Collection, RoleCreateOptions } from "discord.js";
import type { Guild, GuildMember, Collection, RoleCreateOptions } from "discord.js";
import DataService from "./data";
export default class RoleService {
static readonly ROLES: Record<string, RoleCreateOptions> = {
export default abstract class RoleService {
static readonly ROLES = {
// Main
"ROBOT": {
name: "robot",
colors: { primaryColor: "#58a9df" },
hoist: true,
mentionable: true,
position: 1,
},
"FEMOID": {
name: "femoid",
colors: { primaryColor: "#ffb2f4" },
hoist: true,
mentionable: true,
position: 2,
},
"NORMALFAG": {
name: "normalfag",
colors: { primaryColor: "#e26254" },
hoist: true,
mentionable: true,
position: 3,
},
"GAY": {
name: "gay",
colors: { primaryColor: "#71368a" },
hoist: true,
mentionable: true,
position: 4,
},
"TROID": {
name: "troid",
colors: { primaryColor: "#992d22" },
hoist: true,
mentionable: true,
position: 5,
},
"LURKER": {
name: "lurker",
colors: { primaryColor: "#546e7a" },
hoist: true,
mentionable: true,
position: 6,
},
// Utility
"NEWFAG": {
name: "newfag",
mentionable: true,
position: 7,
},
"LIMBO": {
name: "limbo",
position: 8,
}
};
} satisfies Record<string, RoleCreateOptions>;
static readonly STARTER_ROLES = [RoleService.ROLES["LURKER"], RoleService.ROLES["NEWFAG"]];
private client: Client
public static get limboMode() { return DataService.data.limboMode; }
public static set limboMode(mode: boolean) { DataService.data = { ...DataService.data, limboMode: mode }; }
constructor(client: Client) {
this.client = client;
}
validate(guilds: Collection<string, Guild>): void {
static async init(guilds: Collection<string, Guild>) {
// Check if any roles are missing
guilds.forEach(guild => {
const missing = Object.values(RoleService.ROLES).filter(role => !this.getRoleByName(guild, role.name));
if (missing.length) console.error(`${guild.name} is missing roles: ${missing.map(r => r.name).join(", ")}`);
});
}
async createRoles(guild: Guild, roles: RoleCreateOptions[]) {
static async createRolesIfNotExist(guild: Guild, roles: RoleCreateOptions[]) {
for (const role of roles) {
try {
await guild.roles.create(role);
if (!this.getRoleByName(guild, role.name)) {
await guild.roles.create(role);
}
}
catch (err) {
console.error(`Failed to create role: ${role.name}`, err);
@@ -83,7 +76,7 @@ export default class RoleService {
}
}
async giveStarterRoles(guildMember: GuildMember) {
static async giveStarterRoles(guildMember: GuildMember) {
for (const starterRole of RoleService.STARTER_ROLES) {
const role = this.getRoleByName(guildMember.guild, starterRole?.name);
if (!role) continue;
@@ -95,9 +88,15 @@ export default class RoleService {
console.error(`Failed to add starter role: ${role.name}`, err);
}
}
if (this.limboMode) {
const limboRole = this.getRoleByName(guildMember.guild, this.ROLES["LIMBO"].name)
if (!limboRole) return;
await guildMember.roles.add(limboRole);
}
}
getRoleByName(guild: Guild, roleName?: string) {
static getRoleByName(guild: Guild, roleName?: string) {
return guild.roles.cache.find(role => role.name === roleName);
}
}