0.1.3 • Published 6 months ago
h3-discord-interactions v0.1.3
h3-discord-interactions
h3-discord-interactions is a Discord interactions handler optimized for h3-based applications (such as Nitro). It simplifies Discord interaction verification and response handling.
Features
- Optimized for h3-based applications (e.g., Nitro)
- Simplified implementation for Discord interaction verification and response handling
- TypeScript support
Installation
npm install h3-discord-interactions
Example
The following example demonstrates how to handle Discord interactions in a Nitro project route file (server/routes/index.post.ts):
import {
verifyWebhookRequest,
isPingRequest,
pongResponse,
isApplicationCommand,
textResponse,
} from 'h3-discord-interactions';
export default defineEventHandler(async (event) => {
// Verify the webhook request
const publicKey = 'your-public-key';
await verifyWebhookRequest(event, { publicKey });
// If it's a Ping request, return a Pong response
if (await isPingRequest(event)) {
return pongResponse();
}
// If it's not an ApplicationCommand request, throw an error
if (!(await isApplicationCommand(event))) {
throw createError({
statusCode: 400,
statusMessage: 'Invalid request',
});
}
// Return a text response
return textResponse('Hello World!');
});
API Reference
isVerified
Verifies if an interaction request is legitimate using Discord's verification system.
- Parameters:
- event: H3Event object containing the request details.
- publicKey: Your Discord application's public key.
- Returns: A Promise that resolves to true if verified, otherwise false.
verifyWebhookRequest
Verifies a webhook request and throws an error if the verification fails.
- Parameters:
- event: H3Event object containing the request details.
- publicKey: Your Discord application's public key.
- Throws: An error with a 401 status code if verification fails.
isPingRequest
Checks if the interaction is a Ping request from Discord.
- Parameters:
- event: H3Event object containing the request details.
- Returns: A Promise that resolves to true if it's a Ping request, otherwise false.
isApplicationCommand
Determines if the interaction is an application command.
- Parameters:
- event: H3Event object containing the request details.
- Returns: A Promise that resolves to true if it's an application command, otherwise false.
pongResponse
Creates a Pong response object for handling Ping requests.
- Returns: A Pong response object conforming to Discord's API specification.
textResponse
Creates a response object containing a specified text message.
- Parameters:
- content: The text message to be sent.
- Returns: A text message response object conforming to Discord's API specification.