mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-12 01:23:31 +01:00
feat(WebhookClient): allow creation of clients via URLs (#6192)
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const BaseClient = require('./BaseClient');
|
||||
const { Error } = require('../errors');
|
||||
const Webhook = require('../structures/Webhook');
|
||||
|
||||
/**
|
||||
@@ -10,17 +11,37 @@ const Webhook = require('../structures/Webhook');
|
||||
*/
|
||||
class WebhookClient extends BaseClient {
|
||||
/**
|
||||
* @param {Snowflake} id The webhook's id
|
||||
* @param {string} token Token of the webhook
|
||||
* The data for the webhook client containing either an id and token or just a URL
|
||||
* @typedef {Object} WebhookClientData
|
||||
* @property {Snowflake} [id] The id of the webhook
|
||||
* @property {string} [token] The token of the webhook
|
||||
* @property {string} [url] The full url for the webhook client
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {WebhookClientData} data The data of the webhook
|
||||
* @param {ClientOptions} [options] Options for the client
|
||||
* @example
|
||||
* // Create a new webhook and send a message
|
||||
* const hook = new Discord.WebhookClient('1234', 'abcdef');
|
||||
* const hook = new Discord.WebhookClient({ id: '1234', token: 'abcdef' });
|
||||
* hook.send('This will send a message').catch(console.error);
|
||||
*/
|
||||
constructor(id, token, options) {
|
||||
constructor(data, options) {
|
||||
super(options);
|
||||
Object.defineProperty(this, 'client', { value: this });
|
||||
let { id, token } = data;
|
||||
|
||||
if ('url' in data) {
|
||||
const url = data.url.match(
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
/^https?:\/\/(?:canary|ptb)?\.?discord\.com\/api\/webhooks(?:\/v[0-9]\d*)?\/([^\/]+)\/([^\/]+)/i,
|
||||
);
|
||||
|
||||
if (!url || url.length <= 1) throw new Error('WEBHOOK_URL_INVALID');
|
||||
|
||||
[, id, token] = url;
|
||||
}
|
||||
|
||||
this.id = id;
|
||||
Object.defineProperty(this, 'token', { value: token, writable: true, configurable: true });
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ const Messages = {
|
||||
|
||||
WEBHOOK_MESSAGE: 'The message was not sent by a webhook.',
|
||||
WEBHOOK_TOKEN_UNAVAILABLE: 'This action requires a webhook token, but none is available.',
|
||||
WEBHOOK_URL_INVALID: 'The provided webhook URL is not valid.',
|
||||
MESSAGE_REFERENCE_MISSING: 'The message does not reference another message',
|
||||
|
||||
EMOJI_TYPE: 'Emoji must be a string or GuildEmoji/ReactionEmoji',
|
||||
|
||||
Reference in New Issue
Block a user