UNPKG

@tycrek/discord-hookr

Version:

A lightweight and easy way to send webhooks to Discord, without the added baggage of a full API client.

93 lines (92 loc) 3.03 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Webhook = void 0; const api_1 = require("./api"); const EmbedBuilder_1 = require("./EmbedBuilder"); const buildHttpError = (res) => new Error(`Error: Received HTTP ${res.status} ${res.statusText} from Discord API.`); const catchAxiosError = (reject, { response, request, message }) => { // Request was made, server responded with non-2xx status code if (response) reject(buildHttpError(response)); // Request was made but no response was received else if (request) reject(new Error(`Error: No response received`)); // General error else reject(new Error(`Error: ${message}`)); }; class Webhook { hookUrl; payload = {}; constructor(webhookUrl) { this.hookUrl = webhookUrl; } ; setContent(content) { this.payload.content = content; return this; } setUsername(username) { this.payload.username = username; return this; } setAvatar(avatarUrl) { this.payload.avatar_url = avatarUrl; return this; } setTts(tts) { this.payload.tts = tts; return this; } setAllowedMentions(allowedMentions) { this.payload.allowed_mentions = allowedMentions; return this; } setComponents(components) { this.payload.components = components; return this; } setPayloadJson(payloadJson) { this.payload.payload_json = payloadJson; return this; } setFlags(flags) { this.payload.flags = flags; return this; } setThreadName(threadName) { this.payload.thread_name = threadName; return this; } addAttachment(attachment) { if (!this.payload.attachments) this.payload.attachments = []; this.payload.attachments.push(attachment); return this; } addEmbed(embed) { if (!this.payload.embeds) this.payload.embeds = []; if (Array.isArray(embed)) embed.forEach((e) => this.payload.embeds.push((e instanceof EmbedBuilder_1.EmbedBuilder) ? e.getEmbed() : e)); else this.payload.embeds.push((embed instanceof EmbedBuilder_1.EmbedBuilder) ? embed.getEmbed() : embed); return this; } sendFile(filePath, username, avatarUrl) { return new Promise((resolve, reject) => (0, api_1.sendFile)(this.hookUrl, filePath, username, avatarUrl) .then(() => resolve(void 0)) .catch((err) => catchAxiosError(reject, err))); } sendText(text) { this.payload.content = text; return this.send(); } send() { return new Promise((resolve, reject) => (0, api_1.sendWebhook)(this.hookUrl, this.payload) .then(() => resolve(void 0)) .catch((err) => catchAxiosError(reject, err))); } } exports.Webhook = Webhook; ;