Files
public
src
.gitignore
package.json
README.md
tsconfig.json
Code
14 812
src/bot.ts
import {
Client,
Events,
GatewayIntentBits,
REST,
Routes,
SlashCommandBuilder,
type ChatInputCommandInteraction,
} from "discord.js";
import { config } from "./config";
import { AiService } from "./ai";
import { JsonStore } from "./storage";
import { formatStatus, getServerStatus, makeFixPlan } from "./server-tools";
const commands = [
new SlashCommandBuilder()
.setName("ask")
.setDescription("Ask NoobyBot a question")
.addStringOption((option) =>
option.setName("question").setDescription("Your question").setRequired(true),
),
new SlashCommandBuilder()
.setName("server-status")
.setDescription("Show a read-only server overview"),
new SlashCommandBuilder()
.setName("fix")
.setDescription("Create a safe server repair plan")
.addStringOption((option) =>
option.setName("issue").setDescription("What is going wrong?").setRequired(true),
),
new SlashCommandBuilder()
.setName("image")
.setDescription("Generate an image from a prompt")
.addStringOption((option) =>
option.setName("prompt").setDescription("Describe the image").setRequired(true),
),
new SlashCommandBuilder()
.setName("video")
.setDescription("Generate a video from a prompt")
.addStringOption((option) =>
option.setName("prompt").setDescription("Describe the video").setRequired(true),
),
new SlashCommandBuilder()
.setName("game")
.setDescription("Create a small browser game")
.addStringOption((option) =>
option.setName("prompt").setDescription("Describe the game").setRequired(true),
),
].map((command) => command.toJSON());
function limit(text: string, max = 1900): string {
return text.length > max ? `${text.slice(0, max - 3)}...` : text;
}
async function handleInteraction(
interaction: ChatInputCommandInteraction,
ai: AiService,
store: JsonStore,
): Promise<void> {
const name = interaction.commandName;
const userId = interaction.user.id;
store.log({ source: "discord", userId, action: name, input: JSON.stringify(interaction.options.data) });
if (name === "server-status") {
if (!interaction.guildId) {
await interaction.reply({ content: "This command must be used inside a server.", ephemeral: true });
return;
}
const status = await getServerStatus(interaction.client, interaction.guildId);
await interaction.reply(`**${status.name}**\n${formatStatus(status)}`);
return;
}
await interaction.deferReply();
if (name === "ask") {
const question = interaction.options.getString("question", true);
const context = interaction.guildId
? formatStatus(await getServerStatus(interaction.client, interaction.guildId))
: "No Discord server context is available.";
await interaction.editReply(limit(await ai.ask(question, context)));
return;
}
if (name === "fix") {
if (!interaction.guildId) {
await interaction.editReply("Use /fix inside the server you want to troubleshoot.");
return;
}
const issue = interaction.options.getString("issue", true);
const status = await getServerStatus(interaction.client, interaction.guildId);
const plan = makeFixPlan(issue, status);
await interaction.editReply(limit(`**${plan.title}**\nIssue: ${plan.issue}\n\n${plan.actions.map((action, index) => `${index + 1}. ${action}`).join("\n")}\n\n_${plan.safety}_`));
return;
}
if (name === "image" || name === "video") {
const prompt = interaction.options.getString("prompt", true);
const result = name === "image" ? await ai.image(prompt) : await ai.video(prompt);
await interaction.editReply(result.url ? `${result.text ?? "Generated media:"}\n${result.url}` : result.text ?? "No media was returned.");
return;
}
if (name === "game") {
const prompt = interaction.options.getString("prompt", true);
await interaction.editReply(limit(await ai.game(prompt)));
}
}
export function createBot(ai: AiService, store: JsonStore): Client {
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, async (readyClient) => {
const rest = new REST({ version: "10" }).setToken(config.discordToken);
await rest.put(Routes.applicationCommands(readyClient.user.id), { body: commands });
console.log(`NoobyBot connected as ${readyClient.user.tag}`);
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
try {
await handleInteraction(interaction, ai, store);
} catch (error) {
console.error(error);
const message = "Something went wrong while handling that request.";
if (interaction.deferred || interaction.replied) {
await interaction.editReply(message).catch(() => undefined);
} else {
await interaction.reply({ content: message, ephemeral: true }).catch(() => undefined);
}
}
});
return client;
}