### Environment Setup: Configure Bot Credentials and Services (.env) Source: https://context7.com/barthofu/tscord/llms.txt Configuration for bot credentials, guild IDs, owner IDs, and optional services like databases, API servers, and external APIs. Loaded from a .env file. ```bash # .env file configuration BOT_TOKEN="your_discord_bot_token" TEST_GUILD_ID="123456789" BOT_OWNER_ID="987654321" # Optional: Database (defaults to SQLite) DATABASE_HOST="localhost" DATABASE_PORT=5432 DATABASE_NAME="tscord_bot" DATABASE_USER="tscord" DATABASE_PASSWORD="password" # Optional: API Server (defaults shown) API_PORT=4000 API_ADMIN_TOKEN="random_secure_token_here" # Optional: External Services IMGUR_CLIENT_ID="your_imgur_client_id" ``` -------------------------------- ### Initialize a new TSCord bot project Source: https://github.com/barthofu/tscord/blob/main/README.md This command initializes a new Discord bot project using the TSCord template. It sets up the basic project structure and dependencies required for a TSCord bot. Ensure you have Node.js and npm/npx installed. ```bash npx tscord init bot my-bot ``` -------------------------------- ### Get User and Guild Growth Data (API) Source: https://context7.com/barthofu/tscord/llms.txt Fetches daily user and guild growth statistics for a specified number of past days. Requires a Discord user token for authorization. ```shell curl -X GET http://localhost:4000/stats/usersAndGuilds?numberOfDays=30 \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" ``` -------------------------------- ### GET /stats/usersAndGuilds Source: https://context7.com/barthofu/tscord/llms.txt Retrieves the growth statistics for active users, total users, and guilds over a specified number of days. ```APIDOC ## GET /stats/usersAndGuilds ### Description Retrieves the growth statistics for active users, total users, and guilds over a specified number of days. ### Method GET ### Endpoint /stats/usersAndGuilds ### Parameters #### Query Parameters - **numberOfDays** (integer) - Required - The number of past days for which to retrieve statistics. #### Request Body None ### Request Example ```bash curl -X GET http://localhost:4000/stats/usersAndGuilds?numberOfDays=30 \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" ``` ### Response #### Success Response (200) - **activeUsers** (array) - An array of objects, each containing a date and the count of active users for that date. - **users** (array) - An array of objects, each containing a date and the total count of users for that date. - **guilds** (array) - An array of objects, each containing a date and the total count of guilds for that date. #### Response Example ```json { "activeUsers": [ { "date": "01/12/2025", "count": 4800 }, { "date": "02/12/2025", "count": 5000 } ], "users": [ { "date": "01/12/2025", "count": 48000 }, { "date": "02/12/2025", "count": 50000 } ], "guilds": [ { "date": "01/12/2025", "count": 98 }, { "date": "02/12/2025", "count": 100 } ] } ``` ``` -------------------------------- ### Database Service with MikroORM, Backups, and Migrations Source: https://context7.com/barthofu/tscord/llms.txt Manages MikroORM database connections, including automated backups and migrations. Provides methods to access the entity manager, repositories, perform CRUD operations, and manage database backups and size. ```typescript // Usage examples: import { Database } from '@/services' const db = await resolveDependency(Database) // Access entity manager const em = db.em // Get repository const guildRepo = db.get(Guild) const userRepo = db.get(User) // Create and persist entity const newGuild = guildRepo.create({ id: '123456789', prefix: '!', deleted: false }) await db.em.persistAndFlush(newGuild) // Find entities const guild = await guildRepo.findOne({ id: '123456789' }) const allGuilds = await guildRepo.findAll() const activeGuilds = await guildRepo.find({ deleted: false }) // Update entity guild.prefix = '?' await db.em.flush() // Delete entity await db.em.removeAndFlush(guild) // Create database backup const success = await db.backup() // or with custom name: await db.backup('snapshot-before-update') // Restore from backup await db.restore('snapshot-before-update.txt') // Get backup list const backups = db.getBackupList() // Returns: ['snapshot-2025-12-01.txt', 'snapshot-2025-12-02.txt'] // Get database size const size = db.getSize() // Returns: { db: 1024000, backups: 5120000 } // Check if using SQLite const isSQLite = db.isSQLiteDatabase() // Note: Backups run automatically daily at 00:00 via @Schedule decorator ``` -------------------------------- ### Bot Configuration: General Settings and Appearance (TypeScript) Source: https://context7.com/barthofu/tscord/llms.txt Defines general bot settings such as name, description, default locale, command prefix, owner ID, activities, image upload preferences, links, and developer IDs. Also includes configurations for the evaluation command. ```typescript // src/configs/general.ts export const generalConfig: GeneralConfigType = { name: 'MyBot', description: 'A powerful Discord bot', defaultLocale: 'en', simpleCommandsPrefix: '!', ownerId: process.env.BOT_OWNER_ID, activities: [ { text: 'with TypeScript', type: 'PLAYING' }, { text: 'your commands', type: 'LISTENING' }, { text: '/help for commands', type: 'WATCHING' } ], automaticUploadImagesToImgur: false, links: { invite: 'https://discord.com/api/oauth2/authorize?client_id=...', supportServer: 'https://discord.gg/...', gitRemoteRepo: 'https://github.com/...' }, devs: ['987654321'], // Additional developer IDs eval: { name: 'eval', onlyOwner: false } } ``` -------------------------------- ### Prefix Command Source: https://context7.com/barthofu/tscord/llms.txt Allows administrators to configure custom command prefixes for guilds. ```APIDOC ## POST /commands/prefix ### Description Allows administrators to configure custom command prefixes for guilds. This command requires administrator privileges. ### Method POST ### Endpoint /commands/prefix ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **prefix** (string) - Optional - The desired prefix for the guild. If omitted or set to null, the default prefix will be used. ### Request Example ```bash # Usage in Discord: /prefix prefix:! ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating that the prefix has been successfully updated. #### Response Example ``` "Prefix successfully updated to: !" ``` ``` -------------------------------- ### User Entity Management with MikroORM Source: https://context7.com/barthofu/tscord/llms.txt Defines the User entity for tracking user interactions and activity timestamps using MikroORM. Includes methods for updating interaction times and basic user management. ```typescript // src/entities/User.ts import { Entity, EntityRepository, PrimaryKey, Property } from '@mikro-orm/core' @Entity({ repository: () => UserRepository }) export class User extends CustomBaseEntity { @PrimaryKey({ autoincrement: false }) id!: string @Property() lastInteract: Date = new Date() } export class UserRepository extends EntityRepository { async updateLastInteract(userId?: string): Promise { const user = await this.findOne({ id: userId }) if (user) { user.lastInteract = new Date() await this.em.flush() } } } // Usage example: import { Database } from '@/services' const db = await resolveDependency(Database) const userRepo = db.get(User) // Create new user const user = userRepo.create({ id: '987654321' }) await db.em.persistAndFlush(user) // Update last interaction await userRepo.updateLastInteract('987654321') // Count total active users const totalUsers = await userRepo.count() ``` -------------------------------- ### Bot Management API Endpoints Source: https://context7.com/barthofu/tscord/llms.txt These bash commands illustrate how to interact with the bot's management API to retrieve bot information, list and manage guilds, and toggle maintenance mode. An admin token is required for these operations. ```bash # Get bot information curl -X GET http://localhost:4000/bot/info \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" # Response: { "user": { "id": "123456789", "username": "MyBot", "discriminator": "0000", "iconURL": "https://cdn.discordapp.com/avatars/", "bannerURL": null }, "owner": { "id": "987654321", "username": "BotOwner", "discriminator": "0001" } } # List all guilds curl -X GET http://localhost:4000/bot/guilds \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" # Get specific guild details curl -X GET http://localhost:4000/bot/guilds/123456789 \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" # Response: { "discord": { "id": "123456789", "name": "My Server", "memberCount": 1500, "iconURL": "https://cdn.discordapp.com/icons/" }, "database": { "id": "123456789", "prefix": "!", "deleted": false, "lastInteract": "2025-12-01T10:00:00.000Z" } } # Leave a guild curl -X DELETE http://localhost:4000/bot/guilds/123456789 \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" # Enable/disable maintenance mode curl -X POST http://localhost:4000/bot/maintenance \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{"maintenance": true}' # Response: { "maintenance": true } ``` -------------------------------- ### Prefix Command for Guild-Specific Prefixes (TypeScript) Source: https://context7.com/barthofu/tscord/llms.txt Allows administrators to set custom command prefixes for their guilds. Requires administrator permissions to use. Stores the prefix in the database. ```typescript // src/commands/Admin/prefix.ts import { Category } from '@discordx/utilities' import { ApplicationCommandOptionType, CommandInteraction } from 'discord.js' import { Discord, Injectable, Slash, SlashOption } from '@/decorators' import { Guild } from '@/entities' import { Guard, UserPermissions } from '@/guards' import { Database } from '@/services' import { resolveGuild, simpleSuccessEmbed } from '@/utils/functions' @Discord() @Injectable() @Category('Admin') export default class PrefixCommand { constructor(private db: Database) {} @Slash({ name: 'prefix' }) @Guard(UserPermissions(['Administrator'])) async prefix( @SlashOption({ name: 'prefix', localizationSource: 'COMMANDS.PREFIX.OPTIONS.PREFIX', type: ApplicationCommandOptionType.String, }) prefix: string | undefined, interaction: CommandInteraction, client: Client, { localize }: InteractionData ) { const guild = resolveGuild(interaction) const guildData = await this.db.get(Guild).findOne({ id: guild?.id || '' }) if (guildData) { guildData.prefix = prefix || null await this.db.em.persistAndFlush(guildData) simpleSuccessEmbed( interaction, localize.COMMANDS.PREFIX.EMBED.DESCRIPTION({ prefix: prefix || generalConfig.simpleCommandsPrefix, }) ) } } } // Usage in Discord: // /prefix prefix:! // Response: "Prefix successfully updated to: !" ``` -------------------------------- ### Statistics API Endpoints Source: https://context7.com/barthofu/tscord/llms.txt These bash commands show how to retrieve various statistics from the bot, including total usage, command usage over a specified period, and top commands by popularity. Authentication with a user token is required. ```bash # Get total statistics curl -X GET http://localhost:4000/stats/totals \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" # Response: { "stats": { "totalUsers": 50000, "totalGuilds": 100, "totalActiveUsers": 5000, "totalCommands": 150000 } } # Get command usage over time (default: 7 days) curl -X GET http://localhost:4000/stats/commands/usage?numberOfDays=7 \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" # Response: [ { "date": "01/12/2025", "slashCommands": 150, "simpleCommands": 25, "contextMenus": 10 }, { "date": "02/12/2025", "slashCommands": 165, "simpleCommands": 30, "contextMenus": 12 } ] # Get top commands by usage curl -X GET http://localhost:4000/stats/commands/top \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" # Response: [ { "type": "CHAT_INPUT_COMMAND_INTERACTION", "name": "ping", "count": 5000 }, { "type": "CHAT_INPUT_COMMAND_INTERACTION", "name": "help", "count": 3500 } ] ``` -------------------------------- ### Bot Configuration: Logging Settings (TypeScript) Source: https://context7.com/barthofu/tscord/llms.txt Configures the logging behavior for the bot, including options for console output, file storage, specific Discord channels for logs, and exclusion of certain interaction types. Also includes settings for log archiving. ```typescript // src/configs/logs.ts export const logsConfig = { interaction: { console: true, file: true, channel: null, // or Discord channel ID exclude: ['BUTTON_INTERACTION'] }, archive: { enabled: true, retention: 30 // days } } ``` -------------------------------- ### Bot Configuration: API Settings (TypeScript) Source: https://context7.com/barthofu/tscord/llms.txt Configures the API server for the bot, including enabling/disabling the API and setting the port number. This allows for external integrations and dashboard connectivity. ```typescript // src/configs/api.ts export const apiConfig = { enabled: true, port: 4000, } ``` -------------------------------- ### Logger Service for Multi-Channel Logging Source: https://context7.com/barthofu/tscord/llms.txt Implements a comprehensive logging service that writes to console, files, and Discord channels. It supports automatic archiving and provides various methods for different log types. ```typescript // Usage examples: import { Logger } from '@/services' const logger = await resolveDependency(Logger) // Basic logging logger.log('Bot started successfully', 'info') logger.log('Configuration warning', 'warn') logger.log('Critical error occurred', 'error') // Log to specific Discord channel logger.log( 'Important event', 'info', true, // save to file '123456789' // Discord channel ID ) // Log interactions automatically logger.logInteraction(interaction) // Log new users logger.logNewUser(user) // Log guild events logger.logGuild('NEW_GUILD', guildId) logger.logGuild('DELETE_GUILD', guildId) // Log errors with stack traces try { throw new Error('Something went wrong') } catch (error) { logger.logError(error, 'Exception') } // Get recent logs (for API endpoint) const recentLogs = logger.getLastLogs() // Spinner for long operations logger.startSpinner('Loading resources...') // ... operation completes ... logger.spinner.stop() ``` -------------------------------- ### Health Check API Endpoints Source: https://context7.com/barthofu/tscord/llms.txt These bash commands demonstrate how to check the bot's health, latency, resource usage, and comprehensive system monitoring via its internal REST API. Authentication with an admin or user token is required. ```bash # Check if bot is online curl -X GET http://localhost:4000/health/check \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" # Response: { "online": true, "uptime": 3600000, "lastStartup": "2025-12-01T10:00:00.000Z" } # Get bot latency curl -X GET http://localhost:4000/health/latency \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" # Response: { "ping": 45 } # Get process resource usage curl -X GET http://localhost:4000/health/usage \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" # Response: { "cpu": "2.5", "memory": { "usedInMb": "150.3", "percentage": "1.8" }, "elapsed": 3600000 } # Get comprehensive system monitoring (dev only) curl -X GET http://localhost:4000/health/monitoring \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" # Response: { "botStatus": { "online": true, "uptime": 3600000, "maintenance": false }, "host": { "cpu": 25.5, "memory": { "totalMemMb": 8192, "usedMemMb": 4096 }, "uptime": 86400 }, "pid": { "cpu": "2.5", "memory": { "usedInMb": "150.3", "percentage": "1.8" } }, "latency": { "ping": 45 } } ``` -------------------------------- ### Stats Service for Bot Usage Analysis Source: https://context7.com/barthofu/tscord/llms.txt Provides a robust system for tracking and analyzing bot usage statistics with automated data collection. It supports registering custom and automatic events, retrieving various aggregated data, and system metrics. ```typescript // Usage examples: import { Stats } from '@/services' const stats = await resolveDependency(Stats) // Register custom statistic await stats.register('CUSTOM_EVENT', 'event_value', { userId: '123456789', guildId: '987654321' }) // Register interactions automatically await stats.registerInteraction(interaction) // Get total statistics const totals = await stats.getTotalStats() // Returns: { TOTAL_USERS, TOTAL_GUILDS, TOTAL_ACTIVE_USERS, TOTAL_COMMANDS } // Get top commands const topCommands = await stats.getTopCommands() // Returns: [{ type, name, count }, ...] // Get command usage over time const weeklyUsage = await stats.countStatsPerDays('CHAT_INPUT_COMMAND_INTERACTION', 7) // Returns: [{ date: '01/12/2025', count: 150 }, ...] // Get system metrics const pidUsage = await stats.getPidUsage() const hostUsage = await stats.getHostUsage() const latency = stats.getLatency() // Get user activity distribution const userActivity = await stats.getUsersActivity() // Returns: { '1-10': 100, '11-50': 50, '51-100': 25, ... } // Get top guilds by command usage const topGuilds = await stats.getTopGuilds() // Returns: [{ id, name, totalCommands }, ...] // Note: Daily stats are automatically registered at 23:59 via @Schedule decorator ``` -------------------------------- ### Guild Entity Management Source: https://context7.com/barthofu/tscord/llms.txt Manages guild-specific settings and interaction tracking within the database. ```APIDOC ## Database Entity: Guild ### Description Represents a guild in the database, storing guild-specific settings such as command prefixes and interaction tracking. ### Properties - **id** (string) - Primary Key. The unique identifier for the guild. - **prefix** (string | null) - The custom command prefix for the guild. Null if not set. - **deleted** (boolean) - Flag indicating if the guild is marked as deleted. - **lastInteract** (Date) - Timestamp of the last interaction with the guild. ### Repository Methods #### `updateLastInteract(guildId?: string): Promise` Updates the `lastInteract` timestamp for a given guild. #### `getActiveGuilds(): Promise` Retrieves all guilds that are not marked as deleted. ### Usage Example ```typescript import { Database } from '@/services' const db = await resolveDependency(Database) const guildRepo = db.get(Guild) // Find guild by ID const guild = await guildRepo.findOne({ id: '123456789' }) // Update last interaction await guildRepo.updateLastInteract('123456789') // Get all active guilds const activeGuilds = await guildRepo.getActiveGuilds() ``` ``` -------------------------------- ### Bot Management Endpoints Source: https://context7.com/barthofu/tscord/llms.txt Endpoints for retrieving bot information, managing guild associations, and controlling bot settings like maintenance mode. ```APIDOC ## GET /bot/info ### Description Retrieves general information about the bot, including its user profile and owner details. ### Method GET ### Endpoint /bot/info ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/bot/info \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" ``` ### Response #### Success Response (200) - **user** (object) - Information about the bot's user account. - **id** (string) - The bot's Discord user ID. - **username** (string) - The bot's Discord username. - **discriminator** (string) - The bot's Discord discriminator. - **iconURL** (string | null) - URL to the bot's avatar. - **bannerURL** (string | null) - URL to the bot's profile banner. - **owner** (object) - Information about the bot's owner. - **id** (string) - The owner's Discord user ID. - **username** (string) - The owner's Discord username. - **discriminator** (string) - The owner's Discord discriminator. #### Response Example ```json { "user": { "id": "123456789", "username": "MyBot", "discriminator": "0000", "iconURL": "https://cdn.discordapp.com/avatars/...", "bannerURL": null }, "owner": { "id": "987654321", "username": "BotOwner", "discriminator": "0001" } } ``` ## GET /bot/guilds ### Description Lists all guilds (servers) the bot is currently a part of. ### Method GET ### Endpoint /bot/guilds ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/bot/guilds \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" ``` ### Response #### Success Response (200) (Returns a list of guild objects, each containing basic guild information. Specific fields depend on implementation, but typically include IDs and names.) ## GET /bot/guilds/{guildId} ### Description Retrieves detailed information about a specific guild the bot is in. ### Method GET ### Endpoint /bot/guilds/{guildId} ### Parameters #### Path Parameters - **guildId** (string) - Required - The ID of the guild to retrieve information for. #### Query Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/bot/guilds/123456789 \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" ``` ### Response #### Success Response (200) - **discord** (object) - Discord-specific guild information. - **id** (string) - The guild's Discord ID. - **name** (string) - The name of the guild. - **memberCount** (integer) - The current number of members in the guild. - **iconURL** (string) - URL to the guild's icon. - **database** (object) - Database-related information for the guild. - **id** (string) - The guild's database ID. - **prefix** (string) - The configured command prefix for the guild. - **deleted** (boolean) - Indicates if the guild record has been marked as deleted. - **lastInteract** (string) - ISO 8601 timestamp of the last interaction with the guild. #### Response Example ```json { "discord": { "id": "123456789", "name": "My Server", "memberCount": 1500, "iconURL": "https://cdn.discordapp.com/icons/" }, "database": { "id": "123456789", "prefix": "!", "deleted": false, "lastInteract": "2025-12-01T10:00:00.000Z" } } ``` ## DELETE /bot/guilds/{guildId} ### Description Removes the bot from a specific guild (leaves the server). ### Method DELETE ### Endpoint /bot/guilds/{guildId} ### Parameters #### Path Parameters - **guildId** (string) - Required - The ID of the guild to leave. #### Query Parameters None ### Request Example ```bash curl -X DELETE http://localhost:4000/bot/guilds/123456789 \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" ``` ### Response #### Success Response (200) (Typically returns a success message or status code indicating the bot has left the guild.) ## POST /bot/maintenance ### Description Enables or disables maintenance mode for the bot. ### Method POST ### Endpoint /bot/maintenance ### Parameters #### Query Parameters None #### Path Parameters None #### Request Body - **maintenance** (boolean) - Required - Set to `true` to enable maintenance mode, `false` to disable. ### Request Example ```bash curl -X POST http://localhost:4000/bot/maintenance \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{"maintenance": true}' ``` ### Response #### Success Response (200) - **maintenance** (boolean) - The new state of the maintenance mode. #### Response Example ```json { "maintenance": true } ``` ``` -------------------------------- ### Ping Command for Bot Responsiveness (TypeScript) Source: https://context7.com/barthofu/tscord/llms.txt A Discord command that checks the bot's responsiveness by measuring the round-trip time for a message and displaying the WebSocket heartbeat ping. This command is part of the 'General' category. ```typescript // src/commands/General/ping.ts import { Category } from '@discordx/utilities' import { CommandInteraction, Message } from 'discord.js' import { Client } from 'discordx' import { Discord, Slash } from '@/decorators' @Discord() @Category('General') export default class PingCommand { @Slash({ name: 'ping' }) async ping( interaction: CommandInteraction, client: Client, { localize }: InteractionData ) { const msg = (await interaction.followUp({ content: 'Pinging...', fetchReply: true })) as Message const content = localize.COMMANDS.PING.MESSAGE({ member: msg.inGuild() ? `${interaction.member},` : '', time: msg.createdTimestamp - interaction.createdTimestamp, heartbeat: client.ws.ping ? ` The heartbeat ping is ${Math.round(client.ws.ping)}ms.` : '', }) await msg.edit(content) } } // Usage in Discord: // /ping // Response: "Pong! The message round-trip took 45ms. The heartbeat ping is 42ms." ``` -------------------------------- ### Ping Command Source: https://context7.com/barthofu/tscord/llms.txt Checks the bot's responsiveness and measures the latency between the client and the server. ```APIDOC ## POST /commands/ping ### Description Checks the bot's responsiveness and measures the latency between the client and the server. This command is typically used for diagnostics. ### Method POST ### Endpoint /commands/ping ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash # Usage in Discord: /ping ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the bot is responsive and includes the round-trip time and heartbeat ping. #### Response Example ``` "Pong! The message round-trip took 45ms. The heartbeat ping is 42ms." ``` ``` -------------------------------- ### Statistics Endpoints Source: https://context7.com/barthofu/tscord/llms.txt Endpoints for retrieving various statistics about the bot's activity, including command usage and user engagement. ```APIDOC ## GET /stats/totals ### Description Retrieves overall statistics for the bot, such as total users, guilds, and commands processed. ### Method GET ### Endpoint /stats/totals ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/stats/totals \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" ``` ### Response #### Success Response (200) - **stats** (object) - An object containing total counts. - **totalUsers** (integer) - Total number of unique users interacted with. - **totalGuilds** (integer) - Total number of guilds the bot is in. - **totalActiveUsers** (integer) - Total number of users who have been active recently. - **totalCommands** (integer) - Total number of commands executed. #### Response Example ```json { "stats": { "totalUsers": 50000, "totalGuilds": 100, "totalActiveUsers": 5000, "totalCommands": 150000 } } ``` ## GET /stats/commands/usage ### Description Retrieves the usage statistics for different types of commands over a specified period. ### Method GET ### Endpoint /stats/commands/usage ### Parameters #### Query Parameters - **numberOfDays** (integer) - Optional - The number of past days to include in the usage data. Defaults to 7. #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/stats/commands/usage?numberOfDays=7 \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" ``` ### Response #### Success Response (200) - Returns an array of objects, each representing command usage for a specific date. - **date** (string) - The date of the statistics (format: DD/MM/YYYY). - **slashCommands** (integer) - Number of slash commands used on that date. - **simpleCommands** (integer) - Number of simple (message-based) commands used on that date. - **contextMenus** (integer) - Number of context menu interactions on that date. #### Response Example ```json [ { "date": "01/12/2025", "slashCommands": 150, "simpleCommands": 25, "contextMenus": 10 }, { "date": "02/12/2025", "slashCommands": 165, "simpleCommands": 30, "contextMenus": 12 } ] ``` ## GET /stats/commands/top ### Description Retrieves a list of the most used commands. ### Method GET ### Endpoint /stats/commands/top ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/stats/commands/top \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" ``` ### Response #### Success Response (200) - Returns an array of objects, each representing a top command. - **type** (string) - The type of command interaction (e.g., "CHAT_INPUT_COMMAND_INTERACTION"). - **name** (string) - The name of the command. - **count** (integer) - The number of times the command was used. #### Response Example ```json [ { "type": "CHAT_INPUT_COMMAND_INTERACTION", "name": "ping", "count": 5000 }, { "type": "CHAT_INPUT_COMMAND_INTERACTION", "name": "help", "count": 3500 } ] ``` ``` -------------------------------- ### Guild Database Entity Definition (TypeScript) Source: https://context7.com/barthofu/tscord/llms.txt Defines the 'Guild' entity for storing guild-specific settings like custom prefixes and interaction timestamps. Includes methods for updating interaction times and retrieving active guilds. ```typescript // src/entities/Guild.ts import { Entity, EntityRepository, PrimaryKey, Property } from '@mikro-orm/core' @Entity({ repository: () => GuildRepository }) export class Guild extends CustomBaseEntity { @PrimaryKey({ autoincrement: false }) id!: string @Property({ nullable: true, type: 'string' }) prefix: string | null @Property() deleted: boolean = false @Property() lastInteract: Date = new Date() } export class GuildRepository extends EntityRepository { async updateLastInteract(guildId?: string): Promise { const guild = await this.findOne({ id: guildId }) if (guild) { guild.lastInteract = new Date() await this.em.flush() } } async getActiveGuilds() { return this.find({ deleted: false }) } } // Usage example: import { Database } from '@/services' const db = await resolveDependency(Database) const guildRepo = db.get(Guild) // Find guild by ID const guild = await guildRepo.findOne({ id: '123456789' }) // Update last interaction await guildRepo.updateLastInteract('123456789') // Get all active guilds const activeGuilds = await guildRepo.getActiveGuilds() ``` -------------------------------- ### Health Check Endpoints Source: https://context7.com/barthofu/tscord/llms.txt These endpoints provide insights into the bot's operational status, system resource usage, and network latency. ```APIDOC ## GET /health/check ### Description Checks if the bot is online and retrieves its uptime and last startup time. ### Method GET ### Endpoint /health/check ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/health/check \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" ``` ### Response #### Success Response (200) - **online** (boolean) - Indicates if the bot is currently online. - **uptime** (integer) - The duration in milliseconds since the bot last started. - **lastStartup** (string) - The ISO 8601 timestamp of the bot's last startup. #### Response Example ```json { "online": true, "uptime": 3600000, "lastStartup": "2025-12-01T10:00:00.000Z" } ``` ## GET /health/latency ### Description Retrieves the current network latency (ping) of the bot. ### Method GET ### Endpoint /health/latency ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/health/latency \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" ``` ### Response #### Success Response (200) - **ping** (integer) - The bot's current network latency in milliseconds. #### Response Example ```json { "ping": 45 } ``` ## GET /health/usage ### Description Retrieves the current CPU and memory usage of the bot process. ### Method GET ### Endpoint /health/usage ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/health/usage \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" ``` ### Response #### Success Response (200) - **cpu** (string) - The current CPU utilization percentage. - **memory** (object) - An object containing memory usage details. - **usedInMb** (string) - The amount of memory used in megabytes. - **percentage** (string) - The percentage of total memory currently in use. - **elapsed** (integer) - The elapsed time in milliseconds since the bot started. #### Response Example ```json { "cpu": "2.5", "memory": { "usedInMb": "150.3", "percentage": "1.8" }, "elapsed": 3600000 } ``` ## GET /health/monitoring ### Description Provides comprehensive system monitoring data, intended for development environments. ### Method GET ### Endpoint /health/monitoring ### Parameters #### Query Parameters None #### Path Parameters None ### Request Example ```bash curl -X GET http://localhost:4000/health/monitoring \ -H "Authorization: Bearer YOUR_DISCORD_USER_TOKEN" ``` ### Response #### Success Response (200) - **botStatus** (object) - Current status of the bot. - **online** (boolean) - Indicates if the bot is online. - **uptime** (integer) - Uptime in milliseconds. - **maintenance** (boolean) - Indicates if maintenance mode is active. - **host** (object) - Host system resource usage. - **cpu** (number) - Host CPU utilization percentage. - **memory** (object) - Host memory usage. - **totalMemMb** (integer) - Total available memory in MB. - **usedMemMb** (integer) - Used memory in MB. - **uptime** (integer) - Host system uptime in seconds. - **pid** (object) - Bot process resource usage. - **cpu** (string) - Bot process CPU utilization percentage. - **memory** (object) - Bot process memory usage. - **usedInMb** (string) - Used memory in MB. - **percentage** (string) - Percentage of total memory used by the process. - **latency** (object) - Bot's network latency. - **ping** (integer) - Ping in milliseconds. #### Response Example ```json { "botStatus": { "online": true, "uptime": 3600000, "maintenance": false }, "host": { "cpu": 25.5, "memory": { "totalMemMb": 8192, "usedMemMb": 4096 }, "uptime": 86400 }, "pid": { "cpu": "2.5", "memory": { "usedInMb": "150.3", "percentage": "1.8" } }, "latency": { "ping": 45 } } ``` ``` -------------------------------- ### User Permissions Guard: Restrict Commands by Discord Permissions Source: https://context7.com/barthofu/tscord/llms.txt This guard restricts command execution based on Discord user permissions. It supports applying single or multiple required permissions to commands, ensuring only users with the necessary roles can interact. ```typescript // Usage in commands: import { Guard, UserPermissions } from '@/guards' @Slash({ name: 'ban' }) @Guard(UserPermissions(['BanMembers'])) async ban(interaction: CommandInteraction) { // Only users with BanMembers permission can execute } @Slash({ name: 'admin' }) @Guard(UserPermissions(['Administrator'])) async admin(interaction: CommandInteraction) { // Only administrators can execute } // Multiple permissions (user needs ALL) @Slash({ name: 'moderate' }) @Guard(UserPermissions(['ManageMessages', 'KickMembers'])) async moderate(interaction: CommandInteraction) { // User must have both permissions } ``` -------------------------------- ### Maintenance Guard: Control Bot Access During Maintenance Source: https://context7.com/barthofu/tscord/llms.txt This guard blocks commands during maintenance mode, except for developers. It allows enabling, disabling, and checking the maintenance status of the bot. Applied globally or to specific commands. ```typescript // src/guards/maintenance.ts import { Guard } from '@/guards' // Apply to specific command @Slash({ name: 'mycommand' }) @Guard(Maintenance) async mycommand(interaction: CommandInteraction) { // Only executes if not in maintenance or user is dev } // Maintenance is also applied globally in events/interactionCreate.ts // Users see localized message: "The bot is currently in maintenance mode" // Control maintenance mode: import { setMaintenance, isInMaintenance } from '@/utils/functions' // Enable maintenance await setMaintenance(true) // Check status const inMaintenance = await isInMaintenance() // Disable maintenance await setMaintenance(false) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.