### Start Bot in Production Mode (discraft start) Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Starts your Discraft bot in production mode. This command is used for deploying your bot after it has been built. It supports various package managers and can be run via npx or a global installation. ```bash npx discraft start ``` ```bash pnpm discraft start ``` ```bash bunx discraft start ``` ```bash yarn discraft start ``` ```bash discraft start ``` -------------------------------- ### Environment Variables Configuration Example (.env.example) Source: https://github.com/the-best-codes/discraft-js/blob/main/templates/vercel-ts-ai/README.md Example `.env.example` file showing necessary environment variables for a Discraft Vercel bot. Includes Discord API credentials (Public Key, App ID, Token) and Google AI API details (API Key, Model). These should be set in Vercel project settings. ```env # You will need to add these secrets to the 'Environment Variables' section of your Vercel project # https://vercel.com/docs/projects/environment-variables # From `General Information > Public Key` | https://discord.com/developers/applications DISCORD_PUBLIC_KEY='' # From `General Information > App ID` | https://discord.com/developers/applications DISCORD_APP_ID='' # From `Bot > Token` | https://discord.com/developers/applications DISCORD_TOKEN='' # From `Get API Key` | https://aistudio.google.com/app/apikey GOOGLE_AI_API_KEY='' # From the Google model list GOOGLE_AI_MODEL='gemini-2.0-flash-exp' ``` -------------------------------- ### Discraft Project File Structure Example Source: https://github.com/the-best-codes/discraft-js/blob/main/templates/vercel-ts-ai/README.md An example of the directory structure created after initializing a Discraft project with the Vercel + TypeScript + Google AI template. It shows the key files and folders for commands, public assets, scripts, utilities, and configuration. ```tree my-discraft-project/ ├── commands/ │ ├── chat.ts │ └── ping.ts ├── public/ │ └── index.html ├── scripts/ │ └── register.ts ├── utils/ │ ├── logger.ts │ └── types.ts ├── .env.example ├── .gitignore ├── .vercelignore ├── index.ts ├── package.json ├── README.md ├── tsconfig.json └── vercel.json ``` -------------------------------- ### Initialize New Discraft Project (discraft init) Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Initializes a new Discraft project with specified options. You can define the project directory, package manager, and template. Dependency installation can also be skipped. Run via npx or global installation. ```bash npx discraft init -d my-bot -p bun --skip-install -t ts ``` ```bash discraft init -d my-bot -p bun --skip-install -t ts ``` -------------------------------- ### Start Bot in Development Mode (discraft dev) Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Starts your Discraft bot in development mode. This command enables hot-reloading for commands and events, allowing for a streamlined development workflow. It supports various package managers and can be run via npx or a global installation. ```bash npx discraft dev ``` ```bash pnpm discraft dev ``` ```bash bunx discraft dev ``` ```bash yarn discraft dev ``` ```bash discraft dev ``` -------------------------------- ### Discraft CLI: Initialize New Project Source: https://context7.com/the-best-codes/discraft-js/llms.txt Initializes a new Discraft Discord bot project. Supports interactive setup, specifying project name, package manager (bun, npm), and template type (ts, js). Can skip dependency installation. ```bash npx discraft init npx discraft init -d my-discord-bot -p bun -t ts npx discraft init --skip-install -t js npx discraft init -p npm ``` -------------------------------- ### Configure Development Server Options (discraft dev) Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Starts the bot in development mode with advanced configuration options. You can specify the builder (esbuild or bun), the runner (node or bun), and choose to clear the console on each rebuild for a cleaner development experience. ```bash npx discraft dev -b esbuild -r bun -c ``` ```bash discraft dev -b esbuild -r bun -c ``` -------------------------------- ### Install Beta Version (npm) Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Command to install the latest beta version of the Discraft package using npm. This is useful for testing upcoming features. ```bash npm install discraft@beta ``` -------------------------------- ### Project Structure Example Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Illustrates the typical directory and file organization for a Discraft JS project, showing where different types of files like commands, events, and configurations should be placed. ```tree my-discraft-bot/ ├── .discraft/ # Internal Discraft files (auto-generated) ├── clients/ # Discord.js client setup │ └── discord.ts # Discord.js client configuration ├── commands/ # Your bot's command files │ ├── ping.ts # Example ping command │ └── ... # Other commands ├── events/ # Event handlers │ ├── error.ts # Error handling │ ├── messageCreate.ts # Example message handler │ └── ready.ts # Client ready handler ├── utils/ # Utility functions │ └── logger.ts # Logging configuration ├── index.ts # Main entry point for the bot ├── package.json # Project dependencies and scripts ├── tsconfig.json # TypeScript configuration └── .env # Environment variables (e.g., bot token) ``` -------------------------------- ### Discord.js Client Setup with Intents and Partials (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt Initializes a new Discord.js client instance with necessary intents and partials. Intents define the events the bot will receive from Discord, while partials ensure that certain events (like messages or channels) are processed even if they are not fully available. This setup is crucial for the bot's basic functionality. ```typescript import { Client, GatewayIntentBits, Partials } from "discord.js"; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers, GatewayIntentBits.DirectMessages, ], partials: [ Partials.Message, Partials.Channel, Partials.Reaction, ], }); export default client; ``` -------------------------------- ### Initialize Discraft Project with Vercel Template Source: https://github.com/the-best-codes/discraft-js/blob/main/templates/vercel-ts-ai/README.md Command to initialize a new Discraft project, specifically selecting the 'Vercel + TypeScript + Google AI' template. This sets up the project structure for a serverless Discord bot. ```bash mkdir my-discraft-project cd my-discraft-project discraft init ? Select a template: TypeScript JavaScript ❯ Vercel + TypeScript + Google AI ``` -------------------------------- ### Discraft CLI: Start Development Mode Source: https://context7.com/the-best-codes/discraft-js/llms.txt Starts the Discraft bot in development mode with hot reloading. Allows specifying the builder (esbuild, bun) and runner (node, bun). Supports clearing the console on rebuild. ```bash npx discraft dev npx discraft dev -b esbuild -r node npx discraft dev -c npx discraft dev -b bun -r bun ``` -------------------------------- ### Discraft CLI: Start Production Bot Source: https://context7.com/the-best-codes/discraft-js/llms.txt Starts the built Discraft bot in production mode. Supports auto-detection of the runner or explicit selection of runners like 'node' or 'bun'. ```bash npx discraft start npx discraft start -r node npx discraft start -r bun ``` -------------------------------- ### Build and Deploy Discraft Vercel Bot Source: https://github.com/the-best-codes/discraft-js/blob/main/templates/vercel-ts-ai/README.md Commands to build the Discraft bot for Vercel deployment and then deploy it. The build step generates necessary API routes, and the deploy command pushes the project to Vercel. ```bash npm run build # or discraft vercel build npm run deploy ``` -------------------------------- ### Discraft Event Handler Example Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md An example of an event handler in Discraft, specifically for the ClientReady event. This TypeScript code demonstrates how to set the bot's activity status and log a success message upon successful login using Discord.js and a custom logger. ```typescript import { ActivityType, Client, Events } from "discord.js"; import { logger } from "../utils/logger"; export default { event: Events.ClientReady, handler: (client: Client) => { if (!client.user) { logger.error("Client user is not set."); return; } client.user.setPresence({ activities: [ { name: "Discraft", // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore Discord.js does not have this property, but it is valid state: "Created with Discraft", type: ActivityType.Custom, }, ], status: "online", }); logger.success("Client logged in."); }, }; ``` -------------------------------- ### Discraft: Basic Slash Command (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt Example of a basic Discord slash command using Discraft and discord.js. It defines a 'ping' command that responds with 'Pong!'. Requires discord.js. ```typescript import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js"; export default { data: new SlashCommandBuilder() .setName("ping") .setDescription("Responds with Pong!"), async execute(data: { interaction: ChatInputCommandInteraction }) { const interaction = data.interaction; await interaction.reply("Pong!"); }, }; ``` -------------------------------- ### Discord Bot Interactions Endpoint URL Configuration Source: https://github.com/the-best-codes/discraft-js/blob/main/templates/vercel-ts-ai/README.md Instructions for setting the Interactions Endpoint URL in the Discord Developer Portal for your bot. This URL should point to your Vercel deployment followed by '/api' to handle slash commands. ```text 1. Go to your bot's application page on the Discord Developer Portal. 2. Navigate to the 'General Information' tab. 3. In the 'Interactions Endpoint URL' field, enter your Vercel deployment URL followed by '/api'. ``` -------------------------------- ### Discraft: Slash Command with Options and Embeds (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt Example of a Discord slash command with user options and embed responses using Discraft and discord.js. The 'userinfo' command retrieves information about a specified user or the command invoker. Requires discord.js. ```typescript import { ChatInputCommandInteraction, SlashCommandBuilder, EmbedBuilder } from "discord.js"; export default { data: new SlashCommandBuilder() .setName("userinfo") .setDescription("Get information about a user") .addUserOption(option => option .setName("target") .setDescription("The user to get info about") .setRequired(false) ), async execute(data: { interaction: ChatInputCommandInteraction }) { const interaction = data.interaction; const target = interaction.options.getUser("target") || interaction.user; const member = interaction.guild?.members.cache.get(target.id); const embed = new EmbedBuilder() .setTitle(`User Info: ${target.username}`) .setThumbnail(target.displayAvatarURL()) .addFields( { name: "ID", value: target.id, inline: true }, { name: "Tag", value: target.tag, inline: true }, { name: "Created", value: target.createdAt.toDateString(), inline: true }, { name: "Joined Server", value: member?.joinedAt?.toDateString() || "N/A", inline: true } ) .setColor("#5865F2"); await interaction.reply({ embeds: [embed] }); }, }; ``` -------------------------------- ### Standard Discord Bot Entry Point (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt This snippet demonstrates the main entry point for a Discord bot using Discraft JS. It handles bot initialization, token loading, event and command registration, and graceful shutdown on SIGINT. It also includes handlers for uncaught exceptions and unhandled rejections. Dependencies include dotenv, discord.js, and custom modules for commands, events, and logging. ```typescript import { configDotenv } from "dotenv"; configDotenv(); import { Events } from "discord.js"; import { registerCommands } from "./.discraft/commands/index"; import { registerEvents } from "./.discraft/events/index"; import client from "./clients/discord"; import { logger } from "./utils/logger"; logger.start("Starting bot..."); // Register events before login registerEvents(client) .then(() => { logger.verbose("Events registered in main process."); }) .catch((err) => { logger.error("Error registering events."); logger.verbose(err); }) .finally(() => { client.on(Events.ClientReady, async () => { logger.success("Client logged in."); try { await registerCommands(client); } catch (err) { logger.error("Error registering commands."); logger.verbose(err); } }); client.login(process.env.DISCORD_TOKEN).catch((err) => { logger.error( "Client login failed, make sure your token is set correctly." ); logger.verbose(err); }); }); process.on("uncaughtException", (err) => { logger.error("Uncaught exception."); logger.verbose(err); }); process.on("unhandledRejection", (err) => { logger.error("Unhandled rejection."); logger.verbose(err); }); process.on("SIGINT", async () => { logger.info("Received SIGINT, Gracefully shutting down..."); try { logger.info("Closing client..."); await client.destroy(); logger.success("Client closed."); } catch (err) { logger.error("Error while shutting down client."); logger.verbose(err); } logger.info("Exiting..."); process.exit(0); }); ``` -------------------------------- ### Build Bot for Production (discraft build) Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Builds your Discraft bot application for production. This command optimizes your code for deployment. You can specify the builder to use, such as esbuild or bun, for the build process. ```bash npx discraft build -b bun ``` ```bash discraft build -b bun ``` -------------------------------- ### Environment Variable Configuration (.env) Source: https://github.com/the-best-codes/discraft-js/blob/main/README.md Shows the required format for the .env file to store sensitive bot credentials like the Discord token and client ID. This file should not be committed to version control. ```dotenv DISCORD_TOKEN=your_bot_token_here DISCORD_APP_ID=your_client_id_here ``` -------------------------------- ### Discraft CLI: Build for Vercel Deployment Source: https://context7.com/the-best-codes/discraft-js/llms.txt Builds the Discraft project specifically for deployment on Vercel serverless functions. Supports auto-detection or explicit selection of the build tool. ```bash npx discraft vercel build npx discraft vercel build -b bun ``` -------------------------------- ### Discraft CLI: Build for Production Source: https://context7.com/the-best-codes/discraft-js/llms.txt Builds the Discraft project for production deployment. Supports auto-detection of the build tool or explicit selection of builders like 'bun' or 'esbuild'. ```bash npx discraft build npx discraft build -b bun npx discraft build -b esbuild ``` -------------------------------- ### Discraft CLI: Build Standalone Executable Source: https://context7.com/the-best-codes/discraft-js/llms.txt Builds a standalone executable for the Discraft bot. Supports targeting different operating systems and architectures (linux-x64, windows-x64, darwin-arm64, linux-arm64). Allows specifying custom entry points and output file names. ```bash npx discraft exec build --target linux-x64 npx discraft exec build --target windows-x64 --entry dist/index.js --outfile dist/my-bot npx discraft exec build --target darwin-arm64 npx discraft exec build --target linux-arm64 ``` -------------------------------- ### Message Create Event Handler for Prefix Commands (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt Processes incoming messages to handle basic text-based commands prefixed with '!'. It ignores messages from bots, parses the command and arguments, and responds to 'hello' and 'help' commands. For more advanced features, it suggests using slash commands. ```typescript import { Events, Message } from "discord.js"; import { logger } from "../utils/logger"; export default { event: Events.MessageCreate, handler: async (message: Message) => { // Ignore bot messages if (message.author.bot) return; // Check for prefix commands const prefix = "!"; if (!message.content.startsWith(prefix)) return; const args = message.content.slice(prefix.length).trim().split(/ +/); const command = args.shift()?.toLowerCase(); try { if (command === "hello") { await message.reply("Hello! 👋"); } else if (command === "help") { await message.reply( "Available commands: !hello, !help\nUse slash commands for more features!" ); } } catch (error) { logger.error("Error handling message:", error); } }, }; ``` -------------------------------- ### Required Environment Variables for Discraft JS (Bash) Source: https://context7.com/the-best-codes/discraft-js/llms.txt This bash script snippet outlines the essential environment variables required to configure a Discraft JS bot. It includes variables for Discord bot tokens, application IDs, Vercel deployment public keys, and Google AI API keys/models. These variables are typically stored in a `.env` file. ```bash # .env file structure # Bot token from Discord Developer Portal > Bot > Token DISCORD_TOKEN='your_bot_token_here' # Application ID from Discord Developer Portal > General Information > App ID DISCORD_APP_ID='your_application_id_here' # For Vercel deployments: Public key from Discord Developer Portal DISCORD_PUBLIC_KEY='your_public_key_here' # For AI-integrated templates GOOGLE_AI_API_KEY='your_google_ai_api_key_here' GOOGLE_AI_MODEL='gemini-2.0-flash-exp' # Optional: Set log level CONSOLA_LEVEL='info' # Options: verbose, info, warn, error ``` -------------------------------- ### Standard TypeScript Project Layout for Discraft JS (Tree) Source: https://context7.com/the-best-codes/discraft-js/llms.txt This is a tree structure representing a standard TypeScript project layout for a Discraft JS bot. It shows the organization of directories for auto-generated files, client configurations, command handlers, event handlers, utilities, build output, main entry point, and configuration files. ```tree my-discord-bot/ ├── .discraft/ # Auto-generated by CLI (do not edit) │ ├── commands/ │ │ └── index.ts # Auto-generated command registration │ └── events/ │ └── index.ts # Auto-generated event registration ├── clients/ │ └── discord.ts # Discord.js client configuration ├── commands/ │ ├── ping.ts # Slash command examples │ ├── userinfo.ts │ └── messageinfo.ts ├── events/ │ ├── ready.ts # Event handler examples │ ├── messageCreate.ts │ └── error.ts ├── utils/ │ └── logger.ts # Logging utility ├── dist/ # Build output (auto-generated) ├── index.ts # Main entry point ├── package.json ├── tsconfig.json ├── .env # Environment variables (create from .env.example) └── .env.example # Environment variable template ``` -------------------------------- ### Client Ready Event Handler (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt Sets the Discord bot's presence upon successful login. It logs the bot's username and tag and customizes the activity status. This handler is triggered when the Discord client is ready and has successfully connected. ```typescript import { ActivityType, Client, Events } from "discord.js"; import { logger } from "../utils/logger"; export default { event: Events.ClientReady, handler: (client: Client) => { try { if (!client.user) { logger.error("Client user is not set."); return; } client.user.setPresence({ activities: [ { name: "Discraft", state: "Created with Discraft", type: ActivityType.Custom, }, ], status: "online", }); logger.success(`Logged in as ${client.user.tag}!`); } catch (err) { logger.error("Error setting presence:", err); } }, }; ``` -------------------------------- ### AI-Integrated Chat Command for Vercel (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt This TypeScript code defines a Discord slash command named 'chat' that integrates with Gemini AI. It accepts a text prompt and an optional image, processes them using the Google Generative AI API, and returns the AI's response. It handles input validation, image processing, and error handling. Dependencies include `@google/generative-ai` and `discord-api-types/v10`. ```typescript import { GoogleGenerativeAI } from "@google/generative-ai"; import { ApplicationCommandOptionType, ApplicationCommandType, MessageFlags, } from "discord-api-types/v10"; export default { data: { name: "chat", description: "Chat with Gemini AI", options: [ { name: "prompt", description: "The prompt for the AI", type: ApplicationCommandOptionType.String, required: true, }, { name: "image", description: "Optional image to include in the prompt", type: ApplicationCommandOptionType.Attachment, required: false, }, ], }, async execute(data: { interaction: SimplifiedInteraction }) { const genAI = new GoogleGenerativeAI(process.env.GOOGLE_AI_API_KEY || ""); const model = genAI.getGenerativeModel({ model: process.env.GOOGLE_AI_MODEL || "gemini-1.5-flash", }); const interaction = data.interaction; if (interaction.data.type !== ApplicationCommandType.ChatInput) { return { content: "This command can only be used as a chat input command.", flags: MessageFlags.Ephemeral, }; } const promptOption = interaction.data.options?.find( (option) => option.name === "prompt" ); const imageOption = interaction.data.options?.find( (option) => option.name === "image" ); const prompt = promptOption?.value || ""; const imageAttachment = interaction.data.resolved?.attachments?.[imageOption?.value || ""]; if (prompt.length > 2000) { return { content: "Prompt must be less than 2000 characters.", flags: MessageFlags.Ephemeral, }; } try { let parts = [prompt]; if (imageAttachment) { const imageBuffer = await (await fetch(imageAttachment.url)).arrayBuffer(); const imageBase64 = Buffer.from(imageBuffer).toString("base64"); parts = [ prompt, { inlineData: { data: imageBase64, mimeType: imageAttachment.content_type, }, }, ]; } const result = await model.generateContent(parts); const response = result.response.text(); const truncatedResponse = response.length > 1900 ? response.slice(0, 1900) + "\n...[truncated]" : response; return { content: truncatedResponse }; } catch (error) { console.error("Error during AI chat:", error); return { content: "An error occurred while processing your request.", flags: MessageFlags.Ephemeral, }; } }, }; ``` -------------------------------- ### Vercel Serverless Handler for Discord Interactions (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt This TypeScript snippet implements a Vercel Serverless function to handle Discord interactions. It verifies incoming request signatures using Discord's public key, handles PING interactions, and processes APPLICATION_COMMAND interactions by deferring responses, executing the command, and updating the original message. Dependencies include @vercel/node, axios, discord-api-types, discord-interactions, and raw-body. ```typescript import type { VercelRequest, VercelResponse } from "@vercel/node"; import axios from "axios"; import { InteractionResponseType, MessageFlags } from "discord-api-types/v10"; import { InteractionType, verifyKey } from "discord-interactions"; import getRawBody from "raw-body"; import commands from "./.discraft/commands/index"; export default async function handler(req: VercelRequest, res: VercelResponse) { try { if (req.method !== "POST") { return res.status(405).send({ error: "Method Not Allowed" }); } const signature = req.headers["x-signature-ed25519"]; const timestamp = req.headers["x-signature-timestamp"]; const rawBody = await getRawBody(req); // Verify Discord signature const isValidRequest = await verifyKey( rawBody, signature as string, timestamp as string, process.env.DISCORD_PUBLIC_KEY! ); if (!isValidRequest) { return res.status(401).send({ error: "Invalid request signature" }); } const message = JSON.parse(rawBody.toString()); // Handle ping if (message.type === InteractionType.PING) { return res.status(200).json({ type: InteractionResponseType.Pong }); } // Handle commands if (message.type === InteractionType.APPLICATION_COMMAND) { const commandName = message.data.name.toLowerCase(); const command = commands[commandName]; if (command) { // Defer immediately await axios.post( `https://discord.com/api/v10/interactions/${message.id}/${message.token}/callback`, { type: InteractionResponseType.DeferredChannelMessageWithSource, data: { flags: command.data.initialEphemeral ? MessageFlags.Ephemeral : 0 } }, { headers: { "Content-Type": "application/json" } } ); // Execute command const result = await command.execute({ interaction: message }); // Update deferred response await axios.patch( `https://discord.com/api/v10/webhooks/${message.application_id}/${message.token}/messages/@original`, { content: result.content ?? "", flags: result.flags }, { headers: { "Content-Type": "application/json" } } ); return res.status(200).end(); } return res.status(400).json({ error: "Unknown Command" }); } return res.status(400).json({ error: "Unknown Interaction Type" }); } catch (error) { console.error("Error processing request:", error); return res.status(500).json({ error: "Failed to process request" }); } } ``` -------------------------------- ### Discord Error Event Handler (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt Logs general Discord client errors and provides specific handling for common issues like connection resets (ECONNRESET) and rate limiting. This helps in diagnosing and managing bot stability by providing warnings for potential problems. ```typescript import { Events } from "discord.js"; import { logger } from "../utils/logger"; export default { event: Events.Error, handler: (error: Error) => { logger.error("Discord client error:", error); // Add custom error handling logic if (error.message.includes("ECONNRESET")) { logger.warn("Connection reset, client will attempt to reconnect"); } else if (error.message.includes("RATE_LIMIT")) { logger.warn("Rate limit encountered, slowing down requests"); } }, }; ``` -------------------------------- ### Deferred Reply for Long-Running Commands (TypeScript) Source: https://context7.com/the-best-codes/discraft-js/llms.txt Handles Discord slash commands that require significant processing time. It defers the reply to Discord immediately, simulates a long operation using setTimeout, and then edits the deferred reply with the result or an error message. This prevents Discord from timing out the interaction. ```typescript import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js"; export default { data: new SlashCommandBuilder() .setName("longcommand") .setDescription("A command that takes time to process"), async execute(data: { interaction: ChatInputCommandInteraction }) { const interaction = data.interaction; // Defer the reply immediately await interaction.deferReply(); try { // Simulate long-running operation await new Promise(resolve => setTimeout(resolve, 5000)); // Edit the deferred reply await interaction.editReply("Processing complete!"); } catch (error) { await interaction.editReply("An error occurred during processing."); console.error("Command error:", error); } }, }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.