copy eslint + tslint from Discord.js (v13)

This commit is contained in:
March 7th
2022-04-16 17:44:43 +07:00
parent 7fc069f4b9
commit 522f7f756a
64 changed files with 9164 additions and 9003 deletions

3
.eslintignore Normal file
View File

@@ -0,0 +1,3 @@
{
"ignorePatterns": ["node_modules/*"],
}

285
.eslintrc.json Normal file
View File

@@ -0,0 +1,285 @@
{
"extends": [
"eslint:recommended",
"plugin:prettier/recommended"
],
"plugins": [
"import"
],
"parserOptions": {
"ecmaVersion": 2021
},
"env": {
"es2021": true,
"node": true
},
"rules": {
"import/order": [
"error",
{
"groups": [
"builtin",
"external",
"internal",
"index",
"sibling",
"parent"
],
"alphabetize": {
"order": "asc"
}
}
],
"prettier/prettier": [
2,
{
"printWidth": 120,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "all",
"endOfLine": "lf",
"arrowParens": "avoid"
}
],
"strict": [
"error",
"global"
],
"no-await-in-loop": "warn",
"no-compare-neg-zero": "error",
"no-template-curly-in-string": "error",
"no-unsafe-negation": "error",
"valid-jsdoc": [
"error",
{
"requireReturn": false,
"requireReturnDescription": false,
"prefer": {
"return": "returns",
"arg": "param"
},
"preferType": {
"String": "string",
"Number": "number",
"Boolean": "boolean",
"Symbol": "symbol",
"object": "Object",
"function": "Function",
"array": "Array",
"date": "Date",
"error": "Error",
"null": "void"
}
}
],
"accessor-pairs": "warn",
"array-callback-return": "error",
"consistent-return": "error",
"curly": [
"error",
"multi-line",
"consistent"
],
"dot-location": [
"error",
"property"
],
"dot-notation": "error",
"eqeqeq": "error",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"no-lone-blocks": "error",
"no-multi-spaces": "error",
"no-new-func": "error",
"no-new-wrappers": "error",
"no-new": "error",
"no-octal-escape": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-throw-literal": "error",
"no-unmodified-loop-condition": "error",
"no-unused-expressions": "error",
"no-useless-call": "error",
"no-useless-concat": "error",
"no-useless-escape": "error",
"no-useless-return": "error",
"no-void": "error",
"no-warning-comments": "warn",
"prefer-promise-reject-errors": "error",
"require-await": "warn",
"wrap-iife": "error",
"yoda": "error",
"no-label-var": "error",
"no-shadow": "error",
"no-undef-init": "error",
"callback-return": "error",
"getter-return": "off",
"handle-callback-err": "error",
"no-mixed-requires": "error",
"no-new-require": "error",
"no-path-concat": "error",
"array-bracket-spacing": "error",
"block-spacing": "error",
"brace-style": [
"error",
"1tbs",
{
"allowSingleLine": true
}
],
"capitalized-comments": [
"error",
"always",
{
"ignoreConsecutiveComments": true
}
],
"comma-dangle": [
"error",
"always-multiline"
],
"comma-spacing": "error",
"comma-style": "error",
"computed-property-spacing": "error",
"consistent-this": [
"error",
"$this"
],
"eol-last": "error",
"func-names": "error",
"func-name-matching": "error",
"func-style": [
"error",
"declaration",
{
"allowArrowFunctions": true
}
],
"key-spacing": "error",
"keyword-spacing": "error",
"max-depth": "error",
"max-len": [
"error",
120,
2
],
"max-nested-callbacks": [
"error",
{
"max": 4
}
],
"max-statements-per-line": [
"error",
{
"max": 2
}
],
"new-cap": "off",
"newline-per-chained-call": [
"error",
{
"ignoreChainWithDepth": 3
}
],
"no-array-constructor": "error",
"no-inline-comments": "off",
"no-lonely-if": "error",
"no-multiple-empty-lines": [
"error",
{
"max": 2,
"maxEOF": 1,
"maxBOF": 0
}
],
"no-new-object": "error",
"no-spaced-func": "error",
"no-trailing-spaces": "error",
"no-unneeded-ternary": "error",
"no-whitespace-before-property": "error",
"nonblock-statement-body-position": "error",
"object-curly-spacing": [
"error",
"always"
],
"operator-assignment": "error",
"padded-blocks": [
"error",
"never"
],
"quote-props": [
"error",
"as-needed"
],
"quotes": [
"error",
"single",
{
"avoidEscape": true,
"allowTemplateLiterals": true
}
],
"semi-spacing": "error",
"semi": "error",
"space-before-blocks": "error",
"space-before-function-paren": [
"error",
{
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}
],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"template-tag-spacing": "error",
"unicode-bom": "error",
"arrow-body-style": "error",
"arrow-parens": [
"error",
"as-needed"
],
"arrow-spacing": "error",
"no-duplicate-imports": "error",
"no-useless-computed-key": "error",
"no-useless-constructor": "error",
"prefer-arrow-callback": "error",
"prefer-numeric-literals": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error",
"no-restricted-globals": [
"error",
{
"name": "Buffer",
"message": "Import Buffer from `node:buffer` instead"
},
{
"name": "process",
"message": "Import process from `node:process` instead"
},
{
"name": "setTimeout",
"message": "Import setTimeout from `node:timers` instead"
},
{
"name": "setInterval",
"message": "Import setInterval from `node:timers` instead"
},
{
"name": "setImmediate",
"message": "Import setImmediate from `node:timers` instead"
}
]
}
}

8
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
time: "12:00"
open-pull-requests-limit: 15

24
.github/workflows/lint.yml vendored Normal file
View File

@@ -0,0 +1,24 @@
name: Lint
on:
push:
branches:
- '*'
pull_request:
branches:
- '*'
jobs:
eslint:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run lint:all

7
.prettierrc.json Normal file
View File

@@ -0,0 +1,7 @@
{
"singleQuote": true,
"printWidth": 120,
"trailingComma": "all",
"endOfLine": "lf",
"arrowParens": "avoid"
}

View File

@@ -5,7 +5,12 @@
"main": "./src/index.js",
"types": "./typings/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"lint:typings": "tslint typings/index.d.ts",
"format": "prettier --write src/**/*.js typings/**/*.ts",
"lint:all": "npm run lint && npm run lint:typings"
},
"files": [
"src",

View File

@@ -244,44 +244,41 @@ class Client extends BaseClient {
* Update Cloudflare Cookie and Discord Fingerprint
*/
async updateCookie() {
/* Auto find fingerprint and add Cookie */
let cookie = '';
await require('axios')({
method: 'get',
url: 'https://discord.com/api/v9/experiments',
headers: this.options.http.headers,
})
.then((res) => {
if (!'set-cookie' in res.headers) return;
res.headers['set-cookie'].map((line) => {
line.split('; ').map((arr) => {
if (
arr.startsWith('Expires') ||
arr.startsWith('Path') ||
arr.startsWith('Domain') ||
arr.startsWith('HttpOnly') ||
arr.startsWith('Secure') ||
arr.startsWith('Max-Age') ||
arr.startsWith('SameSite')
) {
return;
} else {
cookie += `${arr}; `;
}
});
});
this.options.http.headers['Cookie'] = `${cookie}locale=en`;
this.options.http.headers['x-fingerprint'] = res.data.fingerprint;
this.emit(Events.DEBUG, `Added Cookie: ${cookie}`);
this.emit(Events.DEBUG, `Added Fingerprint: ${res.data.fingerprint}`);
})
.catch((err) => {
this.emit(
Events.DEBUG,
`Finding Cookie and Fingerprint failed: ${err.message}`,
);
});
}
/* Auto find fingerprint and add Cookie */
let cookie = '';
await require('axios')({
method: 'get',
url: 'https://discord.com/api/v9/experiments',
headers: this.options.http.headers,
})
.then(res => {
if (!'set-cookie' in res.headers) return;
res.headers['set-cookie'].map(line => {
line.split('; ').map(arr => {
if (
arr.startsWith('Expires') ||
arr.startsWith('Path') ||
arr.startsWith('Domain') ||
arr.startsWith('HttpOnly') ||
arr.startsWith('Secure') ||
arr.startsWith('Max-Age') ||
arr.startsWith('SameSite')
) {
return;
} else {
cookie += `${arr}; `;
}
});
});
this.options.http.headers['Cookie'] = `${cookie}locale=en`;
this.options.http.headers['x-fingerprint'] = res.data.fingerprint;
this.emit(Events.DEBUG, `Added Cookie: ${cookie}`);
this.emit(Events.DEBUG, `Added Fingerprint: ${res.data.fingerprint}`);
})
.catch(err => {
this.emit(Events.DEBUG, `Finding Cookie and Fingerprint failed: ${err.message}`);
});
}
/**
* Logs the client in, establishing a WebSocket connection to Discord.

View File

@@ -60,7 +60,10 @@ class InteractionCreateAction extends Action {
InteractionType = AutocompleteInteraction;
break;
default:
client.emit(Events.DEBUG, `[INTERACTION] Received [BOT] / Send (Selfbot) interactionID ${data.id} with unknown type: ${data.type}`);
client.emit(
Events.DEBUG,
`[INTERACTION] Received [BOT] / Send (Selfbot) interactionID ${data.id} with unknown type: ${data.type}`,
);
return;
}

View File

@@ -217,7 +217,7 @@ class WebSocketManager extends EventEmitter {
this.shardQueue.add(shard);
if (shard.sessionId) {
this.debug(`Session id is present, attempting an immediate reconnect...`, shard);
this.debug('Session id is present, attempting an immediate reconnect...', shard);
this.reconnect();
} else {
shard.destroy({ reset: true, emit: false, log: false });
@@ -279,7 +279,7 @@ class WebSocketManager extends EventEmitter {
} catch (error) {
this.debug(`Couldn't reconnect or fetch information about the gateway. ${error}`);
if (error.httpStatus !== 401) {
this.debug(`Possible network error occurred. Retrying in 5s...`);
this.debug('Possible network error occurred. Retrying in 5s...');
await sleep(5_000);
this.reconnecting = false;
return this.reconnect();

View File

@@ -13,7 +13,7 @@ let zlib;
try {
zlib = require('zlib-sync');
} catch { } // eslint-disable-line no-empty
} catch {} // eslint-disable-line no-empty
/**
* Represents a Shard's WebSocket connection
@@ -487,8 +487,9 @@ class WebSocketShard extends EventEmitter {
() => {
this.debug(
`Shard ${hasGuildsIntent ? 'did' : 'will'} not receive any more guild packets` +
`${hasGuildsIntent ? ` in ${waitGuildTimeout} ms` : ''}.\nUnavailable guild count: ${this.expectedGuilds.size
}`,
`${hasGuildsIntent ? ` in ${waitGuildTimeout} ms` : ''}.\nUnavailable guild count: ${
this.expectedGuilds.size
}`,
);
this.readyTimeout = null;

View File

@@ -1,10 +1,10 @@
'use strict';
module.exports = (client, { d: data }) => {
if (!data.application_commands[0]) return;
for (const command of data.application_commands) {
const user = client.users.cache.get(command.application_id);
if (!user) continue;
user.applications._add(command, true);
};
if (!data.application_commands[0]) return;
for (const command of data.application_commands) {
const user = client.users.cache.get(command.application_id);
if (!user) continue;
user.applications._add(command, true);
}
};

View File

@@ -4,32 +4,34 @@ const { Collection } = require('@discordjs/collection');
const { Events } = require('../../../util/Constants');
module.exports = (client, { d: data }) => {
// console.log(data);
// console.log(data.ops[0])
const guild = client.guilds.cache.get(data.guild_id);
if (!guild) return;
const members = new Collection();
// Get Member from side Discord Channel (online counting if large server)
for (const object of data.ops) {
if (object.op == 'SYNC') {
for (const member_ of object.items) {
const member = member_.member;
if (!member) continue;
members.set(member.user.id, guild.members._add(member));
if (member.presence)
guild.presences._add(Object.assign(member.presence, { guild }));
}
} else if (object.op == 'INVALIDATE') {
console.warn(`Invalidate [${object.range[0]}, ${object.range[1]}]`);
} else if (object.op == 'UPDATE' || object.op == 'INSERT') {
const member = object.item.member;
if (!member) continue;
members.set(member.user.id, guild.members._add(member));
if (member.presence)
guild.presences._add(Object.assign(member.presence, { guild }));
} else if (object.op == 'DELETE') {
// nothing;
// console.log(data);
// console.log(data.ops[0])
const guild = client.guilds.cache.get(data.guild_id);
if (!guild) return;
const members = new Collection();
// Get Member from side Discord Channel (online counting if large server)
for (const object of data.ops) {
if (object.op == 'SYNC') {
for (const member_ of object.items) {
const member = member_.member;
if (!member) continue;
members.set(member.user.id, guild.members._add(member));
if (member.presence) {
guild.presences._add(Object.assign(member.presence, { guild }));
}
}
} else if (object.op == 'INVALIDATE') {
console.warn(`Invalidate [${object.range[0]}, ${object.range[1]}]`);
} else if (object.op == 'UPDATE' || object.op == 'INSERT') {
const member = object.item.member;
if (!member) continue;
members.set(member.user.id, guild.members._add(member));
if (member.presence) {
guild.presences._add(Object.assign(member.presence, { guild }));
}
} else if (object.op == 'DELETE') {
// nothing;
}
client.emit(Events.GUILD_MEMBER_LIST_UPDATE, members, guild, data);
}
client.emit(Events.GUILD_MEMBER_LIST_UPDATE, members, guild, data);
};

View File

@@ -2,6 +2,6 @@
const { Events } = require('../../../util/Constants');
module.exports = (client, packet) => {
if (client.user.bot) client.actions.InteractionCreate.handle(packet.d);
if (client.user.bot) client.actions.InteractionCreate.handle(packet.d);
else client.emit(Events.INTERACTION_CREATE, packet.d);
};

View File

@@ -2,5 +2,5 @@
const { Events } = require('../../../util/Constants');
module.exports = (client, { d: data }) => {
client.emit(Events.INTERACTION_FAILED, data);
client.emit(Events.INTERACTION_FAILED, data);
};

View File

@@ -2,5 +2,5 @@
const { Events } = require('../../../util/Constants');
module.exports = (client, { d: data }) => {
client.emit(Events.INTERACTION_SUCCESS, data);
client.emit(Events.INTERACTION_SUCCESS, data);
};

View File

@@ -1,5 +1,5 @@
'use strict';
module.exports = (client, { d: data }) => {
// client.user.messageMentions.delete(data.channel_id);
// client.user.messageMentions.delete(data.channel_id);
};

View File

@@ -5,112 +5,99 @@ const chalk = require('chalk');
const axios = require('axios');
const Discord = require('../../../index');
const RichPresence = require('discord-rpc-contructor');
const { ChannelTypes } = require('../../../util/Constants');
const checkUpdate = async () => {
const res_ = await axios.get(
`https://registry.npmjs.com/${encodeURIComponent(
'discord.js-selfbot-v13',
)}`,
);
const lastest_tag = res_.data['dist-tags'].latest;
// Checking if the package is outdated
// Stable version
if (lastest_tag !== Discord.version && Discord.version.includes('-') == false) {
return console.log(`${chalk.yellowBright(
'[WARNING]',
)} New Discord.js-selfbot-v13 version.
Old Version: ${chalk.redBright(
Discord.version,
)} => New Version: ${chalk.greenBright(lastest_tag)}`);
}
return console.log(
`${chalk.greenBright(
'[OK]',
)} Discord.js-selfbot-v13 is up to date. Version: ${chalk.blueBright(
Discord.version,
)}`,
);
const res_ = await axios.get(`https://registry.npmjs.com/${encodeURIComponent('discord.js-selfbot-v13')}`);
const lastest_tag = res_.data['dist-tags'].latest;
// Checking if the package is outdated
// Stable version
if (lastest_tag !== Discord.version && Discord.version.includes('-') == false) {
return console.log(`${chalk.yellowBright('[WARNING]')} New Discord.js-selfbot-v13 version.
Old Version: ${chalk.redBright(Discord.version)} => New Version: ${chalk.greenBright(lastest_tag)}`);
}
return console.log(
`${chalk.greenBright('[OK]')} Discord.js-selfbot-v13 is up to date. Version: ${chalk.blueBright(Discord.version)}`,
);
};
const customStatusAuto = async (client) => {
let custom_status;
if (
client.setting.rawSetting.custom_status?.text ||
res.rawSetting.custom_status?.emoji_name
) {
custom_status = new RichPresence.CustomStatus();
if (client.setting.rawSetting.custom_status.emoji_id) {
const emoji = await client.emojis.resolve(
client.setting.rawSetting.custom_status.emoji_id,
);
if (emoji) custom_status.setDiscordEmoji(emoji);
} else {
custom_status.setUnicodeEmoji(
client.setting.rawSetting.custom_status.emoji_name,
);
}
custom_status.setState(client.setting.rawSetting.custom_status?.text);
client.user.setPresence({
activities: custom_status ? [custom_status.toDiscord()] : [],
status: client.setting.rawSetting.status,
});
}
}
const customStatusAuto = async client => {
let custom_status;
if (client.setting.rawSetting.custom_status?.text || res.rawSetting.custom_status?.emoji_name) {
custom_status = new RichPresence.CustomStatus();
if (client.setting.rawSetting.custom_status.emoji_id) {
const emoji = await client.emojis.resolve(client.setting.rawSetting.custom_status.emoji_id);
if (emoji) custom_status.setDiscordEmoji(emoji);
} else {
custom_status.setUnicodeEmoji(client.setting.rawSetting.custom_status.emoji_name);
}
custom_status.setState(client.setting.rawSetting.custom_status?.text);
client.user.setPresence({
activities: custom_status ? [custom_status.toDiscord()] : [],
status: client.setting.rawSetting.status,
});
}
};
module.exports = (client, { d: data }, shard) => {
if (client.options.checkUpdate) {
try {
checkUpdate();
} catch (e) {
console.log(e);
}
}
client.session_id = data.session_id;
if (client.user) {
client.user._patch(data.user);
} else {
ClientUser ??= require('../../../structures/ClientUser');
client.user = new ClientUser(client, data.user);
client.users.cache.set(client.user.id, client.user);
}
console.log(data.private_channels);
if (client.options.checkUpdate) {
try {
checkUpdate();
} catch (e) {
console.log(e);
}
}
client.session_id = data.session_id;
if (client.user) {
client.user._patch(data.user);
} else {
ClientUser ??= require('../../../structures/ClientUser');
client.user = new ClientUser(client, data.user);
client.users.cache.set(client.user.id, client.user);
}
client.user.setAFK(false);
client.user.setAFK(false);
client.setting._patch(data.user_settings);
client.setting._patch(data.user_settings);
client.user.connectedAccounts = data.connected_accounts ?? [];
client.user.connectedAccounts = data.connected_accounts ?? [];
for (const [userid, note] of Object.entries(data.notes)) {
client.user.notes.set(userid, note);
}
for (const [userid, note] of Object.entries(data.notes)) {
client.user.notes.set(userid, note);
}
if (client.options.readyStatus) {
customStatusAuto(client);
}
for (const private_channel of data.private_channels) {
client.channels._add(private_channel);
}
/**
* read_state: Return Array:
* {
* mention_count: 14, // ok it's ping count
* last_pin_timestamp: '1970-01-01T00:00:00+00:00', // why discord ?
* last_message_id: 0, // :)
* id: '840218426969817119' // channel id
* },
*/
if (client.options.readyStatus) {
customStatusAuto(client);
}
/*
/**
* read_state: Return Array:
* {
* mention_count: 14, // ok it's ping count
* last_pin_timestamp: '1970-01-01T00:00:00+00:00', // why discord ?
* last_message_id: 0, // :)
* id: '840218426969817119' // channel id
* },
*/
/*
for (const object of data.read_state) {
if (object.mention_count == 0) continue;
client.user.messageMentions.set(object.id, object);
}
*/
for (const guild of data.guilds) {
guild.shardId = shard.id;
client.guilds._add(guild);
}
for (const guild of data.guilds) {
guild.shardId = shard.id;
client.guilds._add(guild);
}
client.relationships._setup(data.relationships);
client.relationships._setup(data.relationships);
shard.checkReady();
shard.checkReady();
};

View File

@@ -3,13 +3,13 @@
const { Events } = require('../../../util/Constants');
module.exports = (client, { d: data }) => {
data.user ? client.users._add(data.user) : null;
client.relationships.cache.set(data.id, data.type);
/**
* Emitted whenever a relationship is updated.
* @event Client#relationshipUpdate
* @param {UserID} user The userID that was updated
* @param {Number} type The new relationship type
*/
client.emit(Events.RELATIONSHIP_ADD, data.id, data.type);
data.user ? client.users._add(data.user) : null;
client.relationships.cache.set(data.id, data.type);
/**
* Emitted whenever a relationship is updated.
* @event Client#relationshipUpdate
* @param {UserID} user The userID that was updated
* @param {Number} type The new relationship type
*/
client.emit(Events.RELATIONSHIP_ADD, data.id, data.type);
};

View File

@@ -3,11 +3,11 @@
const { Events } = require('../../../util/Constants');
module.exports = (client, { d: data }) => {
client.relationships.cache.delete(data.id);
/**
* Emitted whenever a relationship is updated.
* @event Client#relationshipUpdate
* @param {UserID} user The userID that was updated
*/
client.emit(Events.RELATIONSHIP_REMOVE, data.id);
client.relationships.cache.delete(data.id);
/**
* Emitted whenever a relationship is updated.
* @event Client#relationshipUpdate
* @param {UserID} user The userID that was updated
*/
client.emit(Events.RELATIONSHIP_REMOVE, data.id);
};

View File

@@ -1,5 +1,5 @@
'use strict';
module.exports = (client, { d: data }) => {
client.user.notes.set(data.id, data.note);
client.user.notes.set(data.id, data.note);
};

View File

@@ -1,5 +1,5 @@
'use strict';
module.exports = (client, { d: data }) => {
client.setting._patch(data);
client.setting._patch(data);
};

View File

@@ -1,80 +1,71 @@
'use strict';
const handlers = Object.fromEntries([
['READY', require('./READY')],
['RESUMED', require('./RESUMED')],
['RELATIONSHIP_ADD', require('./RELATIONSHIP_ADD')],
['RELATIONSHIP_REMOVE', require('./RELATIONSHIP_REMOVE')],
['APPLICATION_COMMAND_CREATE', require('./APPLICATION_COMMAND_CREATE')],
['APPLICATION_COMMAND_DELETE', require('./APPLICATION_COMMAND_DELETE')],
['APPLICATION_COMMAND_UPDATE', require('./APPLICATION_COMMAND_UPDATE')],
['GUILD_CREATE', require('./GUILD_CREATE')],
['GUILD_DELETE', require('./GUILD_DELETE')],
['GUILD_UPDATE', require('./GUILD_UPDATE')],
['INVITE_CREATE', require('./INVITE_CREATE')],
['INVITE_DELETE', require('./INVITE_DELETE')],
['GUILD_MEMBER_ADD', require('./GUILD_MEMBER_ADD')],
['GUILD_MEMBER_REMOVE', require('./GUILD_MEMBER_REMOVE')],
['GUILD_MEMBER_UPDATE', require('./GUILD_MEMBER_UPDATE')],
['GUILD_MEMBERS_CHUNK', require('./GUILD_MEMBERS_CHUNK')],
['GUILD_MEMBER_LIST_UPDATE', require('./GUILD_MEMBER_LIST_UPDATE.js')],
[
'GUILD_APPLICATION_COMMANDS_UPDATE',
require('./GUILD_APPLICATION_COMMANDS_UPDATE.js'),
],
['GUILD_INTEGRATIONS_UPDATE', require('./GUILD_INTEGRATIONS_UPDATE')],
['GUILD_ROLE_CREATE', require('./GUILD_ROLE_CREATE')],
['GUILD_ROLE_DELETE', require('./GUILD_ROLE_DELETE')],
['GUILD_ROLE_UPDATE', require('./GUILD_ROLE_UPDATE')],
['GUILD_BAN_ADD', require('./GUILD_BAN_ADD')],
['GUILD_BAN_REMOVE', require('./GUILD_BAN_REMOVE')],
['GUILD_EMOJIS_UPDATE', require('./GUILD_EMOJIS_UPDATE')],
['CHANNEL_CREATE', require('./CHANNEL_CREATE')],
['CHANNEL_DELETE', require('./CHANNEL_DELETE')],
['CHANNEL_UPDATE', require('./CHANNEL_UPDATE')],
['CHANNEL_PINS_UPDATE', require('./CHANNEL_PINS_UPDATE')],
['MESSAGE_CREATE', require('./MESSAGE_CREATE')],
['MESSAGE_DELETE', require('./MESSAGE_DELETE')],
['MESSAGE_UPDATE', require('./MESSAGE_UPDATE')],
['MESSAGE_DELETE_BULK', require('./MESSAGE_DELETE_BULK')],
['MESSAGE_REACTION_ADD', require('./MESSAGE_REACTION_ADD')],
['MESSAGE_REACTION_REMOVE', require('./MESSAGE_REACTION_REMOVE')],
['MESSAGE_REACTION_REMOVE_ALL', require('./MESSAGE_REACTION_REMOVE_ALL')],
['MESSAGE_REACTION_REMOVE_EMOJI', require('./MESSAGE_REACTION_REMOVE_EMOJI')],
['THREAD_CREATE', require('./THREAD_CREATE')],
['THREAD_UPDATE', require('./THREAD_UPDATE')],
['THREAD_DELETE', require('./THREAD_DELETE')],
['THREAD_LIST_SYNC', require('./THREAD_LIST_SYNC')],
['THREAD_MEMBER_UPDATE', require('./THREAD_MEMBER_UPDATE')],
['THREAD_MEMBERS_UPDATE', require('./THREAD_MEMBERS_UPDATE')],
['USER_SETTINGS_UPDATE', require('./USER_SETTINGS_UPDATE')], // opcode 0
// USER_SETTINGS_PROTO_UPDATE // opcode 0
['MESSAGE_ACK', require('./MESSAGE_ACK')],
['USER_NOTE_UPDATE', require('./USER_NOTE_UPDATE')],
['USER_UPDATE', require('./USER_UPDATE')],
['PRESENCE_UPDATE', require('./PRESENCE_UPDATE')],
['TYPING_START', require('./TYPING_START')],
['VOICE_STATE_UPDATE', require('./VOICE_STATE_UPDATE')],
['VOICE_SERVER_UPDATE', require('./VOICE_SERVER_UPDATE')],
['WEBHOOKS_UPDATE', require('./WEBHOOKS_UPDATE')],
['INTERACTION_CREATE', require('./INTERACTION_CREATE')],
['INTERACTION_SUCCESS', require('./INTERACTION_SUCCESS')],
['INTERACTION_FAILED', require('./INTERACTION_FAILED')],
['STAGE_INSTANCE_CREATE', require('./STAGE_INSTANCE_CREATE')],
['STAGE_INSTANCE_UPDATE', require('./STAGE_INSTANCE_UPDATE')],
['STAGE_INSTANCE_DELETE', require('./STAGE_INSTANCE_DELETE')],
['GUILD_STICKERS_UPDATE', require('./GUILD_STICKERS_UPDATE')],
['GUILD_SCHEDULED_EVENT_CREATE', require('./GUILD_SCHEDULED_EVENT_CREATE')],
['GUILD_SCHEDULED_EVENT_UPDATE', require('./GUILD_SCHEDULED_EVENT_UPDATE')],
['GUILD_SCHEDULED_EVENT_DELETE', require('./GUILD_SCHEDULED_EVENT_DELETE')],
[
'GUILD_SCHEDULED_EVENT_USER_ADD',
require('./GUILD_SCHEDULED_EVENT_USER_ADD'),
],
[
'GUILD_SCHEDULED_EVENT_USER_REMOVE',
require('./GUILD_SCHEDULED_EVENT_USER_REMOVE'),
],
['READY', require('./READY')],
['RESUMED', require('./RESUMED')],
['RELATIONSHIP_ADD', require('./RELATIONSHIP_ADD')],
['RELATIONSHIP_REMOVE', require('./RELATIONSHIP_REMOVE')],
['APPLICATION_COMMAND_CREATE', require('./APPLICATION_COMMAND_CREATE')],
['APPLICATION_COMMAND_DELETE', require('./APPLICATION_COMMAND_DELETE')],
['APPLICATION_COMMAND_UPDATE', require('./APPLICATION_COMMAND_UPDATE')],
['GUILD_CREATE', require('./GUILD_CREATE')],
['GUILD_DELETE', require('./GUILD_DELETE')],
['GUILD_UPDATE', require('./GUILD_UPDATE')],
['INVITE_CREATE', require('./INVITE_CREATE')],
['INVITE_DELETE', require('./INVITE_DELETE')],
['GUILD_MEMBER_ADD', require('./GUILD_MEMBER_ADD')],
['GUILD_MEMBER_REMOVE', require('./GUILD_MEMBER_REMOVE')],
['GUILD_MEMBER_UPDATE', require('./GUILD_MEMBER_UPDATE')],
['GUILD_MEMBERS_CHUNK', require('./GUILD_MEMBERS_CHUNK')],
['GUILD_MEMBER_LIST_UPDATE', require('./GUILD_MEMBER_LIST_UPDATE.js')],
['GUILD_APPLICATION_COMMANDS_UPDATE', require('./GUILD_APPLICATION_COMMANDS_UPDATE.js')],
['GUILD_INTEGRATIONS_UPDATE', require('./GUILD_INTEGRATIONS_UPDATE')],
['GUILD_ROLE_CREATE', require('./GUILD_ROLE_CREATE')],
['GUILD_ROLE_DELETE', require('./GUILD_ROLE_DELETE')],
['GUILD_ROLE_UPDATE', require('./GUILD_ROLE_UPDATE')],
['GUILD_BAN_ADD', require('./GUILD_BAN_ADD')],
['GUILD_BAN_REMOVE', require('./GUILD_BAN_REMOVE')],
['GUILD_EMOJIS_UPDATE', require('./GUILD_EMOJIS_UPDATE')],
['CHANNEL_CREATE', require('./CHANNEL_CREATE')],
['CHANNEL_DELETE', require('./CHANNEL_DELETE')],
['CHANNEL_UPDATE', require('./CHANNEL_UPDATE')],
['CHANNEL_PINS_UPDATE', require('./CHANNEL_PINS_UPDATE')],
['MESSAGE_CREATE', require('./MESSAGE_CREATE')],
['MESSAGE_DELETE', require('./MESSAGE_DELETE')],
['MESSAGE_UPDATE', require('./MESSAGE_UPDATE')],
['MESSAGE_DELETE_BULK', require('./MESSAGE_DELETE_BULK')],
['MESSAGE_REACTION_ADD', require('./MESSAGE_REACTION_ADD')],
['MESSAGE_REACTION_REMOVE', require('./MESSAGE_REACTION_REMOVE')],
['MESSAGE_REACTION_REMOVE_ALL', require('./MESSAGE_REACTION_REMOVE_ALL')],
['MESSAGE_REACTION_REMOVE_EMOJI', require('./MESSAGE_REACTION_REMOVE_EMOJI')],
['THREAD_CREATE', require('./THREAD_CREATE')],
['THREAD_UPDATE', require('./THREAD_UPDATE')],
['THREAD_DELETE', require('./THREAD_DELETE')],
['THREAD_LIST_SYNC', require('./THREAD_LIST_SYNC')],
['THREAD_MEMBER_UPDATE', require('./THREAD_MEMBER_UPDATE')],
['THREAD_MEMBERS_UPDATE', require('./THREAD_MEMBERS_UPDATE')],
['USER_SETTINGS_UPDATE', require('./USER_SETTINGS_UPDATE')], // Opcode 0
// USER_SETTINGS_PROTO_UPDATE // opcode 0
['MESSAGE_ACK', require('./MESSAGE_ACK')],
['USER_NOTE_UPDATE', require('./USER_NOTE_UPDATE')],
['USER_UPDATE', require('./USER_UPDATE')],
['PRESENCE_UPDATE', require('./PRESENCE_UPDATE')],
['TYPING_START', require('./TYPING_START')],
['VOICE_STATE_UPDATE', require('./VOICE_STATE_UPDATE')],
['VOICE_SERVER_UPDATE', require('./VOICE_SERVER_UPDATE')],
['WEBHOOKS_UPDATE', require('./WEBHOOKS_UPDATE')],
['INTERACTION_CREATE', require('./INTERACTION_CREATE')],
['INTERACTION_SUCCESS', require('./INTERACTION_SUCCESS')],
['INTERACTION_FAILED', require('./INTERACTION_FAILED')],
['STAGE_INSTANCE_CREATE', require('./STAGE_INSTANCE_CREATE')],
['STAGE_INSTANCE_UPDATE', require('./STAGE_INSTANCE_UPDATE')],
['STAGE_INSTANCE_DELETE', require('./STAGE_INSTANCE_DELETE')],
['GUILD_STICKERS_UPDATE', require('./GUILD_STICKERS_UPDATE')],
['GUILD_SCHEDULED_EVENT_CREATE', require('./GUILD_SCHEDULED_EVENT_CREATE')],
['GUILD_SCHEDULED_EVENT_UPDATE', require('./GUILD_SCHEDULED_EVENT_UPDATE')],
['GUILD_SCHEDULED_EVENT_DELETE', require('./GUILD_SCHEDULED_EVENT_DELETE')],
['GUILD_SCHEDULED_EVENT_USER_ADD', require('./GUILD_SCHEDULED_EVENT_USER_ADD')],
['GUILD_SCHEDULED_EVENT_USER_REMOVE', require('./GUILD_SCHEDULED_EVENT_USER_REMOVE')],
]);
module.exports = handlers;

View File

@@ -3,210 +3,173 @@
const { register } = require('./DJSError');
const Messages = {
CLIENT_INVALID_OPTION: (prop, must) => `The ${prop} option must be ${must}`,
CLIENT_INVALID_PROVIDED_SHARDS: 'None of the provided shards were valid.',
CLIENT_MISSING_INTENTS: 'Valid intents must be provided for the Client.',
CLIENT_NOT_READY: (action) =>
`The client needs to be logged in to ${action}.`,
CLIENT_INVALID_OPTION: (prop, must) => `The ${prop} option must be ${must}`,
CLIENT_INVALID_PROVIDED_SHARDS: 'None of the provided shards were valid.',
CLIENT_MISSING_INTENTS: 'Valid intents must be provided for the Client.',
CLIENT_NOT_READY: action => `The client needs to be logged in to ${action}.`,
TOKEN_INVALID: 'An invalid token was provided.',
TOKEN_MISSING:
'Request to use token, but token was unavailable to the client.',
TOKEN_INVALID: 'An invalid token was provided.',
TOKEN_MISSING: 'Request to use token, but token was unavailable to the client.',
WS_CLOSE_REQUESTED: 'WebSocket closed due to user request.',
WS_CONNECTION_EXISTS: 'There is already an existing WebSocket connection.',
WS_NOT_OPEN: (data = 'data') => `WebSocket not open to send ${data}`,
MANAGER_DESTROYED: 'Manager was destroyed.',
WS_CLOSE_REQUESTED: 'WebSocket closed due to user request.',
WS_CONNECTION_EXISTS: 'There is already an existing WebSocket connection.',
WS_NOT_OPEN: (data = 'data') => `WebSocket not open to send ${data}`,
MANAGER_DESTROYED: 'Manager was destroyed.',
BITFIELD_INVALID: (bit) => `Invalid bitfield flag or number: ${bit}.`,
BITFIELD_INVALID: bit => `Invalid bitfield flag or number: ${bit}.`,
SHARDING_INVALID: 'Invalid shard settings were provided.',
SHARDING_REQUIRED:
'This session would have handled too many guilds - Sharding is required.',
INVALID_INTENTS: 'Invalid intent provided for WebSocket intents.',
DISALLOWED_INTENTS:
'Privileged intent provided is not enabled or whitelisted.',
SHARDING_NO_SHARDS: 'No shards have been spawned.',
SHARDING_IN_PROCESS: 'Shards are still being spawned.',
SHARDING_INVALID_EVAL_BROADCAST: 'Script to evaluate must be a function',
SHARDING_SHARD_NOT_FOUND: (id) => `Shard ${id} could not be found.`,
SHARDING_ALREADY_SPAWNED: (count) => `Already spawned ${count} shards.`,
SHARDING_PROCESS_EXISTS: (id) => `Shard ${id} already has an active process.`,
SHARDING_WORKER_EXISTS: (id) => `Shard ${id} already has an active worker.`,
SHARDING_READY_TIMEOUT: (id) =>
`Shard ${id}'s Client took too long to become ready.`,
SHARDING_READY_DISCONNECTED: (id) =>
`Shard ${id}'s Client disconnected before becoming ready.`,
SHARDING_READY_DIED: (id) =>
`Shard ${id}'s process exited before its Client became ready.`,
SHARDING_NO_CHILD_EXISTS: (id) =>
`Shard ${id} has no active process or worker.`,
SHARDING_SHARD_MISCALCULATION: (shard, guild, count) =>
`Calculated invalid shard ${shard} for guild ${guild} with ${count} shards.`,
SHARDING_INVALID: 'Invalid shard settings were provided.',
SHARDING_REQUIRED: 'This session would have handled too many guilds - Sharding is required.',
INVALID_INTENTS: 'Invalid intent provided for WebSocket intents.',
DISALLOWED_INTENTS: 'Privileged intent provided is not enabled or whitelisted.',
SHARDING_NO_SHARDS: 'No shards have been spawned.',
SHARDING_IN_PROCESS: 'Shards are still being spawned.',
SHARDING_INVALID_EVAL_BROADCAST: 'Script to evaluate must be a function',
SHARDING_SHARD_NOT_FOUND: id => `Shard ${id} could not be found.`,
SHARDING_ALREADY_SPAWNED: count => `Already spawned ${count} shards.`,
SHARDING_PROCESS_EXISTS: id => `Shard ${id} already has an active process.`,
SHARDING_WORKER_EXISTS: id => `Shard ${id} already has an active worker.`,
SHARDING_READY_TIMEOUT: id => `Shard ${id}'s Client took too long to become ready.`,
SHARDING_READY_DISCONNECTED: id => `Shard ${id}'s Client disconnected before becoming ready.`,
SHARDING_READY_DIED: id => `Shard ${id}'s process exited before its Client became ready.`,
SHARDING_NO_CHILD_EXISTS: id => `Shard ${id} has no active process or worker.`,
SHARDING_SHARD_MISCALCULATION: (shard, guild, count) =>
`Calculated invalid shard ${shard} for guild ${guild} with ${count} shards.`,
COLOR_RANGE: 'Color must be within the range 0 - 16777215 (0xFFFFFF).',
COLOR_CONVERT: 'Unable to convert color to a number.',
COLOR_RANGE: 'Color must be within the range 0 - 16777215 (0xFFFFFF).',
COLOR_CONVERT: 'Unable to convert color to a number.',
INVITE_OPTIONS_MISSING_CHANNEL:
'A valid guild channel must be provided when GuildScheduledEvent is EXTERNAL.',
INVITE_OPTIONS_MISSING_CHANNEL: 'A valid guild channel must be provided when GuildScheduledEvent is EXTERNAL.',
EMBED_TITLE: 'MessageEmbed title must be a string.',
EMBED_FIELD_NAME: 'MessageEmbed field names must be non-empty strings.',
EMBED_FIELD_VALUE: 'MessageEmbed field values must be non-empty strings.',
EMBED_FOOTER_TEXT: 'MessageEmbed footer text must be a string.',
EMBED_DESCRIPTION: 'MessageEmbed description must be a string.',
EMBED_AUTHOR_NAME: 'MessageEmbed author name must be a string.',
/* add */
EMBED_PROVIDER_NAME: 'MessageEmbed provider name must be a string.',
EMBED_TITLE: 'MessageEmbed title must be a string.',
EMBED_FIELD_NAME: 'MessageEmbed field names must be non-empty strings.',
EMBED_FIELD_VALUE: 'MessageEmbed field values must be non-empty strings.',
EMBED_FOOTER_TEXT: 'MessageEmbed footer text must be a string.',
EMBED_DESCRIPTION: 'MessageEmbed description must be a string.',
EMBED_AUTHOR_NAME: 'MessageEmbed author name must be a string.',
/* add */
EMBED_PROVIDER_NAME: 'MessageEmbed provider name must be a string.',
BUTTON_LABEL: 'MessageButton label must be a string',
BUTTON_URL: 'MessageButton URL must be a string',
BUTTON_CUSTOM_ID: 'MessageButton customId must be a string',
BUTTON_LABEL: 'MessageButton label must be a string',
BUTTON_URL: 'MessageButton URL must be a string',
BUTTON_CUSTOM_ID: 'MessageButton customId must be a string',
SELECT_MENU_CUSTOM_ID: 'MessageSelectMenu customId must be a string',
SELECT_MENU_PLACEHOLDER: 'MessageSelectMenu placeholder must be a string',
SELECT_OPTION_LABEL: 'MessageSelectOption label must be a string',
SELECT_OPTION_VALUE: 'MessageSelectOption value must be a string',
SELECT_OPTION_DESCRIPTION: 'MessageSelectOption description must be a string',
SELECT_MENU_CUSTOM_ID: 'MessageSelectMenu customId must be a string',
SELECT_MENU_PLACEHOLDER: 'MessageSelectMenu placeholder must be a string',
SELECT_OPTION_LABEL: 'MessageSelectOption label must be a string',
SELECT_OPTION_VALUE: 'MessageSelectOption value must be a string',
SELECT_OPTION_DESCRIPTION: 'MessageSelectOption description must be a string',
INTERACTION_COLLECTOR_ERROR: (reason) =>
`Collector received no interactions before ending with reason: ${reason}`,
INTERACTION_COLLECTOR_ERROR: reason => `Collector received no interactions before ending with reason: ${reason}`,
FILE_NOT_FOUND: (file) => `File could not be found: ${file}`,
FILE_NOT_FOUND: file => `File could not be found: ${file}`,
USER_BANNER_NOT_FETCHED:
"You must fetch this user's banner before trying to generate its URL!",
USER_NO_DM_CHANNEL: 'No DM Channel exists!',
USER_BANNER_NOT_FETCHED: "You must fetch this user's banner before trying to generate its URL!",
USER_NO_DM_CHANNEL: 'No DM Channel exists!',
VOICE_NOT_STAGE_CHANNEL: 'You are only allowed to do this in stage channels.',
VOICE_NOT_STAGE_CHANNEL: 'You are only allowed to do this in stage channels.',
VOICE_STATE_NOT_OWN:
'You cannot self-deafen/mute/request to speak on VoiceStates that do not belong to the ClientUser.',
VOICE_STATE_INVALID_TYPE: (name) => `${name} must be a boolean.`,
VOICE_STATE_NOT_OWN:
'You cannot self-deafen/mute/request to speak on VoiceStates that do not belong to the ClientUser.',
VOICE_STATE_INVALID_TYPE: name => `${name} must be a boolean.`,
REQ_RESOURCE_TYPE:
'The resource must be a string, Buffer or a valid file stream.',
REQ_RESOURCE_TYPE: 'The resource must be a string, Buffer or a valid file stream.',
IMAGE_FORMAT: (format) => `Invalid image format: ${format}`,
IMAGE_SIZE: (size) => `Invalid image size: ${size}`,
IMAGE_FORMAT: format => `Invalid image format: ${format}`,
IMAGE_SIZE: size => `Invalid image size: ${size}`,
MESSAGE_BULK_DELETE_TYPE:
'The messages must be an Array, Collection, or number.',
MESSAGE_NONCE_TYPE: 'Message nonce must be an integer or a string.',
MESSAGE_CONTENT_TYPE: 'Message content must be a non-empty string.',
MESSAGE_BULK_DELETE_TYPE: 'The messages must be an Array, Collection, or number.',
MESSAGE_NONCE_TYPE: 'Message nonce must be an integer or a string.',
MESSAGE_CONTENT_TYPE: 'Message content must be a non-empty string.',
SPLIT_MAX_LEN:
'Chunk exceeds the max length and contains no split characters.',
SPLIT_MAX_LEN: 'Chunk exceeds the max length and contains no split characters.',
BAN_RESOLVE_ID: (ban = false) =>
`Couldn't resolve the user id to ${ban ? 'ban' : 'unban'}.`,
FETCH_BAN_RESOLVE_ID: "Couldn't resolve the user id to fetch the ban.",
BAN_RESOLVE_ID: (ban = false) => `Couldn't resolve the user id to ${ban ? 'ban' : 'unban'}.`,
FETCH_BAN_RESOLVE_ID: "Couldn't resolve the user id to fetch the ban.",
PRUNE_DAYS_TYPE: 'Days must be a number',
PRUNE_DAYS_TYPE: 'Days must be a number',
GUILD_CHANNEL_RESOLVE: 'Could not resolve channel to a guild channel.',
GUILD_VOICE_CHANNEL_RESOLVE:
'Could not resolve channel to a guild voice channel.',
GUILD_CHANNEL_ORPHAN: 'Could not find a parent to this guild channel.',
GUILD_CHANNEL_UNOWNED:
"The fetched channel does not belong to this manager's guild.",
GUILD_OWNED: 'Guild is owned by the client.',
GUILD_MEMBERS_TIMEOUT: "Members didn't arrive in time.",
GUILD_UNCACHED_ME: 'The client user as a member of this guild is uncached.',
CHANNEL_NOT_CACHED:
'Could not find the channel where this message came from in the cache!',
STAGE_CHANNEL_RESOLVE: 'Could not resolve channel to a stage channel.',
GUILD_SCHEDULED_EVENT_RESOLVE: 'Could not resolve the guild scheduled event.',
GUILD_CHANNEL_RESOLVE: 'Could not resolve channel to a guild channel.',
GUILD_VOICE_CHANNEL_RESOLVE: 'Could not resolve channel to a guild voice channel.',
GUILD_CHANNEL_ORPHAN: 'Could not find a parent to this guild channel.',
GUILD_CHANNEL_UNOWNED: "The fetched channel does not belong to this manager's guild.",
GUILD_OWNED: 'Guild is owned by the client.',
GUILD_MEMBERS_TIMEOUT: "Members didn't arrive in time.",
GUILD_UNCACHED_ME: 'The client user as a member of this guild is uncached.',
CHANNEL_NOT_CACHED: 'Could not find the channel where this message came from in the cache!',
STAGE_CHANNEL_RESOLVE: 'Could not resolve channel to a stage channel.',
GUILD_SCHEDULED_EVENT_RESOLVE: 'Could not resolve the guild scheduled event.',
INVALID_TYPE: (name, expected, an = false) =>
`Supplied ${name} is not a${an ? 'n' : ''} ${expected}.`,
INVALID_ELEMENT: (type, name, elem) =>
`Supplied ${type} ${name} includes an invalid element: ${elem}`,
INVALID_TYPE: (name, expected, an = false) => `Supplied ${name} is not a${an ? 'n' : ''} ${expected}.`,
INVALID_ELEMENT: (type, name, elem) => `Supplied ${type} ${name} includes an invalid element: ${elem}`,
MESSAGE_THREAD_PARENT:
'The message was not sent in a guild text or news channel',
MESSAGE_EXISTING_THREAD: 'The message already has a thread',
THREAD_INVITABLE_TYPE: (type) => `Invitable cannot be edited on ${type}`,
MESSAGE_THREAD_PARENT: 'The message was not sent in a guild text or news channel',
MESSAGE_EXISTING_THREAD: 'The message already has a thread',
THREAD_INVITABLE_TYPE: type => `Invitable cannot be edited on ${type}`,
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.',
WEBHOOK_APPLICATION:
'This message webhook belongs to an application and cannot be fetched.',
MESSAGE_REFERENCE_MISSING: 'The message does not reference another message',
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.',
WEBHOOK_APPLICATION: 'This message webhook belongs to an application and cannot be fetched.',
MESSAGE_REFERENCE_MISSING: 'The message does not reference another message',
EMOJI_TYPE: 'Emoji must be a string or GuildEmoji/ReactionEmoji',
EMOJI_MANAGED: 'Emoji is managed and has no Author.',
MISSING_MANAGE_EMOJIS_AND_STICKERS_PERMISSION: (guild) =>
`Client must have Manage Emojis and Stickers permission in guild ${guild} to see emoji authors.`,
NOT_GUILD_STICKER:
'Sticker is a standard (non-guild) sticker and has no author.',
EMOJI_TYPE: 'Emoji must be a string or GuildEmoji/ReactionEmoji',
EMOJI_MANAGED: 'Emoji is managed and has no Author.',
MISSING_MANAGE_EMOJIS_AND_STICKERS_PERMISSION: guild =>
`Client must have Manage Emojis and Stickers permission in guild ${guild} to see emoji authors.`,
NOT_GUILD_STICKER: 'Sticker is a standard (non-guild) sticker and has no author.',
REACTION_RESOLVE_USER:
"Couldn't resolve the user id to remove from the reaction.",
REACTION_RESOLVE_USER: "Couldn't resolve the user id to remove from the reaction.",
VANITY_URL: 'This guild does not have the VANITY_URL feature enabled.',
VANITY_URL: 'This guild does not have the VANITY_URL feature enabled.',
INVITE_RESOLVE_CODE: 'Could not resolve the code to fetch the invite.',
INVITE_RESOLVE_CODE: 'Could not resolve the code to fetch the invite.',
INVITE_NOT_FOUND: 'Could not find the requested invite.',
INVITE_NOT_FOUND: 'Could not find the requested invite.',
NOT_OWNER_GROUP_DM_CHANNEL: "You can't do this action [Missing Permission]",
USER_ALREADY_IN_GROUP_DM_CHANNEL: 'User is already in the channel.',
USER_NOT_IN_GROUP_DM_CHANNEL: 'User is not in the channel.',
NOT_OWNER_GROUP_DM_CHANNEL: "You can't do this action [Missing Permission]",
USER_ALREADY_IN_GROUP_DM_CHANNEL: 'User is already in the channel.',
USER_NOT_IN_GROUP_DM_CHANNEL: 'User is not in the channel.',
DELETE_GROUP_DM_CHANNEL:
"Bots don't have access to Group DM Channels and cannot delete them",
FETCH_GROUP_DM_CHANNEL:
"Bots don't have access to Group DM Channels and cannot fetch them",
DELETE_GROUP_DM_CHANNEL: "Bots don't have access to Group DM Channels and cannot delete them",
FETCH_GROUP_DM_CHANNEL: "Bots don't have access to Group DM Channels and cannot fetch them",
MEMBER_FETCH_NONCE_LENGTH: 'Nonce length must not exceed 32 characters.',
MEMBER_FETCH_NONCE_LENGTH: 'Nonce length must not exceed 32 characters.',
GLOBAL_COMMAND_PERMISSIONS:
'Permissions for global commands may only be fetched or modified by providing a GuildResolvable ' +
"or from a guild's application command manager.",
GUILD_UNCACHED_ROLE_RESOLVE:
'Cannot resolve roles from an arbitrary guild, provide an id instead',
GLOBAL_COMMAND_PERMISSIONS:
'Permissions for global commands may only be fetched or modified by providing a GuildResolvable ' +
"or from a guild's application command manager.",
GUILD_UNCACHED_ROLE_RESOLVE: 'Cannot resolve roles from an arbitrary guild, provide an id instead',
INTERACTION_ALREADY_REPLIED:
'The reply to this interaction has already been sent or deferred.',
INTERACTION_NOT_REPLIED:
'The reply to this interaction has not been sent or deferred.',
INTERACTION_EPHEMERAL_REPLIED: 'Ephemeral responses cannot be deleted.',
INTERACTION_ALREADY_REPLIED: 'The reply to this interaction has already been sent or deferred.',
INTERACTION_NOT_REPLIED: 'The reply to this interaction has not been sent or deferred.',
INTERACTION_EPHEMERAL_REPLIED: 'Ephemeral responses cannot be deleted.',
COMMAND_INTERACTION_OPTION_NOT_FOUND: (name) =>
`Required option "${name}" not found.`,
COMMAND_INTERACTION_OPTION_TYPE: (name, type, expected) =>
`Option "${name}" is of type: ${type}; expected ${expected}.`,
COMMAND_INTERACTION_OPTION_EMPTY: (name, type) =>
`Required option "${name}" is of type: ${type}; expected a non-empty value.`,
COMMAND_INTERACTION_OPTION_NO_SUB_COMMAND:
'No subcommand specified for interaction.',
COMMAND_INTERACTION_OPTION_NO_SUB_COMMAND_GROUP:
'No subcommand group specified for interaction.',
AUTOCOMPLETE_INTERACTION_OPTION_NO_FOCUSED_OPTION:
'No focused option for autocomplete interaction.',
COMMAND_INTERACTION_OPTION_NOT_FOUND: name => `Required option "${name}" not found.`,
COMMAND_INTERACTION_OPTION_TYPE: (name, type, expected) =>
`Option "${name}" is of type: ${type}; expected ${expected}.`,
COMMAND_INTERACTION_OPTION_EMPTY: (name, type) =>
`Required option "${name}" is of type: ${type}; expected a non-empty value.`,
COMMAND_INTERACTION_OPTION_NO_SUB_COMMAND: 'No subcommand specified for interaction.',
COMMAND_INTERACTION_OPTION_NO_SUB_COMMAND_GROUP: 'No subcommand group specified for interaction.',
AUTOCOMPLETE_INTERACTION_OPTION_NO_FOCUSED_OPTION: 'No focused option for autocomplete interaction.',
INVITE_MISSING_SCOPES:
'At least one valid scope must be provided for the invite',
INVITE_MISSING_SCOPES: 'At least one valid scope must be provided for the invite',
NOT_IMPLEMENTED: (what, name) => `Method ${what} not implemented on ${name}.`,
NOT_IMPLEMENTED: (what, name) => `Method ${what} not implemented on ${name}.`,
SWEEP_FILTER_RETURN:
'The return value of the sweepFilter function was not false or a Function',
SWEEP_FILTER_RETURN: 'The return value of the sweepFilter function was not false or a Function',
INVALID_BOT_METHOD: `Bot accounts cannot use this method`,
INVALID_USER_METHOD: `User accounts cannot use this method`,
INVALID_LOCALE: 'Unable to select this location',
FOLDER_NOT_FOUND: 'Server directory not found',
FOLDER_POSITION_INVALID: 'The server index in the directory is invalid',
APPLICATION_ID_INVALID: "The application isn't BOT",
INVALID_NITRO: 'Invalid Nitro Code',
MESSAGE_ID_NOT_FOUND: 'Message ID not found',
MESSAGE_EMBED_LINK_LENGTH:
'Message content with embed link length is too long',
GUILD_MEMBERS_FETCH: (msg) => `${msg}`
INVALID_BOT_METHOD: 'Bot accounts cannot use this method',
INVALID_USER_METHOD: 'User accounts cannot use this method',
INVALID_LOCALE: 'Unable to select this location',
FOLDER_NOT_FOUND: 'Server directory not found',
FOLDER_POSITION_INVALID: 'The server index in the directory is invalid',
APPLICATION_ID_INVALID: "The application isn't BOT",
INVALID_NITRO: 'Invalid Nitro Code',
MESSAGE_ID_NOT_FOUND: 'Message ID not found',
MESSAGE_EMBED_LINK_LENGTH: 'Message content with embed link length is too long',
GUILD_MEMBERS_FETCH: msg => `${msg}`,
};
for (const [name, message] of Object.entries(Messages)) register(name, message);

View File

@@ -117,7 +117,7 @@ class ApplicationCommandManager extends CachedManager {
* .catch(console.error);
*/
async create(command, guildId) {
if(!this.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.client.user.bot) throw new Error('INVALID_USER_METHOD');
const data = await this.commandPath({ guildId }).post({
data: this.constructor.transformCommand(command),
});
@@ -147,7 +147,7 @@ class ApplicationCommandManager extends CachedManager {
* .catch(console.error);
*/
async set(commands, guildId) {
if(!this.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.client.user.bot) throw new Error('INVALID_USER_METHOD');
const data = await this.commandPath({ guildId }).put({
data: commands.map(c => this.constructor.transformCommand(c)),
});
@@ -170,7 +170,7 @@ class ApplicationCommandManager extends CachedManager {
* .catch(console.error);
*/
async edit(command, data, guildId) {
if(!this.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.client.user.bot) throw new Error('INVALID_USER_METHOD');
const id = this.resolveId(command);
if (!id) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable');
@@ -193,7 +193,7 @@ class ApplicationCommandManager extends CachedManager {
* .catch(console.error);
*/
async delete(command, guildId) {
if(!this.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.client.user.bot) throw new Error('INVALID_USER_METHOD');
const id = this.resolveId(command);
if (!id) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable');

View File

@@ -49,7 +49,10 @@ class ApplicationCommandPermissionsManager extends BaseManager {
* @private
*/
permissionsPath(guildId, commandId) {
return this.client.api.applications(typeof this.user == 'string' ? this.user : this.user.id).guilds(guildId).commands(commandId).permissions;
return this.client.api
.applications(typeof this.user == 'string' ? this.user : this.user.id)
.guilds(guildId)
.commands(commandId).permissions;
}
/**
@@ -161,7 +164,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
* .catch(console.error);
*/
async set({ guild, command, permissions, fullPermissions } = {}) {
if(!this.manager.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.manager.client.user.bot) throw new Error('INVALID_USER_METHOD');
const { guildId, commandId } = this._validateOptions(guild, command);
if (commandId) {
@@ -223,7 +226,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
* .catch(console.error);
*/
async add({ guild, command, permissions }) {
if(!this.manager.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.manager.client.user.bot) throw new Error('INVALID_USER_METHOD');
const { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable');
if (!Array.isArray(permissions)) {
@@ -275,13 +278,13 @@ class ApplicationCommandPermissionsManager extends BaseManager {
* .catch(console.error);
*/
async remove({ guild, command, users, roles }) {
if(!this.manager.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.manager.client.user.bot) throw new Error('INVALID_USER_METHOD');
const { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable');
if (!users && !roles) throw new TypeError('INVALID_TYPE', 'users OR roles', 'Array or Resolvable', true);
let resolvedIds = [];
const resolvedIds = [];
if (Array.isArray(users)) {
users.forEach(user => {
const userId = this.client.users.resolveId(user);

View File

@@ -132,8 +132,8 @@ class ChannelManager extends CachedManager {
console.log(recipients);
if (recipients.length < 2 || recipients.length > 9) throw new Error('Invalid Users length (2 - 9)');
const data = await this.client.api.users['@me'].channels.post({
data: { recipients: recipients.map((r) => r.id) },
});
data: { recipients: recipients.map(r => r.id) },
});
return this._add(data, null, { cache: true, allowUnknownGuild: true });
}
}

View File

@@ -4,364 +4,336 @@ const CachedManager = require('./CachedManager');
const { default: Collection } = require('@discordjs/collection');
const { Error, TypeError } = require('../errors/DJSError');
const { remove } = require('lodash');
const { localeObject, DMScanLevel, stickerAnimationMode } = require('../util/Constants')
const { localeObject, DMScanLevel, stickerAnimationMode } = require('../util/Constants');
/**
* Manages API methods for users and stores their cache.
* @extends {CachedManager}
*/
class ClientUserSettingManager extends CachedManager {
constructor(client, iterable) {
super(client);
// Raw data
this.rawSetting = {};
// Language
this.locale = null;
// Setting => ACTIVITY SETTINGS => Activity Status => Display current activity as a status message
this.activityDisplay = null;
//
this.disableDMfromServer = new Collection();
// Allow direct messages from server members
this.DMfromServerMode = null;
//
this.displayImage = null;
//
this.linkedImageDisplay = null;
// Setting => APP SETTINGS => Accessibility => Automatically play GIFs when Discord is focused.
this.autoplayGIF = null;
// Show embeds and preview website links pasted into chat
this.previewLink = null;
// Setting => APP SETTINGS => Accessibility => Play Animated Emojis
this.animatedEmojis = null;
// Setting => APP SETTINGS => Accessibility => Text-to-speech => Allow playback
this.allowTTS = null;
// Setting => APP SETTINGS => Appearance => Message Display => Compact Mode [OK]
this.compactMode = null;
// Setting => APP SETTINGS => Text & Images => Emoji => Convert Emoticons
this.convertEmoticons = null;
// SAFE DIRECT MESSAGING
this.DMScanLevel = null;
// Setting => APP SETTINGS => Appearance => Theme [OK]
this.theme = '';
//
this.developerMode = null;
//
this.afkTimeout = null;
//
this.stickerAnimationMode = null;
// WHO CAN ADD YOU AS A FRIEND ?
this.addFriendFrom = {
all: null,
mutual_friends: null,
mutual_guilds: null,
};
// Setting => APP SETTINGS => Text & Images => Emoji => Show emoji reactions
this.showEmojiReactions = null;
// Custom Stauts [It's not working now]
this.customStatus = null;
// Guild folder and position
this.guildMetadata = new Collection();
// Todo: add new method from Discum
}
/**
*
* @param {Object} data Raw Data to patch
* @extends https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/discum/user/user.py
* @private
*/
_patch(data) {
this.rawSetting = Object.assign(this.rawSetting, data);
if ('locale' in data) {
this.locale = localeObject[data.locale];
}
if ('show_current_game' in data) {
this.activityDisplay = data.show_current_game;
}
if ('default_guilds_restricted' in data) {
this.DMfromServerMode = data.default_guilds_restricted;
}
if ('inline_attachment_media' in data) {
this.displayImage = data.inline_attachment_media;
}
if ('inline_embed_media' in data) {
this.linkedImageDisplay = data.inline_embed_media;
}
if ('gif_auto_play' in data) {
this.autoplayGIF = data.gif_auto_play;
}
if ('render_embeds' in data) {
this.previewLink = data.render_embeds;
}
if ('animate_emoji' in data) {
this.animatedEmojis = data.animate_emoji;
}
if ('enable_tts_command' in data) {
this.allowTTS = data.enable_tts_command;
}
if ('message_display_compact' in data) {
this.compactMode = data.message_display_compact;
}
if ('convert_emoticons' in data) {
this.convertEmoticons = data.convert_emoticons;
}
if ('explicit_content_filter' in data) {
this.DMScanLevel = DMScanLevel[data.explicit_content_filter];
}
if ('theme' in data) {
this.theme = data.theme;
}
if ('developer_mode' in data) {
this.developerMode = data.developer_mode;
}
if ('afk_timeout' in data) {
this.afkTimeout = data.afk_timeout * 1000; // second => milisecond
}
if ('animate_stickers' in data) {
this.stickerAnimationMode = stickerAnimationMode[data.animate_stickers];
}
if ('render_reactions' in data) {
this.showEmojiReactions = data.render_reactions;
}
if ('custom_status' in data) {
this.customStatus = data.custom_status || {}; // Thanks PinkDuwc._#3443 reported this issue
this.customStatus.status = data.status;
}
if ('friend_source_flags' in data) {
this.addFriendFrom = {
all: data.friend_source_flags.all || false,
mutual_friends:
data.friend_source_flags.all ? true : data.friend_source_flags.mutual_friends,
mutual_guilds:
data.friend_source_flags.all ? true : data.friend_source_flags.mutual_guilds,
};
}
if ('guild_folders' in data) {
const data_ = data.guild_positions.map((guildId, i) => {
// Find folder
const folderIndex = data.guild_folders.findIndex((obj) =>
obj.guild_ids.includes(guildId),
);
const metadata = {
guildId: guildId,
guildIndex: i,
folderId: data.guild_folders[folderIndex]?.id,
folderIndex,
folderName: data.guild_folders[folderIndex]?.name,
folderColor: data.guild_folders[folderIndex]?.color,
folderGuilds: data.guild_folders[folderIndex]?.guild_ids,
};
return [guildId, metadata];
});
this.guildMetadata = new Collection(data_);
}
if ('restricted_guilds' in data) {
data.restricted_guilds.map((guildId) => {
const guild = this.client.guilds.cache.get(guildId);
if (!guild) return;
guild.disableDM = true;
this.disableDMfromServer.set(guildId, true);
});
}
}
async fetch() {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
try {
const data = await this.client.api.users('@me').settings.get();
this._patch(data);
return this;
} catch (e) {
throw e;
}
}
/**
* Edit data
* @param {Object} data Data to edit
* @private
*/
async edit(data) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
try {
const res = await this.client.api.users('@me').settings.patch({ data });
this._patch(res);
return this;
} catch (e) {
throw e;
}
}
/**
* Set compact mode
* @param {Boolean | null} value Compact mode enable or disable
* @returns {Boolean}
*/
async setDisplayCompactMode(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
if (
typeof value !== 'boolean' &&
typeof value !== 'null' &&
typeof value !== 'undefined'
)
throw new TypeError(
'INVALID_TYPE',
'value',
'boolean | null | undefined',
true,
);
if (!value) value = !this.compactMode;
if (value !== this.compactMode) {
await this.edit({ message_display_compact: value });
}
return this.compactMode;
}
/**
* Discord Theme
* @param {null |dark |light} value Theme to set
* @returns {theme}
*/
async setTheme(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
const validValues = ['dark', 'light'];
if (
typeof value !== 'string' &&
typeof value !== 'null' &&
typeof value !== 'undefined'
)
throw new TypeError(
'INVALID_TYPE',
'value',
'string | null | undefined',
true,
);
if (!validValues.includes(value)) {
value == validValues[0]
? (value = validValues[1])
: (value = validValues[0]);
}
if (value !== this.theme) {
await this.edit({ theme: value });
}
return this.theme;
}
/**
* * Locale Setting, must be one of:
* * `DANISH`
* * `GERMAN`
* * `ENGLISH_UK`
* * `ENGLISH_US`
* * `SPANISH`
* * `FRENCH`
* * `CROATIAN`
* * `ITALIAN`
* * `LITHUANIAN`
* * `HUNGARIAN`
* * `DUTCH`
* * `NORWEGIAN`
* * `POLISH`
* * `BRAZILIAN_PORTUGUESE`
* * `ROMANIA_ROMANIAN`
* * `FINNISH`
* * `SWEDISH`
* * `VIETNAMESE`
* * `TURKISH`
* * `CZECH`
* * `GREEK`
* * `BULGARIAN`
* * `RUSSIAN`
* * `UKRAINIAN`
* * `HINDI`
* * `THAI`
* * `CHINA_CHINESE`
* * `JAPANESE`
* * `TAIWAN_CHINESE`
* * `KOREAN`
* @param {string} value
* @returns {locale}
*/
async setLocale(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
if (typeof value !== 'string')
throw new TypeError('INVALID_TYPE', 'value', 'string', true);
if (!localeObject[value]) throw new Error('INVALID_LOCALE');
if (localeObject[value] !== this.locale) {
await this.edit({ locale: localeObject[value] });
}
return this.locale;
}
// TODO: Guild positions & folders
// Change Index in Array [Hidden]
/**
*
* @param {Array} array Array
* @param {Number} from Index1
* @param {Number} to Index2
* @returns {Array}
* @private
*/
_move(array, from, to) {
array.splice(to, 0, array.splice(from, 1)[0]);
return array;
}
// TODO: Move Guild
// folder to folder
// folder to home
// home to home
// home to folder
/**
* Change Guild Position (from * to Folder or Home)
* @param {GuildIDResolve} guildId guild.id
* @param {Number} newPosition Guild Position
* * **WARNING**: Type = `FOLDER`, newPosition is the guild's index in the Folder.
* @param {number} type Move to folder or home
* * `FOLDER`: 1
* * `HOME`: 2
* @param {FolderID} folderId If you want to move to folder
* @private
*/
async guildChangePosition(guildId, newPosition, type, folderId) {
// get Guild default position
// Escape
const oldGuildFolderPosition = this.rawSetting.guild_folders.findIndex(
(value) => value.guild_ids.includes(guildId),
);
const newGuildFolderPosition = this.rawSetting.guild_folders.findIndex(
(value) =>
value.guild_ids.includes(this.rawSetting.guild_positions[newPosition]),
);
if (type == 2 || `${type}`.toUpperCase() == 'HOME') {
// Delete GuildID from Folder and create new Folder
// Check it is folder
const folder = this.rawSetting.guild_folders[oldGuildFolderPosition];
if (folder.id) {
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids =
this.rawSetting.guild_folders[
oldGuildFolderPosition
].guild_ids.filter((v) => v !== guildId);
}
this.rawSetting.guild_folders = this._move(
this.rawSetting.guild_folders,
oldGuildFolderPosition,
newGuildFolderPosition,
);
this.rawSetting.guild_folders[newGuildFolderPosition].id = null;
} else if (type == 1 || `${type}`.toUpperCase() == 'FOLDER') {
// Delete GuildID from oldFolder
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids =
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids.filter(
(v) => v !== guildId,
);
// Index new Folder
const folderIndex = this.rawSetting.guild_folders.findIndex(
(value) => value.id == folderId,
);
const folder = this.rawSetting.guild_folders[folderIndex];
folder.guild_ids.push(guildId);
folder.guild_ids = [...new Set(folder.guild_ids)];
folder.guild_ids = this._move(
folder.guild_ids,
folder.guild_ids.findIndex((v) => v == guildId),
newPosition,
);
}
this.edit({ guild_folders: this.rawSetting.guild_folders });
}
constructor(client, iterable) {
super(client);
// Raw data
this.rawSetting = {};
// Language
this.locale = null;
// Setting => ACTIVITY SETTINGS => Activity Status => Display current activity as a status message
this.activityDisplay = null;
//
this.disableDMfromServer = new Collection();
// Allow direct messages from server members
this.DMfromServerMode = null;
//
this.displayImage = null;
//
this.linkedImageDisplay = null;
// Setting => APP SETTINGS => Accessibility => Automatically play GIFs when Discord is focused.
this.autoplayGIF = null;
// Show embeds and preview website links pasted into chat
this.previewLink = null;
// Setting => APP SETTINGS => Accessibility => Play Animated Emojis
this.animatedEmojis = null;
// Setting => APP SETTINGS => Accessibility => Text-to-speech => Allow playback
this.allowTTS = null;
// Setting => APP SETTINGS => Appearance => Message Display => Compact Mode [OK]
this.compactMode = null;
// Setting => APP SETTINGS => Text & Images => Emoji => Convert Emoticons
this.convertEmoticons = null;
// SAFE DIRECT MESSAGING
this.DMScanLevel = null;
// Setting => APP SETTINGS => Appearance => Theme [OK]
this.theme = '';
//
this.developerMode = null;
//
this.afkTimeout = null;
//
this.stickerAnimationMode = null;
// WHO CAN ADD YOU AS A FRIEND ?
this.addFriendFrom = {
all: null,
mutual_friends: null,
mutual_guilds: null,
};
// Setting => APP SETTINGS => Text & Images => Emoji => Show emoji reactions
this.showEmojiReactions = null;
// Custom Stauts [It's not working now]
this.customStatus = null;
// Guild folder and position
this.guildMetadata = new Collection();
// Todo: add new method from Discum
}
/**
*
* @param {Object} data Raw Data to patch
* @extends https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/discum/user/user.py
* @private
*/
_patch(data) {
this.rawSetting = Object.assign(this.rawSetting, data);
if ('locale' in data) {
this.locale = localeObject[data.locale];
}
if ('show_current_game' in data) {
this.activityDisplay = data.show_current_game;
}
if ('default_guilds_restricted' in data) {
this.DMfromServerMode = data.default_guilds_restricted;
}
if ('inline_attachment_media' in data) {
this.displayImage = data.inline_attachment_media;
}
if ('inline_embed_media' in data) {
this.linkedImageDisplay = data.inline_embed_media;
}
if ('gif_auto_play' in data) {
this.autoplayGIF = data.gif_auto_play;
}
if ('render_embeds' in data) {
this.previewLink = data.render_embeds;
}
if ('animate_emoji' in data) {
this.animatedEmojis = data.animate_emoji;
}
if ('enable_tts_command' in data) {
this.allowTTS = data.enable_tts_command;
}
if ('message_display_compact' in data) {
this.compactMode = data.message_display_compact;
}
if ('convert_emoticons' in data) {
this.convertEmoticons = data.convert_emoticons;
}
if ('explicit_content_filter' in data) {
this.DMScanLevel = DMScanLevel[data.explicit_content_filter];
}
if ('theme' in data) {
this.theme = data.theme;
}
if ('developer_mode' in data) {
this.developerMode = data.developer_mode;
}
if ('afk_timeout' in data) {
this.afkTimeout = data.afk_timeout * 1000; // second => milisecond
}
if ('animate_stickers' in data) {
this.stickerAnimationMode = stickerAnimationMode[data.animate_stickers];
}
if ('render_reactions' in data) {
this.showEmojiReactions = data.render_reactions;
}
if ('custom_status' in data) {
this.customStatus = data.custom_status || {}; // Thanks PinkDuwc._#3443 reported this issue
this.customStatus.status = data.status;
}
if ('friend_source_flags' in data) {
this.addFriendFrom = {
all: data.friend_source_flags.all || false,
mutual_friends: data.friend_source_flags.all ? true : data.friend_source_flags.mutual_friends,
mutual_guilds: data.friend_source_flags.all ? true : data.friend_source_flags.mutual_guilds,
};
}
if ('guild_folders' in data) {
const data_ = data.guild_positions.map((guildId, i) => {
// Find folder
const folderIndex = data.guild_folders.findIndex(obj => obj.guild_ids.includes(guildId));
const metadata = {
guildId: guildId,
guildIndex: i,
folderId: data.guild_folders[folderIndex]?.id,
folderIndex,
folderName: data.guild_folders[folderIndex]?.name,
folderColor: data.guild_folders[folderIndex]?.color,
folderGuilds: data.guild_folders[folderIndex]?.guild_ids,
};
return [guildId, metadata];
});
this.guildMetadata = new Collection(data_);
}
if ('restricted_guilds' in data) {
data.restricted_guilds.map(guildId => {
const guild = this.client.guilds.cache.get(guildId);
if (!guild) return;
guild.disableDM = true;
this.disableDMfromServer.set(guildId, true);
});
}
}
async fetch() {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
try {
const data = await this.client.api.users('@me').settings.get();
this._patch(data);
return this;
} catch (e) {
throw e;
}
}
/**
* Edit data
* @param {Object} data Data to edit
* @private
*/
async edit(data) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
try {
const res = await this.client.api.users('@me').settings.patch({ data });
this._patch(res);
return this;
} catch (e) {
throw e;
}
}
/**
* Set compact mode
* @param {Boolean | null} value Compact mode enable or disable
* @returns {Boolean}
*/
async setDisplayCompactMode(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
if (typeof value !== 'boolean' && typeof value !== 'null' && typeof value !== 'undefined') {
throw new TypeError('INVALID_TYPE', 'value', 'boolean | null | undefined', true);
}
if (!value) value = !this.compactMode;
if (value !== this.compactMode) {
await this.edit({ message_display_compact: value });
}
return this.compactMode;
}
/**
* Discord Theme
* @param {null |dark |light} value Theme to set
* @returns {theme}
*/
async setTheme(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
const validValues = ['dark', 'light'];
if (typeof value !== 'string' && typeof value !== 'null' && typeof value !== 'undefined') {
throw new TypeError('INVALID_TYPE', 'value', 'string | null | undefined', true);
}
if (!validValues.includes(value)) {
value == validValues[0] ? (value = validValues[1]) : (value = validValues[0]);
}
if (value !== this.theme) {
await this.edit({ theme: value });
}
return this.theme;
}
/**
* * Locale Setting, must be one of:
* * `DANISH`
* * `GERMAN`
* * `ENGLISH_UK`
* * `ENGLISH_US`
* * `SPANISH`
* * `FRENCH`
* * `CROATIAN`
* * `ITALIAN`
* * `LITHUANIAN`
* * `HUNGARIAN`
* * `DUTCH`
* * `NORWEGIAN`
* * `POLISH`
* * `BRAZILIAN_PORTUGUESE`
* * `ROMANIA_ROMANIAN`
* * `FINNISH`
* * `SWEDISH`
* * `VIETNAMESE`
* * `TURKISH`
* * `CZECH`
* * `GREEK`
* * `BULGARIAN`
* * `RUSSIAN`
* * `UKRAINIAN`
* * `HINDI`
* * `THAI`
* * `CHINA_CHINESE`
* * `JAPANESE`
* * `TAIWAN_CHINESE`
* * `KOREAN`
* @param {string} value
* @returns {locale}
*/
async setLocale(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
if (typeof value !== 'string') {
throw new TypeError('INVALID_TYPE', 'value', 'string', true);
}
if (!localeObject[value]) throw new Error('INVALID_LOCALE');
if (localeObject[value] !== this.locale) {
await this.edit({ locale: localeObject[value] });
}
return this.locale;
}
// TODO: Guild positions & folders
// Change Index in Array [Hidden]
/**
*
* @param {Array} array Array
* @param {Number} from Index1
* @param {Number} to Index2
* @returns {Array}
* @private
*/
_move(array, from, to) {
array.splice(to, 0, array.splice(from, 1)[0]);
return array;
}
// TODO: Move Guild
// folder to folder
// folder to home
// home to home
// home to folder
/**
* Change Guild Position (from * to Folder or Home)
* @param {GuildIDResolve} guildId guild.id
* @param {Number} newPosition Guild Position
* * **WARNING**: Type = `FOLDER`, newPosition is the guild's index in the Folder.
* @param {number} type Move to folder or home
* * `FOLDER`: 1
* * `HOME`: 2
* @param {FolderID} folderId If you want to move to folder
* @private
*/
async guildChangePosition(guildId, newPosition, type, folderId) {
// get Guild default position
// Escape
const oldGuildFolderPosition = this.rawSetting.guild_folders.findIndex(value => value.guild_ids.includes(guildId));
const newGuildFolderPosition = this.rawSetting.guild_folders.findIndex(value =>
value.guild_ids.includes(this.rawSetting.guild_positions[newPosition]),
);
if (type == 2 || `${type}`.toUpperCase() == 'HOME') {
// Delete GuildID from Folder and create new Folder
// Check it is folder
const folder = this.rawSetting.guild_folders[oldGuildFolderPosition];
if (folder.id) {
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids = this.rawSetting.guild_folders[
oldGuildFolderPosition
].guild_ids.filter(v => v !== guildId);
}
this.rawSetting.guild_folders = this._move(
this.rawSetting.guild_folders,
oldGuildFolderPosition,
newGuildFolderPosition,
);
this.rawSetting.guild_folders[newGuildFolderPosition].id = null;
} else if (type == 1 || `${type}`.toUpperCase() == 'FOLDER') {
// Delete GuildID from oldFolder
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids = this.rawSetting.guild_folders[
oldGuildFolderPosition
].guild_ids.filter(v => v !== guildId);
// Index new Folder
const folderIndex = this.rawSetting.guild_folders.findIndex(value => value.id == folderId);
const folder = this.rawSetting.guild_folders[folderIndex];
folder.guild_ids.push(guildId);
folder.guild_ids = [...new Set(folder.guild_ids)];
folder.guild_ids = this._move(
folder.guild_ids,
folder.guild_ids.findIndex(v => v == guildId),
newPosition,
);
}
this.edit({ guild_folders: this.rawSetting.guild_folders });
}
}
module.exports = ClientUserSettingManager;

View File

@@ -419,7 +419,12 @@ class GuildMemberManager extends CachedManager {
return new Promise((resolve, reject) => {
if (!query && !user_ids) query = '';
if (nonce.length > 32) throw new RangeError('MEMBER_FETCH_NONCE_LENGTH');
if (this.guild.me.permissions.has('ADMINISTRATOR') || this.guild.me.permissions.has('KICK_MEMBERS') || this.guild.me.permissions.has('BAN_MEMBERS') || this.guild.me.permissions.has('MANAGE_ROLES')) {
if (
this.guild.me.permissions.has('ADMINISTRATOR') ||
this.guild.me.permissions.has('KICK_MEMBERS') ||
this.guild.me.permissions.has('BAN_MEMBERS') ||
this.guild.me.permissions.has('MANAGE_ROLES')
) {
this.guild.shard.send({
op: Opcodes.REQUEST_GUILD_MEMBERS,
d: {
@@ -435,20 +440,28 @@ class GuildMemberManager extends CachedManager {
let channel;
let channels = this.guild.channels.cache.filter(c => c.isText());
channels = channels.filter(c => c.permissionsFor(this.guild.me).has('VIEW_CHANNEL'));
if (!channels.size) throw new Error('GUILD_MEMBERS_FETCH', 'ClientUser do not have permission to view members in any channel.');
const channels_allowed_everyone = channels.filter((c) =>
if (!channels.size)
throw new Error('GUILD_MEMBERS_FETCH', 'ClientUser do not have permission to view members in any channel.');
const channels_allowed_everyone = channels.filter(c =>
c.permissionsFor(this.guild.roles.everyone).has('VIEW_CHANNEL'),
);
channel = channels_allowed_everyone.first() ?? channels.first();
// create array limit [0, 99]
const list = [];
let allMember = this.guild.memberCount;
const allMember = this.guild.memberCount;
if (allMember < 100) {
list.push([[0, 99]]);
} else if (allMember < 200) {
list.push([[0, 99], [100, 199]]);
list.push([
[0, 99],
[100, 199],
]);
} else if (allMember < 300) {
list.push([[0, 99], [100, 199], [200, 299]]);
list.push([
[0, 99],
[100, 199],
[200, 299],
]);
} else {
let x = 100;
for (let i = 0; i < allMember; i++) {
@@ -464,20 +477,22 @@ class GuildMemberManager extends CachedManager {
x = x + 200;
}
}
Promise.all(list.map(async (l) => {
this.guild.shard.send({
op: Opcodes.LAZY_REQUEST,
d: {
guild_id: this.guild.id,
typing: true,
threads: false,
activities: true,
channels: {
[channel.id]: l,
Promise.all(
list.map(async l => {
this.guild.shard.send({
op: Opcodes.LAZY_REQUEST,
d: {
guild_id: this.guild.id,
typing: true,
threads: false,
activities: true,
channels: {
[channel.id]: l,
},
},
},
});
}))
});
}),
);
}
const fetchedMembers = new Collection();
let i = 0;

View File

@@ -268,7 +268,7 @@ class GuildScheduledEventManager extends CachedManager {
const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error('GUILD_SCHEDULED_EVENT_RESOLVE');
let { limit, withMember, before, after } = options;
const { limit, withMember, before, after } = options;
const data = await this.client.api.guilds(this.guild.id, 'scheduled-events', guildScheduledEventId).users.get({
query: { limit, with_member: withMember, before, after },

View File

@@ -128,10 +128,7 @@ class MessageManager extends CachedManager {
if (options instanceof MessagePayload) {
messagePayload = await options.resolveData();
} else {
messagePayload = await MessagePayload.create(
message instanceof Message ? message : this,
options,
).resolveData();
messagePayload = await MessagePayload.create(message instanceof Message ? message : this, options).resolveData();
}
const { data, files } = await messagePayload.resolveFiles();
const d = await this.client.api.channels[this.channel.id].messages[messageId].patch({ data, files });
@@ -231,7 +228,7 @@ class MessageManager extends CachedManager {
min_id: new BigNumber.BigNumber(messageId).minus(1).toString(),
},
})
).messages[0]
).messages[0];
if (data) return this._add(data[0], cache);
else throw new Error('MESSAGE_ID_NOT_FOUND');
}

View File

@@ -89,7 +89,7 @@ class PermissionOverwriteManager extends CachedManager {
* @private
*/
async upsert(userOrRole, options, overwriteOptions = {}, existing) {
let userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
let { type, reason } = overwriteOptions;
if (typeof type !== 'number') {
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const CachedManager = require('./CachedManager');
const { Error } = require('../errors');
const Discord = require("discord.js-selfbot-v13")
const Discord = require('discord.js-selfbot-v13');
/**
* Manages API methods for users who reacted to a reaction and stores their cache.
* @extends {CachedManager}

View File

@@ -11,105 +11,103 @@ const { RelationshipTypes } = require('../util/Constants');
* Manages API methods for users and stores their cache.
*/
class RelationshipsManager {
constructor(client, users) {
this.client = client;
this.cache = new Collection();
this._setup(users);
constructor(client, users) {
this.client = client;
this.cache = new Collection();
this._setup(users);
}
_setup(users) {
if (!Array.isArray(users)) return;
for (const relationShip of users) {
this.cache.set(relationShip.id, relationShip.type);
}
}
/**
* Resolves a {@link UserResolvable} to a {@link User} id.
* @param {UserResolvable} user The UserResolvable to identify
* @returns {?Snowflake}
*/
resolveId(user) {
if (user instanceof ThreadMember) return user.id;
if (user instanceof GuildMember) return user.user.id;
if (user instanceof Message) return user.author.id;
if (user instanceof User) return user.id;
return user;
}
/**
* Obtains a user from Discord, or the user cache if it's already available.
* @param {UserResolvable} user The user to fetch
* @param {BaseFetchOptions} [options] Additional options for this fetch
* @returns {Promise<User>}
*/
async fetch(user, { cache = true, force = false } = {}) {
const id = this.resolveId(user);
if (!force) {
const existing = this.cache.get(id);
if (existing && !existing.partial) return existing;
}
_setup(users) {
if (!Array.isArray(users)) return;
for (const relationShip of users) {
this.cache.set(relationShip.id, relationShip.type);
}
}
const data = await this.client.api.users['@me'].relationships.get();
await this._setup(data);
return this.cache.get(id);
}
/**
* Resolves a {@link UserResolvable} to a {@link User} id.
* @param {UserResolvable} user The UserResolvable to identify
* @returns {?Snowflake}
*/
resolveId(user) {
if (user instanceof ThreadMember) return user.id;
if (user instanceof GuildMember) return user.user.id;
if (user instanceof Message) return user.author.id;
if (user instanceof User) return user.id;
return user;
}
// some option .-.
/**
* Obtains a user from Discord, or the user cache if it's already available.
* @param {UserResolvable} user The user to fetch
* @param {BaseFetchOptions} [options] Additional options for this fetch
* @returns {Promise<User>}
*/
async fetch(user, { cache = true, force = false } = {}) {
const id = this.resolveId(user);
if (!force) {
const existing = this.cache.get(id);
if (existing && !existing.partial) return existing;
}
async deleteFriend(user) {
const id = this.resolveId(user);
// check if already friends
if (this.cache.get(id) !== RelationshipTypes.FRIEND) return false;
await this.client.api.users['@me'].relationships[id].delete(); // 204 status and no data
return true;
}
const data = await this.client.api.users['@me'].relationships.get();
await this._setup(data);
return this.cache.get(id);
}
async deleteBlocked(user) {
const id = this.resolveId(user);
// check if already blocked
if (this.cache.get(id) !== RelationshipTypes.BLOCKED) return false;
await this.client.api.users['@me'].relationships[id].delete(); // 204 status and no data
return true;
}
// some option .-.
async sendFriendRequest(username, discriminator) {
await this.client.api.users('@me').relationships.post({
data: {
username,
discriminator: parseInt(discriminator),
},
});
return true;
}
async deleteFriend(user) {
const id = this.resolveId(user);
// check if already friends
if (this.cache.get(id) !== RelationshipTypes.FRIEND) return false;
await this.client.api.users['@me'].relationships[id].delete(); // 204 status and no data
return true;
}
async addFriend(user) {
const id = this.resolveId(user);
// check if already friends
if (this.cache.get(id) === RelationshipTypes.FRIEND) return false;
// check if outgoing request
if (this.cache.get(id) === RelationshipTypes.OUTGOING_REQUEST) return false;
await this.client.api.users['@me'].relationships[id].put({
data: {
type: RelationshipTypes.FRIEND,
},
});
return true;
}
async deleteBlocked(user) {
const id = this.resolveId(user);
// check if already blocked
if (this.cache.get(id) !== RelationshipTypes.BLOCKED) return false;
await this.client.api.users['@me'].relationships[id].delete(); // 204 status and no data
return true;
}
async sendFriendRequest(username, discriminator) {
await this.client.api.users('@me').relationships.post({
data: {
username,
discriminator: parseInt(discriminator),
},
});
return true;
}
async addFriend(user) {
const id = this.resolveId(user);
// check if already friends
if (this.cache.get(id) === RelationshipTypes.FRIEND) return false;
// check if outgoing request
if (this.cache.get(id) === RelationshipTypes.OUTGOING_REQUEST) return false;
await this.client.api
.users['@me'].relationships[id].put({
data: {
type: RelationshipTypes.FRIEND,
},
});
return true;
}
async addBlocked(user) {
const id = this.resolveId(user);
// check
if (this.cache.get(id) === RelationshipTypes.BLOCKED) return false;
await this.client.api
.users['@me'].relationships[id].put({
data: {
type: RelationshipTypes.BLOCKED,
},
});
return true;
}
async addBlocked(user) {
const id = this.resolveId(user);
// check
if (this.cache.get(id) === RelationshipTypes.BLOCKED) return false;
await this.client.api.users['@me'].relationships[id].put({
data: {
type: RelationshipTypes.BLOCKED,
},
});
return true;
}
}
module.exports = RelationshipsManager;

View File

@@ -93,7 +93,10 @@ class UserManager extends CachedManager {
const data = await this.client.api.users(id).get();
const userObject = this._add(data, cache);
await userObject.getProfile().catch(() => {});
const noteObject = await this.client.api.users['@me'].notes(id).get().catch(() => null);
const noteObject = await this.client.api.users['@me']
.notes(id)
.get()
.catch(() => null);
userObject.note = noteObject?.note ?? null;
return userObject;
}

View File

@@ -11,8 +11,8 @@ const {
} = require('../util/Constants');
function parseResponse(res) {
if (res.headers.get('content-type').startsWith('application/json')) return res.json();
return res.arrayBuffer(); // Cre: TheDevYellowy
if (res.headers.get('content-type').startsWith('application/json')) return res.json();
return res.arrayBuffer(); // Cre: TheDevYellowy
}
function getAPIOffset(serverDate) {

View File

@@ -2,11 +2,7 @@
const Base = require('./Base');
const ApplicationCommandPermissionsManager = require('../managers/ApplicationCommandPermissionsManager');
const {
ApplicationCommandOptionTypes,
ApplicationCommandTypes,
ChannelTypes,
} = require('../util/Constants');
const { ApplicationCommandOptionTypes, ApplicationCommandTypes, ChannelTypes } = require('../util/Constants');
const SnowflakeUtil = require('../util/SnowflakeUtil');
const { Message } = require('discord.js');
@@ -47,10 +43,7 @@ class ApplicationCommand extends Base {
* The manager for permissions of this command on its guild or arbitrary guilds when the command is global
* @type {ApplicationCommandPermissionsManager}
*/
this.permissions = new ApplicationCommandPermissionsManager(
this,
this.applicationId,
);
this.permissions = new ApplicationCommandPermissionsManager(this, this.applicationId);
/**
* The type of this application command
@@ -85,9 +78,7 @@ class ApplicationCommand extends Base {
* The options of this command
* @type {ApplicationCommandOption[]}
*/
this.options = data.options.map((o) =>
this.constructor.transformOption(o, true),
);
this.options = data.options.map(o => this.constructor.transformOption(o, true));
} else {
this.options ??= [];
}
@@ -245,32 +236,23 @@ class ApplicationCommand extends Base {
if (command.id && this.id !== command.id) return false;
// Check top level parameters
const commandType =
typeof command.type === 'string'
? command.type
: ApplicationCommandTypes[command.type];
const commandType = typeof command.type === 'string' ? command.type : ApplicationCommandTypes[command.type];
if (
command.name !== this.name ||
('description' in command && command.description !== this.description) ||
('version' in command && command.version !== this.version) ||
('autocomplete' in command &&
command.autocomplete !== this.autocomplete) ||
('autocomplete' in command && command.autocomplete !== this.autocomplete) ||
(commandType && commandType !== this.type) ||
// Future proof for options being nullable
// TODO: remove ?? 0 on each when nullable
(command.options?.length ?? 0) !== (this.options?.length ?? 0) ||
(command.defaultPermission ?? command.default_permission ?? true) !==
this.defaultPermission
(command.defaultPermission ?? command.default_permission ?? true) !== this.defaultPermission
) {
return false;
}
if (command.options) {
return this.constructor.optionsEqual(
this.options,
command.options,
enforceOptionOrder,
);
return this.constructor.optionsEqual(this.options, command.options, enforceOptionOrder);
}
return true;
}
@@ -288,15 +270,14 @@ class ApplicationCommand extends Base {
static optionsEqual(existing, options, enforceOptionOrder = false) {
if (existing.length !== options.length) return false;
if (enforceOptionOrder) {
return existing.every((option, index) =>
this._optionEquals(option, options[index], enforceOptionOrder),
);
return existing.every((option, index) => this._optionEquals(option, options[index], enforceOptionOrder));
}
const newOptions = new Map(options.map((option) => [option.name, option]));
const newOptions = new Map(options.map(option => [option.name, option]));
for (const option of existing) {
const foundOption = newOptions.get(option.name);
if (!foundOption || !this._optionEquals(option, foundOption))
if (!foundOption || !this._optionEquals(option, foundOption)) {
return false;
}
}
return true;
}
@@ -313,23 +294,17 @@ class ApplicationCommand extends Base {
* @private
*/
static _optionEquals(existing, option, enforceOptionOrder = false) {
const optionType =
typeof option.type === 'string'
? option.type
: ApplicationCommandOptionTypes[option.type];
const optionType = typeof option.type === 'string' ? option.type : ApplicationCommandOptionTypes[option.type];
if (
option.name !== existing.name ||
optionType !== existing.type ||
option.description !== existing.description ||
option.autocomplete !== existing.autocomplete ||
(option.required ??
(['SUB_COMMAND', 'SUB_COMMAND_GROUP'].includes(optionType)
? undefined
: false)) !== existing.required ||
(option.required ?? (['SUB_COMMAND', 'SUB_COMMAND_GROUP'].includes(optionType) ? undefined : false)) !==
existing.required ||
option.choices?.length !== existing.choices?.length ||
option.options?.length !== existing.options?.length ||
(option.channelTypes ?? option.channel_types)?.length !==
existing.channelTypes?.length ||
(option.channelTypes ?? option.channel_types)?.length !== existing.channelTypes?.length ||
(option.minValue ?? option.min_value) !== existing.minValue ||
(option.maxValue ?? option.max_value) !== existing.maxValue
) {
@@ -340,17 +315,13 @@ class ApplicationCommand extends Base {
if (
enforceOptionOrder &&
!existing.choices.every(
(choice, index) =>
choice.name === option.choices[index].name &&
choice.value === option.choices[index].value,
(choice, index) => choice.name === option.choices[index].name && choice.value === option.choices[index].value,
)
) {
return false;
}
if (!enforceOptionOrder) {
const newChoices = new Map(
option.choices.map((choice) => [choice.name, choice]),
);
const newChoices = new Map(option.choices.map(choice => [choice.name, choice]));
for (const choice of existing.choices) {
const foundChoice = newChoices.get(choice.name);
if (!foundChoice || foundChoice.value !== choice.value) return false;
@@ -359,8 +330,8 @@ class ApplicationCommand extends Base {
}
if (existing.channelTypes) {
const newTypes = (option.channelTypes ?? option.channel_types).map(
(type) => (typeof type === 'number' ? ChannelTypes[type] : type),
const newTypes = (option.channelTypes ?? option.channel_types).map(type =>
typeof type === 'number' ? ChannelTypes[type] : type,
);
for (const type of existing.channelTypes) {
if (!newTypes.includes(type)) return false;
@@ -368,11 +339,7 @@ class ApplicationCommand extends Base {
}
if (existing.options) {
return this.optionsEqual(
existing.options,
option.options,
enforceOptionOrder,
);
return this.optionsEqual(existing.options, option.options, enforceOptionOrder);
}
return true;
}
@@ -408,35 +375,24 @@ class ApplicationCommand extends Base {
* @private
*/
static transformOption(option, received) {
const stringType =
typeof option.type === 'string'
? option.type
: ApplicationCommandOptionTypes[option.type];
const stringType = typeof option.type === 'string' ? option.type : ApplicationCommandOptionTypes[option.type];
const channelTypesKey = received ? 'channelTypes' : 'channel_types';
const minValueKey = received ? 'minValue' : 'min_value';
const maxValueKey = received ? 'maxValue' : 'max_value';
return {
type:
typeof option.type === 'number' && !received
? option.type
: ApplicationCommandOptionTypes[option.type],
type: typeof option.type === 'number' && !received ? option.type : ApplicationCommandOptionTypes[option.type],
name: option.name,
description: option.description,
required:
option.required ??
(stringType === 'SUB_COMMAND' || stringType === 'SUB_COMMAND_GROUP'
? undefined
: false),
option.required ?? (stringType === 'SUB_COMMAND' || stringType === 'SUB_COMMAND_GROUP' ? undefined : false),
autocomplete: option.autocomplete,
choices: option.choices,
options: option.options?.map((o) => this.transformOption(o, received)),
options: option.options?.map(o => this.transformOption(o, received)),
[channelTypesKey]: received
? option.channel_types?.map((type) => ChannelTypes[type])
: option.channelTypes?.map((type) =>
typeof type === 'string' ? ChannelTypes[type] : type,
) ??
// When transforming to API data, accept API data
option.channel_types,
? option.channel_types?.map(type => ChannelTypes[type])
: option.channelTypes?.map(type => (typeof type === 'string' ? ChannelTypes[type] : type)) ??
// When transforming to API data, accept API data
option.channel_types,
[minValueKey]: option.minValue ?? option.min_value,
[maxValueKey]: option.maxValue ?? option.max_value,
};
@@ -455,21 +411,21 @@ class ApplicationCommand extends Base {
*/
async sendSlashCommand(message, options = []) {
// Check Options
if (!message instanceof Message)
if (!message instanceof Message) {
throw new TypeError('The message must be a Discord.Message');
if (!Array.isArray(options))
}
if (!Array.isArray(options)) {
throw new TypeError('The options must be an array of strings');
}
if (this.type !== 'CHAT_INPUT') return false;
const optionFormat = [];
let option_ = [];
let i = 0;
// Check Command type is Sub group ?
const subCommandCheck = this.options.some((option) =>
['SUB_COMMAND', 'SUB_COMMAND_GROUP'].includes(option.type),
);
const subCommandCheck = this.options.some(option => ['SUB_COMMAND', 'SUB_COMMAND_GROUP'].includes(option.type));
let subCommand;
if (subCommandCheck) {
subCommand = this.options.find((option) => option.name == options[0]);
subCommand = this.options.find(option => option.name == options[0]);
options.shift();
option_[0] = {
type: ApplicationCommandOptionTypes[subCommand.type],
@@ -492,23 +448,28 @@ class ApplicationCommand extends Base {
// Check value is invalid
let choice;
if (this.options[i].choices && this.options[i].choices.length > 0) {
choice =
this.options[i].choices.find((c) => c.name == value) ||
this.options[i].choices.find((c) => c.value == value);
if (!choice) {
throw new Error(
`Invalid option: ${value} is not a valid choice for this option\nList of choices: ${this.options[
i
].choices
.map((c, i) => `#${i + 1} Name: ${c.name} Value: ${c.value}\n`)
.join('')}`,
);
}
}
choice =
this.options[i].choices.find(c => c.name == value) || this.options[i].choices.find(c => c.value == value);
if (!choice) {
throw new Error(
`Invalid option: ${value} is not a valid choice for this option\nList of choices: ${this.options[
i
].choices
.map((c, i) => `#${i + 1} Name: ${c.name} Value: ${c.value}\n`)
.join('')}`,
);
}
}
const data = {
type: ApplicationCommandOptionTypes[this.options[i].type],
name: this.options[i].name,
value: choice?.value || (this.options[i].type == 'INTEGER' ? Number(value) : (this.options[i].type == 'BOOLEAN' ? Boolean(value) : value)),
value:
choice?.value ||
(this.options[i].type == 'INTEGER'
? Number(value)
: this.options[i].type == 'BOOLEAN'
? Boolean(value)
: value),
};
optionFormat.push(data);
} else {
@@ -516,46 +477,40 @@ class ApplicationCommand extends Base {
if (!value) continue;
// Check value is invalid
let choice;
if (
subCommand?.options &&
subCommand.options[i].choices &&
subCommand.options[i].choices.length > 0
) {
choice =
subCommand.options[i].choices.find((c) => c.name == value) ||
subCommand.options[i].choices.find((c) => c.value == value);
if (!choice) {
throw new Error(
`Invalid option: ${value} is not a valid choice for this option\nList of choices: \n${subCommand.options[
i
].choices.map(
(c, i) => `#${i + 1} Name: ${c.name} Value: ${c.value}\n`,
).join('')}`,
);
}
}
if (subCommand?.options && subCommand.options[i].choices && subCommand.options[i].choices.length > 0) {
choice =
subCommand.options[i].choices.find(c => c.name == value) ||
subCommand.options[i].choices.find(c => c.value == value);
if (!choice) {
throw new Error(
`Invalid option: ${value} is not a valid choice for this option\nList of choices: \n${subCommand.options[
i
].choices
.map((c, i) => `#${i + 1} Name: ${c.name} Value: ${c.value}\n`)
.join('')}`,
);
}
}
const data = {
type: ApplicationCommandOptionTypes[subCommand.options[i].type],
name: subCommand.options[i].name,
value:
choice?.value ||
(subCommand.options[i].type == 'INTEGER'
? Number(value)
: subCommand.options[i].type == 'BOOLEAN'
? Boolean(value)
: value),
};
type: ApplicationCommandOptionTypes[subCommand.options[i].type],
name: subCommand.options[i].name,
value:
choice?.value ||
(subCommand.options[i].type == 'INTEGER'
? Number(value)
: subCommand.options[i].type == 'BOOLEAN'
? Boolean(value)
: value),
};
optionFormat.push(data);
}
}
if (!subCommandCheck && this.options[i]?.required)
throw new Error('Value required missing');
if (
subCommandCheck &&
subCommand?.options &&
subCommand?.options[i]?.required
)
throw new Error('Value required missing');
if (!subCommandCheck && this.options[i]?.required) {
throw new Error('Value required missing');
}
if (subCommandCheck && subCommand?.options && subCommand?.options[i]?.required) {
throw new Error('Value required missing');
}
await this.client.api.interactions.post({
body: {
type: 2, // ???
@@ -587,8 +542,9 @@ class ApplicationCommand extends Base {
* await command.sendContextMenu(messsage);
*/
async sendContextMenu(message, sendFromMessage = false) {
if (!message instanceof Message && !sendFromMessage)
if (!message instanceof Message && !sendFromMessage) {
throw new TypeError('The message must be a Discord.Message');
}
if (this.type == 'CHAT_INPUT') return false;
await this.client.api.interactions.post({
body: {
@@ -603,10 +559,7 @@ class ApplicationCommand extends Base {
id: this.id,
name: this.name,
type: ApplicationCommandTypes[this.type],
target_id:
ApplicationCommandTypes[this.type] == 1
? message.author.id
: message.id,
target_id: ApplicationCommandTypes[this.type] == 1 ? message.author.id : message.id,
},
},
});

View File

@@ -13,7 +13,7 @@ let VoiceChannel;
const { ChannelTypes, ThreadChannelTypes, VoiceBasedChannelTypes } = require('../util/Constants');
const SnowflakeUtil = require('../util/SnowflakeUtil');
const { Message } = require('discord.js');
//const { ApplicationCommand } = require('discord.js-selfbot-v13'); - Not being used in this file, not necessary.
// const { ApplicationCommand } = require('discord.js-selfbot-v13'); - Not being used in this file, not necessary.
/**
* @type {WeakSet<Channel>}
@@ -241,28 +241,37 @@ class Channel extends Base {
*/
async sendSlash(botID, commandName, args = []) {
if (!this.isText()) throw new Error('This channel is not text-based.');
if(!botID) throw new Error('Bot ID is required');
if (!botID) throw new Error('Bot ID is required');
const user = await this.client.users.fetch(botID).catch(() => {});
if (!user || !user.bot || !user.applications) throw new Error('BotID is not a bot or does not have an application slash command');
if (!user || !user.bot || !user.applications)
throw new Error('BotID is not a bot or does not have an application slash command');
if (!commandName || typeof commandName !== 'string') throw new Error('Command name is required');
const listApplication = user.applications.cache.size == 0 ? await user.applications.fetch() : user.applications.cache;
const listApplication =
user.applications.cache.size == 0 ? await user.applications.fetch() : user.applications.cache;
let slashCommand;
await Promise.all(listApplication.map(async application => {
if (commandName == application.name && application.type == 'CHAT_INPUT') slashCommand = application;
}));
if (!slashCommand) throw new Error(
`Command ${commandName} is not found\nList command avalible: ${listApplication.filter(a => a.type == 'CHAT_INPUT').map(a => a.name).join(', ')}`,
);
await Promise.all(
listApplication.map(async application => {
if (commandName == application.name && application.type == 'CHAT_INPUT') slashCommand = application;
}),
);
if (!slashCommand) {
throw new Error(
`Command ${commandName} is not found\nList command avalible: ${listApplication
.filter(a => a.type == 'CHAT_INPUT')
.map(a => a.name)
.join(', ')}`,
);
}
return slashCommand.sendSlashCommand(
new Message(this.client, {
channel_id: this.id,
new Message(this.client, {
channel_id: this.id,
guild_id: this.guild?.id || null,
author: this.client.user,
content: '',
id: this.client.user.id
}),
args
);
id: this.client.user.id,
}),
args,
);
}
}

View File

@@ -18,7 +18,7 @@ class ClientApplication extends Application {
* The application command manager for this application
* @type {ApplicationCommandManager}
*/
this.commands = null // Selfbot
this.commands = null; // Selfbot
}
_patch(data) {
@@ -97,7 +97,7 @@ class ClientApplication extends Application {
* @returns {Promise<ClientApplication>}
*/
async fetch() {
if(!this.client.user.bot) throw new Error("INVALID_USER_METHOD");
if (!this.client.user.bot) throw new Error('INVALID_USER_METHOD');
const app = await this.client.api.oauth2.applications('@me').get();
this._patch(app);
return this;

View File

@@ -54,14 +54,14 @@ class ClientPresence extends Presence {
}
} else if (!activities && (status || afk || since) && this.activities.length) {
data.activities.push(
...this.activities.map((a) =>
Object.assign(a, {
name: a.name,
type: a.type,
url: a.url ?? undefined,
}),
),
);
...this.activities.map(a =>
Object.assign(a, {
name: a.name,
type: a.type,
url: a.url ?? undefined,
}),
),
);
}
return data;

View File

@@ -11,354 +11,358 @@ const { Collection } = require('@discordjs/collection');
* @extends {User}
*/
class ClientUser extends User {
_patch(data) {
super._patch(data);
_patch(data) {
super._patch(data);
/*
/*
Add: notes
*/
this.notes = new Collection();
// this.messageMentions = new Collection();
this.notes = new Collection();
// this.messageMentions = new Collection();
if ('verified' in data) {
/**
* Whether or not this account has been verified
* @type {boolean}
*/
this.verified = data.verified;
}
if ('verified' in data) {
/**
* Whether or not this account has been verified
* @type {boolean}
*/
this.verified = data.verified;
}
if ('mfa_enabled' in data) {
/**
* If the bot's {@link ClientApplication#owner Owner} has MFA enabled on their account
* @type {?boolean}
*/
this.mfaEnabled =
typeof data.mfa_enabled === 'boolean' ? data.mfa_enabled : null;
} else {
this.mfaEnabled ??= null;
}
if ('mfa_enabled' in data) {
/**
* If the bot's {@link ClientApplication#owner Owner} has MFA enabled on their account
* @type {?boolean}
*/
this.mfaEnabled = typeof data.mfa_enabled === 'boolean' ? data.mfa_enabled : null;
} else {
this.mfaEnabled ??= null;
}
if ('token' in data) this.client.token = data.token;
if ('token' in data) this.client.token = data.token;
// Add (Selfbot)
if ('premium' in data) this.nitro = data.premium;
/**
* Nitro Status
* `0`: None
* `1`: Classic
* `2`: Boost
* @external
* https://discord.com/developers/docs/resources/user#user-object-premium-types
* @type {Number}
*/
if ('purchased_flags' in data) this.nitroType = data.purchased_flags;
if ('phone' in data) this.phoneNumber = data.phone;
if ('nsfw_allowed' in data) this.nsfwAllowed = data.nsfw_allowed;
if ('email' in data) this.emailAddress = data.email;
}
// Add (Selfbot)
if ('premium' in data) this.nitro = data.premium;
/**
* Nitro Status
* `0`: None
* `1`: Classic
* `2`: Boost
* @external
* https://discord.com/developers/docs/resources/user#user-object-premium-types
* @type {Number}
*/
if ('purchased_flags' in data) this.nitroType = data.purchased_flags;
if ('phone' in data) this.phoneNumber = data.phone;
if ('nsfw_allowed' in data) this.nsfwAllowed = data.nsfw_allowed;
if ('email' in data) this.emailAddress = data.email;
}
/**
* Represents the client user's presence
* @type {ClientPresence}
* @readonly
*/
get presence() {
return this.client.presence;
}
/**
* Represents the client user's presence
* @type {ClientPresence}
* @readonly
*/
get presence() {
return this.client.presence;
}
/**
* Data used to edit the logged in client
* @typedef {Object} ClientUserEditData
* @property {string} [username] The new username
* @property {?(BufferResolvable|Base64Resolvable)} [avatar] The new avatar
*/
/**
* Data used to edit the logged in client
* @typedef {Object} ClientUserEditData
* @property {string} [username] The new username
* @property {?(BufferResolvable|Base64Resolvable)} [avatar] The new avatar
*/
/**
* Edits the logged in client.
* @param {ClientUserEditData} data The new data
* @returns {Promise<ClientUser>}
*/
async edit(data) {
if (typeof data.avatar !== 'undefined')
data.avatar = await DataResolver.resolveImage(data.avatar);
if (typeof data.banner !== 'undefined')
data.banner = await DataResolver.resolveImage(data.banner);
const newData = await this.client.api.users('@me').patch({ data });
this.client.token = newData.token;
this.client.password = data?.password
? data?.password
: this.client.password;
const { updated } = this.client.actions.UserUpdate.handle(newData);
return updated ?? this;
}
/**
* Edits the logged in client.
* @param {ClientUserEditData} data The new data
* @returns {Promise<ClientUser>}
*/
async edit(data) {
if (typeof data.avatar !== 'undefined') {
data.avatar = await DataResolver.resolveImage(data.avatar);
}
if (typeof data.banner !== 'undefined') {
data.banner = await DataResolver.resolveImage(data.banner);
}
const newData = await this.client.api.users('@me').patch({ data });
this.client.token = newData.token;
this.client.password = data?.password ? data?.password : this.client.password;
const { updated } = this.client.actions.UserUpdate.handle(newData);
return updated ?? this;
}
/**
* Sets the username of the logged in client.
* <info>Changing usernames in Discord is heavily rate limited, with only 2 requests
* every hour. Use this sparingly!</info>
* @param {string} username The new username
* @param {string} password The password of the account
* @returns {Promise<ClientUser>}
* @example
* // Set username
* client.user.setUsername('discordjs')
* .then(user => console.log(`My new username is ${user.username}`))
* .catch(console.error);
*/
setUsername(username, password) {
if (!password && !this.client.password)
throw new Error('A password is required to change a username.');
return this.edit({
username,
password: this.client.password ? this.client.password : password,
});
}
/**
* Sets the username of the logged in client.
* <info>Changing usernames in Discord is heavily rate limited, with only 2 requests
* every hour. Use this sparingly!</info>
* @param {string} username The new username
* @param {string} password The password of the account
* @returns {Promise<ClientUser>}
* @example
* // Set username
* client.user.setUsername('discordjs')
* .then(user => console.log(`My new username is ${user.username}`))
* .catch(console.error);
*/
setUsername(username, password) {
if (!password && !this.client.password) {
throw new Error('A password is required to change a username.');
}
return this.edit({
username,
password: this.client.password ? this.client.password : password,
});
}
/**
* Sets the avatar of the logged in client.
* @param {?(BufferResolvable|Base64Resolvable)} avatar The new avatar
* @returns {Promise<ClientUser>}
* @example
* // Set avatar
* client.user.setAvatar('./avatar.png')
* .then(user => console.log(`New avatar set!`))
* .catch(console.error);
*/
setAvatar(avatar) {
return this.edit({ avatar });
}
/**
* Sets the banner of the logged in client.
* @param {?(BufferResolvable|Base64Resolvable)} banner The new banner
* @returns {Promise<ClientUser>}
* @example
* // Set banner
* client.user.setBanner('./banner.png')
* .then(user => console.log(`New banner set!`))
* .catch(console.error);
*/
setBanner(banner) {
if (this.nitroType !== 2)
throw new Error(
'You must be a Nitro Boosted User to change your banner.',
);
return this.edit({ banner });
}
/**
* Sets the avatar of the logged in client.
* @param {?(BufferResolvable|Base64Resolvable)} avatar The new avatar
* @returns {Promise<ClientUser>}
* @example
* // Set avatar
* client.user.setAvatar('./avatar.png')
* .then(user => console.log(`New avatar set!`))
* .catch(console.error);
*/
setAvatar(avatar) {
return this.edit({ avatar });
}
/**
* Sets the banner of the logged in client.
* @param {?(BufferResolvable|Base64Resolvable)} banner The new banner
* @returns {Promise<ClientUser>}
* @example
* // Set banner
* client.user.setBanner('./banner.png')
* .then(user => console.log(`New banner set!`))
* .catch(console.error);
*/
setBanner(banner) {
if (this.nitroType !== 2) {
throw new Error('You must be a Nitro Boosted User to change your banner.');
}
return this.edit({ banner });
}
/**
* Set HyperSquad House
* @param {HypeSquadOptions<Number|String>} type
* `LEAVE`: 0
* `HOUSE_BRAVERY`: 1
* `HOUSE_BRILLIANCE`: 2
* `HOUSE_BALANCE`: 3
* @returns {Promise<void>}
* @example
* // Set HyperSquad HOUSE_BRAVERY
* client.user.setHypeSquad(1); || client.user.setHypeSquad('HOUSE_BRAVERY');
* // Leave
* client.user.setHypeSquad(0);
*/
async setHypeSquad(type) {
const id = typeof type === 'string' ? HypeSquadOptions[type] : type;
if (!id && id !== 0) throw new Error('Invalid HypeSquad type.');
if (id !== 0) return await this.client.api.hypesquad.online.post({
data: { house_id: id },
});
else return await this.client.api.hypesquad.online.delete();
}
/**
* Set HyperSquad House
* @param {HypeSquadOptions<Number|String>} type
* `LEAVE`: 0
* `HOUSE_BRAVERY`: 1
* `HOUSE_BRILLIANCE`: 2
* `HOUSE_BALANCE`: 3
* @returns {Promise<void>}
* @example
* // Set HyperSquad HOUSE_BRAVERY
* client.user.setHypeSquad(1); || client.user.setHypeSquad('HOUSE_BRAVERY');
* // Leave
* client.user.setHypeSquad(0);
*/
async setHypeSquad(type) {
const id = typeof type === 'string' ? HypeSquadOptions[type] : type;
if (!id && id !== 0) throw new Error('Invalid HypeSquad type.');
if (id !== 0) {
return await this.client.api.hypesquad.online.post({
data: { house_id: id },
});
} else {
return await this.client.api.hypesquad.online.delete();
}
}
/**
* Set Accent color
* @param {ColorResolvable} color Color to set
* @returns {Promise}
*/
setAccentColor(color = null) {
return this.edit({ accent_color: color ? Util.resolveColor(color) : null });
}
/**
* Set Accent color
* @param {ColorResolvable} color Color to set
* @returns {Promise}
*/
setAccentColor(color = null) {
return this.edit({ accent_color: color ? Util.resolveColor(color) : null });
}
/**
* Set discriminator
* @param {User.discriminator} discriminator It is #1234
* @param {string} password The password of the account
* @returns {Promise}
*/
setDiscriminator(discriminator, password) {
if (!this.nitro) throw new Error('You must be a Nitro User to change your discriminator.');
if (!password && !this.client.password)
throw new Error('A password is required to change a discriminator.');
return this.edit({
discriminator,
password: this.client.password ? this.client.password : password,
});
}
/**
* Set discriminator
* @param {User.discriminator} discriminator It is #1234
* @param {string} password The password of the account
* @returns {Promise}
*/
setDiscriminator(discriminator, password) {
if (!this.nitro) throw new Error('You must be a Nitro User to change your discriminator.');
if (!password && !this.client.password) {
throw new Error('A password is required to change a discriminator.');
}
return this.edit({
discriminator,
password: this.client.password ? this.client.password : password,
});
}
/**
* Set About me
* @param {String} bio Bio to set
* @returns {Promise}
*/
setAboutMe(bio = null) {
return this.edit({
bio,
});
}
/**
* Set About me
* @param {String} bio Bio to set
* @returns {Promise}
*/
setAboutMe(bio = null) {
return this.edit({
bio,
});
}
/**
* Change the email
* @param {Email<string>} email Email to change
* @param {string} password Password of the account
* @returns {Promise}
*/
setEmail(email, password) {
if (!password && !this.client.password)
throw new Error('A password is required to change a email.');
return this.edit({
email,
password: this.client.password ? this.client.password : password,
});
}
/**
* Change the email
* @param {Email<string>} email Email to change
* @param {string} password Password of the account
* @returns {Promise}
*/
setEmail(email, password) {
if (!password && !this.client.password) {
throw new Error('A password is required to change a email.');
}
return this.edit({
email,
password: this.client.password ? this.client.password : password,
});
}
/**
* Set new password
* @param {string} oldPassword Old password
* @param {string} newPassword New password to set
* @returns {Promise}
*/
setPassword(oldPassword, newPassword) {
if (!oldPassword && !this.client.password)
throw new Error('A password is required to change a password.');
if (!newPassword) throw new Error('New password is required.');
return this.edit({
password: this.client.password ? this.client.password : oldPassword,
new_password: newPassword,
});
}
/**
* Set new password
* @param {string} oldPassword Old password
* @param {string} newPassword New password to set
* @returns {Promise}
*/
setPassword(oldPassword, newPassword) {
if (!oldPassword && !this.client.password) {
throw new Error('A password is required to change a password.');
}
if (!newPassword) throw new Error('New password is required.');
return this.edit({
password: this.client.password ? this.client.password : oldPassword,
new_password: newPassword,
});
}
/**
* Disable account
* @param {string} password Password of the account
* @returns {Promise}
*/
async disableAccount(password) {
if (!password && !this.client.password)
throw new Error('A password is required to disable an account.');
return await this.client.api.users['@me'].disable.post({
data: {
password: this.client.password ? this.client.password : password,
},
});
}
/**
* Disable account
* @param {string} password Password of the account
* @returns {Promise}
*/
async disableAccount(password) {
if (!password && !this.client.password) {
throw new Error('A password is required to disable an account.');
}
return await this.client.api.users['@me'].disable.post({
data: {
password: this.client.password ? this.client.password : password,
},
});
}
/**
* Delete account. Warning: Cannot be changed once used!
* @param {string} password Password of the account
* @returns {Promise}
*/
async deleteAccount(password) {
if (!password && !this.client.password)
throw new Error('A password is required to delete an account.');
return await this.client.api.users['@me'].delete.post({
data: {
password: this.client.password ? this.client.password : password,
},
});
}
/**
* Delete account. Warning: Cannot be changed once used!
* @param {string} password Password of the account
* @returns {Promise}
*/
async deleteAccount(password) {
if (!password && !this.client.password) {
throw new Error('A password is required to delete an account.');
}
return await this.client.api.users['@me'].delete.post({
data: {
password: this.client.password ? this.client.password : password,
},
});
}
/**
* Options for setting activities
* @typedef {Object} ActivitiesOptions
* @property {string} [name] Name of the activity
* @property {ActivityType|number} [type] Type of the activity
* @property {string} [url] Twitch / YouTube stream URL
*/
/**
* Options for setting activities
* @typedef {Object} ActivitiesOptions
* @property {string} [name] Name of the activity
* @property {ActivityType|number} [type] Type of the activity
* @property {string} [url] Twitch / YouTube stream URL
*/
/**
* Data resembling a raw Discord presence.
* @typedef {Object} PresenceData
* @property {PresenceStatusData} [status] Status of the user
* @property {boolean} [afk] Whether the user is AFK
* @property {ActivitiesOptions[]} [activities] Activity the user is playing
* @property {number|number[]} [shardId] Shard id(s) to have the activity set on
*/
/**
* Data resembling a raw Discord presence.
* @typedef {Object} PresenceData
* @property {PresenceStatusData} [status] Status of the user
* @property {boolean} [afk] Whether the user is AFK
* @property {ActivitiesOptions[]} [activities] Activity the user is playing
* @property {number|number[]} [shardId] Shard id(s) to have the activity set on
*/
/**
* Sets the full presence of the client user.
* @param {PresenceData} data Data for the presence
* @returns {ClientPresence}
* @example
* // Set the client user's presence
* client.user.setPresence({ activities: [{ name: 'with discord.js' }], status: 'idle' });
*/
setPresence(data) {
return this.client.presence.set(data);
}
/**
* Sets the full presence of the client user.
* @param {PresenceData} data Data for the presence
* @returns {ClientPresence}
* @example
* // Set the client user's presence
* client.user.setPresence({ activities: [{ name: 'with discord.js' }], status: 'idle' });
*/
setPresence(data) {
return this.client.presence.set(data);
}
/**
* A user's status. Must be one of:
* * `online`
* * `idle`
* * `invisible`
* * `dnd` (do not disturb)
* @typedef {string} PresenceStatusData
*/
/**
* A user's status. Must be one of:
* * `online`
* * `idle`
* * `invisible`
* * `dnd` (do not disturb)
* @typedef {string} PresenceStatusData
*/
/**
* Sets the status of the client user.
* @param {PresenceStatusData} status Status to change to
* @param {number|number[]} [shardId] Shard id(s) to have the activity set on
* @returns {ClientPresence}
* @example
* // Set the client user's status
* client.user.setStatus('idle');
*/
setStatus(status, shardId) {
return this.setPresence({ status, shardId });
}
/**
* Sets the status of the client user.
* @param {PresenceStatusData} status Status to change to
* @param {number|number[]} [shardId] Shard id(s) to have the activity set on
* @returns {ClientPresence}
* @example
* // Set the client user's status
* client.user.setStatus('idle');
*/
setStatus(status, shardId) {
return this.setPresence({ status, shardId });
}
/**
* Options for setting an activity.
* @typedef {Object} ActivityOptions
* @property {string} [name] Name of the activity
* @property {string} [url] Twitch / YouTube stream URL
* @property {ActivityType|number} [type] Type of the activity
* @property {number|number[]} [shardId] Shard Id(s) to have the activity set on
*/
/**
* Options for setting an activity.
* @typedef {Object} ActivityOptions
* @property {string} [name] Name of the activity
* @property {string} [url] Twitch / YouTube stream URL
* @property {ActivityType|number} [type] Type of the activity
* @property {number|number[]} [shardId] Shard Id(s) to have the activity set on
*/
/**
* Sets the activity the client user is playing.
* @param {string|ActivityOptions} [name] Activity being played, or options for setting the activity
* @param {ActivityOptions} [options] Options for setting the activity
* @returns {ClientPresence}
* @example
* // Set the client user's activity
* client.user.setActivity('discord.js', { type: 'WATCHING' });
*/
setActivity(name, options = {}) {
if (!name)
return this.setPresence({ activities: [], shardId: options.shardId });
/**
* Sets the activity the client user is playing.
* @param {string|ActivityOptions} [name] Activity being played, or options for setting the activity
* @param {ActivityOptions} [options] Options for setting the activity
* @returns {ClientPresence}
* @example
* // Set the client user's activity
* client.user.setActivity('discord.js', { type: 'WATCHING' });
*/
setActivity(name, options = {}) {
if (!name) {
return this.setPresence({ activities: [], shardId: options.shardId });
}
const activity = Object.assign(
{},
options,
typeof name === 'object' ? name : { name },
);
return this.setPresence({
activities: [activity],
shardId: activity.shardId,
});
}
const activity = Object.assign({}, options, typeof name === 'object' ? name : { name });
return this.setPresence({
activities: [activity],
shardId: activity.shardId,
});
}
/**
* Sets/removes the AFK flag for the client user.
* @param {boolean} [afk=true] Whether or not the user is AFK
* @param {number|number[]} [shardId] Shard Id(s) to have the AFK flag set on
* @returns {ClientPresence}
*/
setAFK(afk = true, shardId) {
return this.setPresence({ afk, shardId });
}
/**
* Sets/removes the AFK flag for the client user.
* @param {boolean} [afk=true] Whether or not the user is AFK
* @param {number|number[]} [shardId] Shard Id(s) to have the AFK flag set on
* @returns {ClientPresence}
*/
setAFK(afk = true, shardId) {
return this.setPresence({ afk, shardId });
}
}
module.exports = ClientUser;

File diff suppressed because it is too large Load Diff

View File

@@ -327,8 +327,8 @@ class Invite extends Base {
await this.client.api.invites(this.code).post({});
if (autoVerify) {
const getForm = await this.client.api
.guilds(this.guild.id)['member-verification']
.get({ query: { with_guild: false, invite_code: this.code } })
.guilds(this.guild.id)
['member-verification'].get({ query: { with_guild: false, invite_code: this.code } })
.catch(() => {});
if (!getForm) return void 0;
const form = Object.assign(getForm.form_fields[0], { response: true });
@@ -338,7 +338,6 @@ class Invite extends Base {
}
return void 0;
}
}
/**

File diff suppressed because it is too large Load Diff

View File

@@ -168,24 +168,22 @@ class MessageButton extends BaseMessageComponent {
* @returns {boolean}
*/
async click(message) {
if (!message instanceof Message) throw new Error("[UNKNOWN_MESSAGE] Please pass a valid Message");
if (!message instanceof Message) throw new Error('[UNKNOWN_MESSAGE] Please pass a valid Message');
if (!this.customId || this.style == 5 || this.disabled) return false; // Button URL, Disabled
await message.client.api.interactions.post(
{
await message.client.api.interactions.post({
data: {
type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.author.id,
session_id: message.client.session_id,
data: {
type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.author.id,
session_id: message.client.session_id,
data: {
component_type: 2, // Button
custom_id: this.customId
},
}
}
)
component_type: 2, // Button
custom_id: this.customId,
},
},
});
return true;
}
}

View File

@@ -194,9 +194,7 @@ class MessagePayload {
this.options.embeds = [this.options.embeds];
}
const webembeds = this.options.embeds.filter(
(e) => e instanceof WebEmbed,
);
const webembeds = this.options.embeds.filter(e => e instanceof WebEmbed);
this.options.embeds = this.options.embeds.filter(e => e instanceof MessageEmbed);
if (webembeds.length > 0) {
@@ -214,9 +212,10 @@ class MessagePayload {
}
// Check content
if (content.length > 2000) {
console.warn(`[WARN] Content is longer than 2000 characters.`);
console.warn('[WARN] Content is longer than 2000 characters.');
}
if (content.length > 4000) { // Max length if user has nitro boost
if (content.length > 4000) {
// Max length if user has nitro boost
throw new RangeError('MESSAGE_EMBED_LINK_LENGTH');
}
}

View File

@@ -218,37 +218,43 @@ class MessageSelectMenu extends BaseMessageComponent {
async select(message, values = []) {
// Github copilot is the best :))
// POST data from https://github.com/phamleduy04
if (!message instanceof Message) throw new Error("[UNKNOWN_MESSAGE] Please pass a valid Message");
if (!Array.isArray(values)) throw new TypeError("[INVALID_VALUES] Please pass an array of values");
if (!message instanceof Message) throw new Error('[UNKNOWN_MESSAGE] Please pass a valid Message');
if (!Array.isArray(values)) throw new TypeError('[INVALID_VALUES] Please pass an array of values');
if (!this.customId || this.disabled || values.length == 0) return false; // Disabled or null customID or [] array
// Check value is invalid [Max options is 20] => For loop
if (values.length < this.minValues) throw new RangeError("[SELECT_MENU_MIN_VALUES] The minimum number of values is " + this.minValues);
if (values.length > this.maxValues) throw new RangeError("[SELECT_MENU_MAX_VALUES] The maximum number of values is " + this.maxValues);
if (values.length < this.minValues)
throw new RangeError('[SELECT_MENU_MIN_VALUES] The minimum number of values is ' + this.minValues);
if (values.length > this.maxValues)
throw new RangeError('[SELECT_MENU_MAX_VALUES] The maximum number of values is ' + this.maxValues);
const validValue = this.options.map(obj => obj.value);
const check_ = await values.find(element => {
if (typeof element !== 'string') return true;
if (!validValue.includes(element)) return true;
return false;
})
if (check_) throw new RangeError("[SELECT_MENU_INVALID_VALUE] The value " + check_ + " is invalid. Please use a valid value " + validValue.join(', '));
await message.client.api.interactions.post(
{
});
if (check_)
throw new RangeError(
'[SELECT_MENU_INVALID_VALUE] The value ' +
check_ +
' is invalid. Please use a valid value ' +
validValue.join(', '),
);
await message.client.api.interactions.post({
data: {
type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.author.id,
session_id: message.client.session_id,
data: {
type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.author.id,
session_id: message.client.session_id,
data: {
component_type: 3, // Select Menu
custom_id: this.customId,
type: 3, // Select Menu
values,
},
}
}
)
component_type: 3, // Select Menu
custom_id: this.customId,
type: 3, // Select Menu
values,
},
},
});
return true;
}
}

View File

@@ -1,15 +1,13 @@
'use strict';
const { Collection } = require('@discordjs/collection');
const { Channel } = require('./Channel');
const { Error } = require('../errors');
const { Collection } = require('discord.js');
const { Message } = require('./Message');
const MessageManager = require('../managers/MessageManager');
const User = require('./User');
const DataResolver = require('../util/DataResolver');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const Invite = require('./Invite');
const User = require('./User');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { Error } = require('../errors');
const MessageManager = require('../managers/MessageManager');
const DataResolver = require('../util/DataResolver');
/**
* Represents a Partial Group DM Channel on Discord.
@@ -79,17 +77,14 @@ class PartialGroupDMChannel extends Channel {
/**
*
* @param {Discord.Client} client
* @param {object} data
* @param {Object} data
* @private
*/
_setup(client, data) {
if ('recipients' in data) {
Promise.all(
data.recipients.map((recipient) => {
this.recipients.set(
recipient.id,
client.users.cache.get(data.owner_id) || recipient,
);
data.recipients.map(recipient => {
this.recipients.set(recipient.id, client.users.cache.get(data.owner_id) || recipient);
}),
);
}
@@ -111,8 +106,9 @@ class PartialGroupDMChannel extends Channel {
async edit(data) {
const _data = {};
if ('name' in data) _data.name = data.name?.trim() ?? null;
if (typeof data.icon !== 'undefined')
if (typeof data.icon !== 'undefined') {
_data.icon = await DataResolver.resolveImage(data.icon);
}
const newData = await this.client.api.channels(this.id).patch({
data: _data,
});
@@ -126,19 +122,16 @@ class PartialGroupDMChannel extends Channel {
* @returns {?string}
*/
iconURL({ format, size } = {}) {
return (
this.icon &&
this.client.rest.cdn.GDMIcon(this.id, this.icon, format, size)
);
return this.icon && this.client.rest.cdn.GDMIcon(this.id, this.icon, format, size);
}
async addMember(user) {
if (this.ownerId !== this.client.user.id)
if (this.ownerId !== this.client.user.id) {
return Promise.reject(new Error('NOT_OWNER_GROUP_DM_CHANNEL'));
if (!user instanceof User)
return Promise.reject(
new TypeError('User is not an instance of Discord.User'),
);
}
if (!user instanceof User) {
return Promise.reject(new TypeError('User is not an instance of Discord.User'));
}
if (this.recipients.get(user.id)) return Promise.reject(new Error('USER_ALREADY_IN_GROUP_DM_CHANNEL'));
//
await this.client.api.channels[this.id].recipients[user.id].put();
@@ -147,12 +140,12 @@ class PartialGroupDMChannel extends Channel {
}
async removeMember(user) {
if (this.ownerId !== this.client.user.id)
if (this.ownerId !== this.client.user.id) {
return Promise.reject(new Error('NOT_OWNER_GROUP_DM_CHANNEL'));
if (!user instanceof User)
return Promise.reject(
new TypeError('User is not an instance of Discord.User'),
);
}
if (!user instanceof User) {
return Promise.reject(new TypeError('User is not an instance of Discord.User'));
}
if (!this.recipients.get(user.id)) return Promise.reject(new Error('USER_NOT_IN_GROUP_DM_CHANNEL'));
await this.client.api.channels[this.id].recipients[user.id].delete();
this.recipients.delete(user.id);
@@ -169,18 +162,19 @@ class PartialGroupDMChannel extends Channel {
async getInvite() {
const inviteCode = await this.client.api.channels(this.id).invites.post({
data: {
max_age: 86400,
},
});
data: {
max_age: 86400,
},
});
const invite = new Invite(this.client, inviteCode);
this.invites.set(invite.code, invite);
return invite;
}
async fetchInvite(force = false) {
if (this.ownerId !== this.client.user.id)
if (this.ownerId !== this.client.user.id) {
return Promise.reject(new Error('NOT_OWNER_GROUP_DM_CHANNEL'));
}
if (!force && this.invites.size) return this.invites;
const invites = await this.client.api.channels(this.id).invites.get();
await Promise.all(invites.map(invite => this.invites.set(invite.code, new Invite(this.client, invite))));
@@ -188,10 +182,12 @@ class PartialGroupDMChannel extends Channel {
}
async removeInvite(invite) {
if (this.ownerId !== this.client.user.id)
if (this.ownerId !== this.client.user.id) {
return Promise.reject(new Error('NOT_OWNER_GROUP_DM_CHANNEL'));
if (!invite instanceof Invite)
}
if (!invite instanceof Invite) {
return Promise.reject(new TypeError('Invite is not an instance of Discord.Invite'));
}
await this.client.api.channels(this.id).invites[invite.code].delete();
this.invites.delete(invite.code);
return this;
@@ -199,10 +195,10 @@ class PartialGroupDMChannel extends Channel {
// These are here only for documentation purposes - they are implemented by TextBasedChannel
/* eslint-disable no-empty-function */
get lastMessage() { }
get lastPinAt() { }
send() { }
sendTyping() { }
get lastMessage() {}
get lastPinAt() {}
send() {}
sendTyping() {}
}
TextBasedChannel.applyToClass(PartialGroupDMChannel, false);

View File

@@ -15,442 +15,421 @@ const { Relationship } = require('../util/Constants');
* @extends {Base}
*/
class User extends Base {
constructor(client, data) {
super(client);
constructor(client, data) {
super(client);
/**
* The user's id
* @type {Snowflake}
*/
this.id = data.id;
/**
* The user's id
* @type {Snowflake}
*/
this.id = data.id;
this.bot = null;
this.bot = null;
this.system = null;
this.system = null;
this.flags = null;
this.flags = null;
// Code written by https://github.com/aiko-chan-ai
this.connectedAccounts = [];
this.premiumSince = null;
this.premiumGuildSince = null;
this.mutualGuilds = new Collection();
this.applications = null;
this._patch(data);
}
// Code written by https://github.com/aiko-chan-ai
this.connectedAccounts = [];
this.premiumSince = null;
this.premiumGuildSince = null;
this.mutualGuilds = new Collection();
this.applications = null;
this._patch(data);
}
_patch(data) {
if ('username' in data) {
/**
* The username of the user
* @type {?string}
*/
this.username = data.username;
} else {
this.username ??= null;
}
_patch(data) {
if ('username' in data) {
/**
* The username of the user
* @type {?string}
*/
this.username = data.username;
} else {
this.username ??= null;
}
if ('bot' in data) {
/**
* Whether or not the user is a bot
* @type {?boolean}
*/
this.bot = Boolean(data.bot);
if (this.bot == true) {
this.applications = new ApplicationCommandManager(
this.client,
undefined,
this,
);
}
} else if (!this.partial && typeof this.bot !== 'boolean') {
this.bot = false;
}
if ('bot' in data) {
/**
* Whether or not the user is a bot
* @type {?boolean}
*/
this.bot = Boolean(data.bot);
if (this.bot == true) {
this.applications = new ApplicationCommandManager(this.client, undefined, this);
}
} else if (!this.partial && typeof this.bot !== 'boolean') {
this.bot = false;
}
if ('discriminator' in data) {
/**
* A discriminator based on username for the user
* @type {?string}
*/
this.discriminator = data.discriminator;
} else {
this.discriminator ??= null;
}
if ('discriminator' in data) {
/**
* A discriminator based on username for the user
* @type {?string}
*/
this.discriminator = data.discriminator;
} else {
this.discriminator ??= null;
}
if ('avatar' in data) {
/**
* The user avatar's hash
* @type {?string}
*/
this.avatar = data.avatar;
} else {
this.avatar ??= null;
}
if ('avatar' in data) {
/**
* The user avatar's hash
* @type {?string}
*/
this.avatar = data.avatar;
} else {
this.avatar ??= null;
}
if ('banner' in data) {
/**
* The user banner's hash
* <info>The user must be force fetched for this property to be present or be updated</info>
* @type {?string}
*/
this.banner = data.banner;
} else if (this.banner !== null) {
this.banner ??= undefined;
}
if ('banner' in data) {
/**
* The user banner's hash
* <info>The user must be force fetched for this property to be present or be updated</info>
* @type {?string}
*/
this.banner = data.banner;
} else if (this.banner !== null) {
this.banner ??= undefined;
}
if ('accent_color' in data) {
/**
* The base 10 accent color of the user's banner
* <info>The user must be force fetched for this property to be present or be updated</info>
* @type {?number}
*/
this.accentColor = data.accent_color;
} else if (this.accentColor !== null) {
this.accentColor ??= undefined;
}
if ('accent_color' in data) {
/**
* The base 10 accent color of the user's banner
* <info>The user must be force fetched for this property to be present or be updated</info>
* @type {?number}
*/
this.accentColor = data.accent_color;
} else if (this.accentColor !== null) {
this.accentColor ??= undefined;
}
if ('system' in data) {
/**
* Whether the user is an Official Discord System user (part of the urgent message system)
* @type {?boolean}
*/
this.system = Boolean(data.system);
} else if (!this.partial && typeof this.system !== 'boolean') {
this.system = false;
}
if ('system' in data) {
/**
* Whether the user is an Official Discord System user (part of the urgent message system)
* @type {?boolean}
*/
this.system = Boolean(data.system);
} else if (!this.partial && typeof this.system !== 'boolean') {
this.system = false;
}
if ('public_flags' in data) {
/**
* The flags for this user
* @type {?UserFlags}
*/
this.flags = new UserFlags(data.public_flags);
}
}
if ('public_flags' in data) {
/**
* The flags for this user
* @type {?UserFlags}
*/
this.flags = new UserFlags(data.public_flags);
}
}
/**
* Check relationship status
* @readonly
*/
get relationships() {
const i = this.client.relationships.cache.get(this.id) ?? 0;
return Relationship[parseInt(i)];
}
/**
* Check relationship status
* @readonly
*/
get relationships() {
const i = this.client.relationships.cache.get(this.id) ?? 0;
return Relationship[parseInt(i)];
}
/**
* Check note
* @readonly
*/
get note() {
return this.client.user.notes.get(this.id);
}
/**
* Check note
* @readonly
*/
get note() {
return this.client.user.notes.get(this.id);
}
// Code written by https://github.com/aiko-chan-ai
_ProfilePatch(data) {
if (!data) return;
// Code written by https://github.com/aiko-chan-ai
_ProfilePatch(data) {
if (!data) return;
if (data.connected_accounts.length > 0)
this.connectedAccounts = data.connected_accounts;
if (data.connected_accounts.length > 0) {
this.connectedAccounts = data.connected_accounts;
}
if ('premium_since' in data) {
const date = new Date(data.premium_since);
this.premiumSince = date.getTime();
}
if ('premium_since' in data) {
const date = new Date(data.premium_since);
this.premiumSince = date.getTime();
}
if ('premium_guild_since' in data) {
const date = new Date(data.premium_guild_since);
this.premiumGuildSince = date.getTime();
}
if ('premium_guild_since' in data) {
const date = new Date(data.premium_guild_since);
this.premiumGuildSince = date.getTime();
}
this.mutualGuilds = new Collection(
data.mutual_guilds.map((obj) => [obj.id, obj]),
);
}
this.mutualGuilds = new Collection(data.mutual_guilds.map(obj => [obj.id, obj]));
}
/**
* Get profile from Discord, if client is in a server with the target.
* <br>Code written by https://github.com/aiko-chan-ai
*/
async getProfile() {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
try {
const data = await this.client.api.users(this.id).profile.get();
this._ProfilePatch(data);
return this;
} catch (e) {
throw e;
}
}
/**
* Get profile from Discord, if client is in a server with the target.
* <br>Code written by https://github.com/aiko-chan-ai
*/
async getProfile() {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
try {
const data = await this.client.api.users(this.id).profile.get();
this._ProfilePatch(data);
return this;
} catch (e) {
throw e;
}
}
/**
* Friends the user and send Request [If no request]
* @returns {Promise<User>} the user object
*/
async setFriend() {
return this.client.relationships.addFriend(this);
}
/**
* Friends the user and send Request [If no request]
* @returns {Promise<User>} the user object
*/
async setFriend() {
return this.client.relationships.addFriend(this);
}
/**
* Send Friend Request to the user
* @returns {Promise<User>} the user object
*/
async sendFriendRequest() {
return this.client.relationships.sendFriendRequest(
this.username,
this.discriminator,
);
}
/**
* Blocks the user
* @returns {Promise<User>} the user object
*/
async setBlock() {
return this.client.relationships.addBlocked(this);
}
/**
* Send Friend Request to the user
* @returns {Promise<User>} the user object
*/
async sendFriendRequest() {
return this.client.relationships.sendFriendRequest(this.username, this.discriminator);
}
/**
* Blocks the user
* @returns {Promise<User>} the user object
*/
async setBlock() {
return this.client.relationships.addBlocked(this);
}
/**
* Removes the user from your blocks list
* @returns {Promise<User>} the user object
*/
async unBlock() {
return this.client.relationships.deleteBlocked(this);
}
/**
* Removes the user from your blocks list
* @returns {Promise<User>} the user object
*/
async unBlock() {
return this.client.relationships.deleteBlocked(this);
}
/**
* Removes the user from your friends list
* @returns {Promise<User>} the user object
*/
unFriend() {
return this.client.relationships.deleteFriend(this);
}
/**
* Removes the user from your friends list
* @returns {Promise<User>} the user object
*/
unFriend() {
return this.client.relationships.deleteFriend(this);
}
/**
* Whether this User is a partial
* @type {boolean}
* @readonly
*/
get partial() {
return typeof this.username !== 'string';
}
/**
* Whether this User is a partial
* @type {boolean}
* @readonly
*/
get partial() {
return typeof this.username !== 'string';
}
/**
* The timestamp the user was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return SnowflakeUtil.timestampFrom(this.id);
}
/**
* The timestamp the user was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return SnowflakeUtil.timestampFrom(this.id);
}
/**
* The time the user was created at
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* The time the user was created at
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* A link to the user's avatar.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
avatarURL({ format, size, dynamic } = {}) {
if (!this.avatar) return null;
return this.client.rest.cdn.Avatar(
this.id,
this.avatar,
format,
size,
dynamic,
);
}
/**
* A link to the user's avatar.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
avatarURL({ format, size, dynamic } = {}) {
if (!this.avatar) return null;
return this.client.rest.cdn.Avatar(this.id, this.avatar, format, size, dynamic);
}
/**
* A link to the user's default avatar
* @type {string}
* @readonly
*/
get defaultAvatarURL() {
return this.client.rest.cdn.DefaultAvatar(this.discriminator % 5);
}
/**
* A link to the user's default avatar
* @type {string}
* @readonly
*/
get defaultAvatarURL() {
return this.client.rest.cdn.DefaultAvatar(this.discriminator % 5);
}
/**
* A link to the user's avatar if they have one.
* Otherwise a link to their default avatar will be returned.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {string}
*/
displayAvatarURL(options) {
return this.avatarURL(options) ?? this.defaultAvatarURL;
}
/**
* A link to the user's avatar if they have one.
* Otherwise a link to their default avatar will be returned.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {string}
*/
displayAvatarURL(options) {
return this.avatarURL(options) ?? this.defaultAvatarURL;
}
/**
* The hexadecimal version of the user accent color, with a leading hash
* <info>The user must be force fetched for this property to be present</info>
* @type {?string}
* @readonly
*/
get hexAccentColor() {
if (typeof this.accentColor !== 'number') return this.accentColor;
return `#${this.accentColor.toString(16).padStart(6, '0')}`;
}
/**
* The hexadecimal version of the user accent color, with a leading hash
* <info>The user must be force fetched for this property to be present</info>
* @type {?string}
* @readonly
*/
get hexAccentColor() {
if (typeof this.accentColor !== 'number') return this.accentColor;
return `#${this.accentColor.toString(16).padStart(6, '0')}`;
}
/**
* A link to the user's banner.
* <info>This method will throw an error if called before the user is force fetched.
* See {@link User#banner} for more info</info>
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
bannerURL({ format, size, dynamic } = {}) {
if (typeof this.banner === 'undefined')
throw new Error('USER_BANNER_NOT_FETCHED');
if (!this.banner) return null;
return this.client.rest.cdn.Banner(
this.id,
this.banner,
format,
size,
dynamic,
);
}
/**
* A link to the user's banner.
* <info>This method will throw an error if called before the user is force fetched.
* See {@link User#banner} for more info</info>
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
bannerURL({ format, size, dynamic } = {}) {
if (typeof this.banner === 'undefined') {
throw new Error('USER_BANNER_NOT_FETCHED');
}
if (!this.banner) return null;
return this.client.rest.cdn.Banner(this.id, this.banner, format, size, dynamic);
}
/**
* The Discord "tag" (e.g. `hydrabolt#0001`) for this user
* @type {?string}
* @readonly
*/
get tag() {
return typeof this.username === 'string'
? `${this.username}#${this.discriminator}`
: null;
}
/**
* The Discord "tag" (e.g. `hydrabolt#0001`) for this user
* @type {?string}
* @readonly
*/
get tag() {
return typeof this.username === 'string' ? `${this.username}#${this.discriminator}` : null;
}
/**
* The DM between the client's user and this user
* @type {?DMChannel}
* @readonly
*/
get dmChannel() {
return this.client.users.dmChannel(this.id);
}
/**
* The DM between the client's user and this user
* @type {?DMChannel}
* @readonly
*/
get dmChannel() {
return this.client.users.dmChannel(this.id);
}
/**
* Creates a DM channel between the client and the user.
* @param {boolean} [force=false] Whether to skip the cache check and request the API
* @returns {Promise<DMChannel>}
*/
createDM(force = false) {
return this.client.users.createDM(this.id, force);
}
/**
* Creates a DM channel between the client and the user.
* @param {boolean} [force=false] Whether to skip the cache check and request the API
* @returns {Promise<DMChannel>}
*/
createDM(force = false) {
return this.client.users.createDM(this.id, force);
}
/**
* Deletes a DM channel (if one exists) between the client and the user. Resolves with the channel if successful.
* @returns {Promise<DMChannel>}
*/
deleteDM() {
return this.client.users.deleteDM(this.id);
}
/**
* Deletes a DM channel (if one exists) between the client and the user. Resolves with the channel if successful.
* @returns {Promise<DMChannel>}
*/
deleteDM() {
return this.client.users.deleteDM(this.id);
}
/**
* Checks if the user is equal to another.
* It compares id, username, discriminator, avatar, banner, accent color, and bot flags.
* It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties.
* @param {User} user User to compare with
* @returns {boolean}
*/
equals(user) {
return (
user &&
this.id === user.id &&
this.username === user.username &&
this.discriminator === user.discriminator &&
this.avatar === user.avatar &&
this.flags?.bitfield === user.flags?.bitfield &&
this.banner === user.banner &&
this.accentColor === user.accentColor
);
}
/**
* Checks if the user is equal to another.
* It compares id, username, discriminator, avatar, banner, accent color, and bot flags.
* It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties.
* @param {User} user User to compare with
* @returns {boolean}
*/
equals(user) {
return (
user &&
this.id === user.id &&
this.username === user.username &&
this.discriminator === user.discriminator &&
this.avatar === user.avatar &&
this.flags?.bitfield === user.flags?.bitfield &&
this.banner === user.banner &&
this.accentColor === user.accentColor
);
}
/**
* Compares the user with an API user object
* @param {APIUser} user The API user object to compare
* @returns {boolean}
* @private
*/
_equals(user) {
return (
user &&
this.id === user.id &&
this.username === user.username &&
this.discriminator === user.discriminator &&
this.avatar === user.avatar &&
this.flags?.bitfield === user.public_flags &&
('banner' in user ? this.banner === user.banner : true) &&
('accent_color' in user ? this.accentColor === user.accent_color : true)
);
}
/**
* Compares the user with an API user object
* @param {APIUser} user The API user object to compare
* @returns {boolean}
* @private
*/
_equals(user) {
return (
user &&
this.id === user.id &&
this.username === user.username &&
this.discriminator === user.discriminator &&
this.avatar === user.avatar &&
this.flags?.bitfield === user.public_flags &&
('banner' in user ? this.banner === user.banner : true) &&
('accent_color' in user ? this.accentColor === user.accent_color : true)
);
}
/**
* Fetches this user's flags.
* @param {boolean} [force=false] Whether to skip the cache check and request the API
* @returns {Promise<UserFlags>}
*/
fetchFlags(force = false) {
return this.client.users.fetchFlags(this.id, { force });
}
/**
* Fetches this user's flags.
* @param {boolean} [force=false] Whether to skip the cache check and request the API
* @returns {Promise<UserFlags>}
*/
fetchFlags(force = false) {
return this.client.users.fetchFlags(this.id, { force });
}
/**
* Fetches this user.
* @param {boolean} [force=true] Whether to skip the cache check and request the API
* @returns {Promise<User>}
*/
fetch(force = true) {
return this.client.users.fetch(this.id, { force });
}
/**
* Fetches this user.
* @param {boolean} [force=true] Whether to skip the cache check and request the API
* @returns {Promise<User>}
*/
fetch(force = true) {
return this.client.users.fetch(this.id, { force });
}
/**
* When concatenated with a string, this automatically returns the user's mention instead of the User object.
* @returns {string}
* @example
* // Logs: Hello from <@123456789012345678>!
* console.log(`Hello from ${user}!`);
*/
toString() {
return `<@${this.id}>`;
}
/**
* When concatenated with a string, this automatically returns the user's mention instead of the User object.
* @returns {string}
* @example
* // Logs: Hello from <@123456789012345678>!
* console.log(`Hello from ${user}!`);
*/
toString() {
return `<@${this.id}>`;
}
toJSON(...props) {
const json = super.toJSON(
{
createdTimestamp: true,
defaultAvatarURL: true,
hexAccentColor: true,
tag: true,
},
...props,
);
json.avatarURL = this.avatarURL();
json.displayAvatarURL = this.displayAvatarURL();
json.bannerURL = this.banner ? this.bannerURL() : this.banner;
return json;
}
toJSON(...props) {
const json = super.toJSON(
{
createdTimestamp: true,
defaultAvatarURL: true,
hexAccentColor: true,
tag: true,
},
...props,
);
json.avatarURL = this.avatarURL();
json.displayAvatarURL = this.displayAvatarURL();
json.bannerURL = this.banner ? this.bannerURL() : this.banner;
return json;
}
/**
* Set note to user
* @param {String<User.note>} note Note to set
* @returns {Promise<User.note>}
*/
async setNote(note = null) {
await this.client.api.users['@me'].notes(id).put({ data: { note } });
return (this.note = note);
}
/**
* Set note to user
* @param {String<User.note>} note Note to set
* @returns {Promise<User.note>}
*/
async setNote(note = null) {
await this.client.api.users['@me'].notes(id).put({ data: { note } });
return (this.note = note);
}
// These are here only for documentation purposes - they are implemented by TextBasedChannel
/* eslint-disable no-empty-function */
send() {}
// These are here only for documentation purposes - they are implemented by TextBasedChannel
/* eslint-disable no-empty-function */
send() {}
}
TextBasedChannel.applyToClass(User);

View File

@@ -2,369 +2,357 @@
const axios = require('axios');
const baseURL = 'https://sagiri-fansub.tk/embed?';
const hiddenCharter =
'||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||';
'||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||';
const { RangeError } = require('../errors');
const Util = require('../util/Util');
class WebEmbed {
constructor(data = {}) {
this._setup(data);
/**
* Shorten the link
* @type {?boolean}
*/
this.shorten = data.shorten ?? true;
constructor(data = {}) {
this._setup(data);
/**
* Shorten the link
* @type {?boolean}
*/
this.shorten = data.shorten ?? true;
/**
* Hidden Embed link
* @type {?boolean}
*/
this.hidden = data.hidden ?? false;
}
/**
* @private
* @param {object} data
*/
_setup(data) {
/**
* Type image of this embed
* @type {?thumbnail | image}
*/
this.imageType = 'thumbnail';
/**
* The title of this embed
* @type {?string}
*/
this.title = data.title ?? null;
/**
* Hidden Embed link
* @type {?boolean}
*/
this.hidden = data.hidden ?? false;
}
/**
* @private
* @param {object} data
*/
_setup(data) {
/**
* Type image of this embed
* @type {?thumbnail | image}
*/
this.imageType = 'thumbnail';
/**
* The title of this embed
* @type {?string}
*/
this.title = data.title ?? null;
/**
* The description of this embed
* @type {?string}
*/
this.description = data.description ?? null;
/**
* The description of this embed
* @type {?string}
*/
this.description = data.description ?? null;
/**
* The URL of this embed
* @type {?string}
*/
this.url = data.url ?? null;
/**
* The URL of this embed
* @type {?string}
*/
this.url = data.url ?? null;
/**
* The color of this embed
* @type {?number}
*/
this.color = 'color' in data ? Util.resolveColor(data.color) : null;
/**
* The color of this embed
* @type {?number}
*/
this.color = 'color' in data ? Util.resolveColor(data.color) : null;
/**
* Represents the image of a MessageEmbed
* @typedef {Object} MessageEmbedImage
* @property {string} url URL for this image
* @property {string} proxyURL ProxyURL for this image
* @property {number} height Height of this image
* @property {number} width Width of this image
*/
/**
* Represents the image of a MessageEmbed
* @typedef {Object} MessageEmbedImage
* @property {string} url URL for this image
* @property {string} proxyURL ProxyURL for this image
* @property {number} height Height of this image
* @property {number} width Width of this image
*/
/**
* The image of this embed, if there is one
* @type {?MessageEmbedImage}
*/
this.image = data.image
? {
url: data.image.url,
proxyURL: data.image.proxyURL ?? data.image.proxy_url,
height: data.image.height,
width: data.image.width,
}
: null;
/**
* The thumbnail of this embed (if there is one)
* @type {?MessageEmbedThumbnail}
*/
this.thumbnail = data.thumbnail
? {
url: data.thumbnail.url,
proxyURL: data.thumbnail.proxyURL ?? data.thumbnail.proxy_url,
height: data.thumbnail.height,
width: data.thumbnail.width,
}
: null;
/**
* Represents the video of a MessageEmbed
* @typedef {Object} MessageEmbedVideo
* @property {string} url URL of this video
* @property {string} proxyURL ProxyURL for this video
* @property {number} height Height of this video
* @property {number} width Width of this video
*/
/**
* The video of this embed (if there is one)
* @type {?MessageEmbedVideo}
* @readonly
*/
this.video = data.video
? {
url: data.video.url,
proxyURL: data.video.proxyURL ?? data.video.proxy_url,
height: data.video.height,
width: data.video.width,
}
: null;
/**
* Represents the author field of a MessageEmbed
* @typedef {Object} MessageEmbedAuthor
* @property {string} name The name of this author
* @property {string} url URL of this author
* @property {string} iconURL URL of the icon for this author
* @property {string} proxyIconURL Proxied URL of the icon for this author
*/
/**
* The author of this embed (if there is one)
* @type {?MessageEmbedAuthor}
*/
this.author = data.author
? {
name: data.author.name,
url: data.author.url,
}
: null;
/**
* Represents the provider of a MessageEmbed
* @typedef {Object} MessageEmbedProvider
* @property {string} name The name of this provider
* @property {string} url URL of this provider
*/
/**
* The provider of this embed (if there is one)
* @type {?MessageEmbedProvider}
*/
this.provider = data.provider
? {
name: data.provider.name,
url: data.provider.name,
}
: null;
}
/**
* The options to provide for setting an author for a {@link MessageEmbed}.
* @typedef {Object} EmbedAuthorData
* @property {string} name The name of this author.
*/
/**
* Sets the author of this embed.
* @param {string|EmbedAuthorData|null} options The options to provide for the author.
* Provide `null` to remove the author data.
* @returns {MessageEmbed}
*/
setAuthor(options) {
if (options === null) {
this.author = {};
return this;
}
const { name, url } = options;
this.author = {
name: Util.verifyString(name, RangeError, 'EMBED_AUTHOR_NAME'),
url,
};
return this;
}
/**
* The options to provide for setting an provider for a {@link MessageEmbed}.
* @typedef {Object} EmbedProviderData
* @property {string} name The name of this provider.
*/
/**
* Sets the provider of this embed.
* @param {string|EmbedProviderData|null} options The options to provide for the provider.
* Provide `null` to remove the provider data.
* @returns {MessageEmbed}
*/
setProvider(options) {
if (options === null) {
this.provider = {};
return this;
}
const { name, url } = options;
this.provider = {
name: Util.verifyString(name, RangeError, 'EMBED_PROVIDER_NAME'),
url,
};
return this;
}
/**
* Sets the color of this embed.
* @param {ColorResolvable} color The color of the embed
* @returns {MessageEmbed}
*/
setColor(color) {
this.color = Util.resolveColor(color);
return this;
}
/**
* Sets the description of this embed.
* @param {string} description The description (Limit 350 characters)
* @returns {MessageEmbed}
*/
setDescription(description) {
this.description = Util.verifyString(
description,
RangeError,
'EMBED_DESCRIPTION',
);
return this;
}
/**
* Sets the image of this embed.
* @param {string} url The URL of the image
* @returns {MessageEmbed}
*/
setImage(url) {
if (this.thumbnail && this.thumbnail.url) {
console.warn('You can only set image or thumbnail per embed.');
this.thumbnail.url = null;
}
this.imageType = 'image';
this.image = { url };
return this;
}
/**
* Sets the thumbnail of this embed.
* @param {string} url The URL of the image
* @returns {MessageEmbed}
*/
setThumbnail(url) {
if (this.image && this.image.url) {
console.warn('You can only set image or thumbnail per embed.');
this.image.url = null;
}
this.imageType = 'thumbnail';
this.thumbnail = { url };
return this;
}
/**
* Sets the video of this embed.
* @param {string} url The URL of the video
* @returns {MessageEmbed}
*/
setVideo(url) {
this.video = { url };
return this;
}
/**
* Sets the title of this embed.
* @param {string} title The title
* @returns {MessageEmbed}
*/
setTitle(title) {
this.title = Util.verifyString(title, RangeError, 'EMBED_TITLE');
return this;
}
/**
* Sets the URL of this embed.
* @param {string} url The URL
* @returns {MessageEmbed}
*/
setURL(url) {
this.url = url;
return this;
}
/**
* Return Message Content + Embed (if hidden, pls check content length because it has 1000+ length)
* @returns {string} Message Content
*/
async toMessage() {
const arrayQuery = [`image_type=${this.imageType}`];
if (this.title) {
arrayQuery.push(`title=${encodeURIComponent(this.title)}`);
}
if (this.description) {
arrayQuery.push(`description=${encodeURIComponent(this.description)}`);
}
if (this.url) {
arrayQuery.push(`url=${encodeURIComponent(this.url)}`);
}
if (this.color) {
arrayQuery.push(
`color=${encodeURIComponent('#' + this.color.toString(16))}`,
);
}
if (this.image?.url) {
arrayQuery.push(`image=${encodeURIComponent(this.image.url)}`);
}
if (this.video?.url) {
arrayQuery.push(`video=${encodeURIComponent(this.video.url)}`);
}
if (this.author) {
if (this.author.name)
arrayQuery.push(`author_name=${encodeURIComponent(this.author.name)}`);
if (this.author.url)
arrayQuery.push(`author_url=${encodeURIComponent(this.author.url)}`);
}
if (this.provider) {
if (this.provider.name)
arrayQuery.push(
`provider_name=${encodeURIComponent(this.provider.name)}`,
);
if (this.provider.url)
arrayQuery.push(
`provider_url=${encodeURIComponent(this.provider.url)}`,
);
}
if (this.thumbnail?.url) {
arrayQuery.push(`image=${encodeURIComponent(this.thumbnail.url)}`);
/**
* The image of this embed, if there is one
* @type {?MessageEmbedImage}
*/
this.image = data.image
? {
url: data.image.url,
proxyURL: data.image.proxyURL ?? data.image.proxy_url,
height: data.image.height,
width: data.image.width,
}
const fullURL = `${baseURL}${arrayQuery.join('&')}`;
if (this.shorten) {
const url = await getShorten(fullURL);
if (!url) console.log('Cannot shorten URL in WebEmbed');
return this.hidden
? `${hiddenCharter} ${url || fullURL}`
: url || fullURL;
} else {
return this.hidden ? `${hiddenCharter} ${fullURL}` : fullURL;
}
}
: null;
/**
* The thumbnail of this embed (if there is one)
* @type {?MessageEmbedThumbnail}
*/
this.thumbnail = data.thumbnail
? {
url: data.thumbnail.url,
proxyURL: data.thumbnail.proxyURL ?? data.thumbnail.proxy_url,
height: data.thumbnail.height,
width: data.thumbnail.width,
}
: null;
/**
* Represents the video of a MessageEmbed
* @typedef {Object} MessageEmbedVideo
* @property {string} url URL of this video
* @property {string} proxyURL ProxyURL for this video
* @property {number} height Height of this video
* @property {number} width Width of this video
*/
/**
* The video of this embed (if there is one)
* @type {?MessageEmbedVideo}
* @readonly
*/
this.video = data.video
? {
url: data.video.url,
proxyURL: data.video.proxyURL ?? data.video.proxy_url,
height: data.video.height,
width: data.video.width,
}
: null;
/**
* Represents the author field of a MessageEmbed
* @typedef {Object} MessageEmbedAuthor
* @property {string} name The name of this author
* @property {string} url URL of this author
* @property {string} iconURL URL of the icon for this author
* @property {string} proxyIconURL Proxied URL of the icon for this author
*/
/**
* The author of this embed (if there is one)
* @type {?MessageEmbedAuthor}
*/
this.author = data.author
? {
name: data.author.name,
url: data.author.url,
}
: null;
/**
* Represents the provider of a MessageEmbed
* @typedef {Object} MessageEmbedProvider
* @property {string} name The name of this provider
* @property {string} url URL of this provider
*/
/**
* The provider of this embed (if there is one)
* @type {?MessageEmbedProvider}
*/
this.provider = data.provider
? {
name: data.provider.name,
url: data.provider.name,
}
: null;
}
/**
* The options to provide for setting an author for a {@link MessageEmbed}.
* @typedef {Object} EmbedAuthorData
* @property {string} name The name of this author.
*/
/**
* Sets the author of this embed.
* @param {string|EmbedAuthorData|null} options The options to provide for the author.
* Provide `null` to remove the author data.
* @returns {MessageEmbed}
*/
setAuthor(options) {
if (options === null) {
this.author = {};
return this;
}
const { name, url } = options;
this.author = {
name: Util.verifyString(name, RangeError, 'EMBED_AUTHOR_NAME'),
url,
};
return this;
}
/**
* The options to provide for setting an provider for a {@link MessageEmbed}.
* @typedef {Object} EmbedProviderData
* @property {string} name The name of this provider.
*/
/**
* Sets the provider of this embed.
* @param {string|EmbedProviderData|null} options The options to provide for the provider.
* Provide `null` to remove the provider data.
* @returns {MessageEmbed}
*/
setProvider(options) {
if (options === null) {
this.provider = {};
return this;
}
const { name, url } = options;
this.provider = {
name: Util.verifyString(name, RangeError, 'EMBED_PROVIDER_NAME'),
url,
};
return this;
}
/**
* Sets the color of this embed.
* @param {ColorResolvable} color The color of the embed
* @returns {MessageEmbed}
*/
setColor(color) {
this.color = Util.resolveColor(color);
return this;
}
/**
* Sets the description of this embed.
* @param {string} description The description (Limit 350 characters)
* @returns {MessageEmbed}
*/
setDescription(description) {
this.description = Util.verifyString(description, RangeError, 'EMBED_DESCRIPTION');
return this;
}
/**
* Sets the image of this embed.
* @param {string} url The URL of the image
* @returns {MessageEmbed}
*/
setImage(url) {
if (this.thumbnail && this.thumbnail.url) {
console.warn('You can only set image or thumbnail per embed.');
this.thumbnail.url = null;
}
this.imageType = 'image';
this.image = { url };
return this;
}
/**
* Sets the thumbnail of this embed.
* @param {string} url The URL of the image
* @returns {MessageEmbed}
*/
setThumbnail(url) {
if (this.image && this.image.url) {
console.warn('You can only set image or thumbnail per embed.');
this.image.url = null;
}
this.imageType = 'thumbnail';
this.thumbnail = { url };
return this;
}
/**
* Sets the video of this embed.
* @param {string} url The URL of the video
* @returns {MessageEmbed}
*/
setVideo(url) {
this.video = { url };
return this;
}
/**
* Sets the title of this embed.
* @param {string} title The title
* @returns {MessageEmbed}
*/
setTitle(title) {
this.title = Util.verifyString(title, RangeError, 'EMBED_TITLE');
return this;
}
/**
* Sets the URL of this embed.
* @param {string} url The URL
* @returns {MessageEmbed}
*/
setURL(url) {
this.url = url;
return this;
}
/**
* Return Message Content + Embed (if hidden, pls check content length because it has 1000+ length)
* @returns {string} Message Content
*/
async toMessage() {
const arrayQuery = [`image_type=${this.imageType}`];
if (this.title) {
arrayQuery.push(`title=${encodeURIComponent(this.title)}`);
}
if (this.description) {
arrayQuery.push(`description=${encodeURIComponent(this.description)}`);
}
if (this.url) {
arrayQuery.push(`url=${encodeURIComponent(this.url)}`);
}
if (this.color) {
arrayQuery.push(`color=${encodeURIComponent('#' + this.color.toString(16))}`);
}
if (this.image?.url) {
arrayQuery.push(`image=${encodeURIComponent(this.image.url)}`);
}
if (this.video?.url) {
arrayQuery.push(`video=${encodeURIComponent(this.video.url)}`);
}
if (this.author) {
if (this.author.name) {
arrayQuery.push(`author_name=${encodeURIComponent(this.author.name)}`);
}
if (this.author.url) {
arrayQuery.push(`author_url=${encodeURIComponent(this.author.url)}`);
}
}
if (this.provider) {
if (this.provider.name) {
arrayQuery.push(`provider_name=${encodeURIComponent(this.provider.name)}`);
}
if (this.provider.url) {
arrayQuery.push(`provider_url=${encodeURIComponent(this.provider.url)}`);
}
}
if (this.thumbnail?.url) {
arrayQuery.push(`image=${encodeURIComponent(this.thumbnail.url)}`);
}
const fullURL = `${baseURL}${arrayQuery.join('&')}`;
if (this.shorten) {
const url = await getShorten(fullURL);
if (!url) console.log('Cannot shorten URL in WebEmbed');
return this.hidden ? `${hiddenCharter} ${url || fullURL}` : url || fullURL;
} else {
return this.hidden ? `${hiddenCharter} ${fullURL}` : fullURL;
}
}
}
// Credit: https://www.npmjs.com/package/node-url-shortener + google :))
const getShorten = async (url) => {
const APIurl = [
// 'https://is.gd/create.php?format=simple&url=', :(
'https://tinyurl.com/api-create.php?url=',
'https://sagiri-fansub.tk/api/v1/short?url=', // my api, pls don't ddos :(
'https://lazuee.ga/api/v1/shorten?url='
// 'https://cdpt.in/shorten?url=', Redirects 5s :(
];
try {
const res = await axios.get(
`${
APIurl[Math.floor(Math.random() * APIurl.length)]
}${encodeURIComponent(url)}`,
);
if (typeof res.data == 'string') return res.data;
else if (typeof res.data == 'object') return res.data.shorten;
else throw null;
} catch {
return void 0;
}
}
const getShorten = async url => {
const APIurl = [
// 'https://is.gd/create.php?format=simple&url=', :(
'https://tinyurl.com/api-create.php?url=',
'https://sagiri-fansub.tk/api/v1/short?url=', // my api, pls don't ddos :(
'https://lazuee.ga/api/v1/shorten?url=',
// 'https://cdpt.in/shorten?url=', Redirects 5s :(
];
try {
const res = await axios.get(`${APIurl[Math.floor(Math.random() * APIurl.length)]}${encodeURIComponent(url)}`);
if (typeof res.data == 'string') return res.data;
else if (typeof res.data == 'object') return res.data.shorten;
else throw null;
} catch {
return void 0;
}
};
module.exports = WebEmbed;
module.exports.hiddenEmbed = hiddenCharter;

View File

@@ -316,15 +316,12 @@ class Webhook {
if (!this.token) throw new Error('WEBHOOK_TOKEN_UNAVAILABLE');
let messagePayload;
if (options instanceof MessagePayload) {
messagePayload = await options.resolveData();
} else {
messagePayload = await MessagePayload.create(
message instanceof Message ? message : this,
options,
).resolveData();
}
const { data, files } = await messagePayload.resolveFiles();
if (options instanceof MessagePayload) {
messagePayload = await options.resolveData();
} else {
messagePayload = await MessagePayload.create(message instanceof Message ? message : this, options).resolveData();
}
const { data, files } = await messagePayload.resolveFiles();
const d = await this.client.api
.webhooks(this.id, this.token)

View File

@@ -4,104 +4,104 @@ const process = require('node:process');
const Package = (exports.Package = require('../../package.json'));
const { Error, RangeError, TypeError } = require('../errors');
const listUserAgent = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.107",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 YaBrowser/19.9.3.314 Yowser/2.5 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Safari/605.1.15",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0",
"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:70.0) Gecko/20100101 Firefox/70.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/77.0.3865.90 Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.107",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0 Waterfox/56.2.14",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)",
"Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (Linux; Android 6.0.1; SAMSUNG SM-G570Y Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/44.0.2403.133 Mobile Safari/537.36",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; FSL 7.0.5.01003)",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0",
"Mozilla/5.0 (X11; U; Linux x86_64; de; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)",
"Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.0) Opera 7.02 Bork-edition [en]",
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1",
"Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1"
]
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.107',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 YaBrowser/19.9.3.314 Yowser/2.5 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0',
'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:70.0) Gecko/20100101 Firefox/70.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/77.0.3865.90 Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.107',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:69.0) Gecko/20100101 Firefox/69.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0 Waterfox/56.2.14',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)',
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4',
'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'Mozilla/5.0 (Linux; Android 6.0.1; SAMSUNG SM-G570Y Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/44.0.2403.133 Mobile Safari/537.36',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; FSL 7.0.5.01003)',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0',
'Mozilla/5.0 (X11; U; Linux x86_64; de; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)',
'Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.0) Opera 7.02 Bork-edition [en]',
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1',
'Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1',
];
exports.DMScanLevel = {
0: 'NOT_SCAN',
@@ -116,36 +116,36 @@ exports.stickerAnimationMode = {
};
exports.localeObject = {
da: 'DANISH',
de: 'GERMAN',
'en-GB': 'ENGLISH_UK',
'en-US': 'ENGLISH_US',
'es-ES': 'SPANISH',
fr: 'FRENCH',
hr: 'CROATIAN',
it: 'ITALIAN',
lt: 'LITHUANIAN',
hu: 'HUNGARIAN',
nl: 'DUTCH',
no: 'NORWEGIAN',
pl: 'POLISH',
'pt-BR': 'BRAZILIAN_PORTUGUESE',
ro: 'ROMANIA_ROMANIAN',
fi: 'FINNISH',
'sv-SE': 'SWEDISH',
vi: 'VIETNAMESE',
tr: 'TURKISH',
cs: 'CZECH',
el: 'GREEK',
bg: 'BULGARIAN',
ru: 'RUSSIAN',
uk: 'UKRAINIAN',
hi: 'HINDI',
th: 'THAI',
'zh-CN': 'CHINA_CHINESE',
ja: 'JAPANESE',
'zh-TW': 'TAIWAN_CHINESE',
ko: 'KOREAN',
da: 'DANISH',
de: 'GERMAN',
'en-GB': 'ENGLISH_UK',
'en-US': 'ENGLISH_US',
'es-ES': 'SPANISH',
fr: 'FRENCH',
hr: 'CROATIAN',
it: 'ITALIAN',
lt: 'LITHUANIAN',
hu: 'HUNGARIAN',
nl: 'DUTCH',
no: 'NORWEGIAN',
pl: 'POLISH',
'pt-BR': 'BRAZILIAN_PORTUGUESE',
ro: 'ROMANIA_ROMANIAN',
fi: 'FINNISH',
'sv-SE': 'SWEDISH',
vi: 'VIETNAMESE',
tr: 'TURKISH',
cs: 'CZECH',
el: 'GREEK',
bg: 'BULGARIAN',
ru: 'RUSSIAN',
uk: 'UKRAINIAN',
hi: 'HINDI',
th: 'THAI',
'zh-CN': 'CHINA_CHINESE',
ja: 'JAPANESE',
'zh-TW': 'TAIWAN_CHINESE',
ko: 'KOREAN',
};
exports.UserAgent = listUserAgent[Math.floor(Math.random() * listUserAgent.length)];
@@ -254,127 +254,127 @@ exports.Status = {
};
exports.Opcodes = {
DISPATCH: 0, // # Receive dispatches an event
HEARTBEAT: 1, // # Send/Receive used for ping checking
IDENTIFY: 2, // # Send used for client handshake
STATUS_UPDATE: 3, // # Send used to update the client status
VOICE_STATE_UPDATE: 4, // # Send used to join/move/leave voice channels
VOICE_GUILD_PING: 5, // # Send used for voice ping checking
RESUME: 6, // # Send used to resume a closed connection
RECONNECT: 7, // # Receive used to tell when to reconnect (sometimes...)
REQUEST_GUILD_MEMBERS: 8, // # Send used to request guild members (when searching for members in the search bar of a guild)
INVALID_SESSION: 9, // # Receive used to notify client they have an invalid session id
HELLO: 10, // # Receive sent immediately after connecting, contains heartbeat and server debug information
HEARTBEAT_ACK: 11, // # Sent immediately following a client heartbeat that was received
// GUILD_SYNC: 12, // # Receive guild_sync but not used anymore
/** Add some opcode from Discum
DISPATCH: 0, // # Receive dispatches an event
HEARTBEAT: 1, // # Send/Receive used for ping checking
IDENTIFY: 2, // # Send used for client handshake
STATUS_UPDATE: 3, // # Send used to update the client status
VOICE_STATE_UPDATE: 4, // # Send used to join/move/leave voice channels
VOICE_GUILD_PING: 5, // # Send used for voice ping checking
RESUME: 6, // # Send used to resume a closed connection
RECONNECT: 7, // # Receive used to tell when to reconnect (sometimes...)
REQUEST_GUILD_MEMBERS: 8, // # Send used to request guild members (when searching for members in the search bar of a guild)
INVALID_SESSION: 9, // # Receive used to notify client they have an invalid session id
HELLO: 10, // # Receive sent immediately after connecting, contains heartbeat and server debug information
HEARTBEAT_ACK: 11, // # Sent immediately following a client heartbeat that was received
// GUILD_SYNC: 12, // # Receive guild_sync but not used anymore
/** Add some opcode from Discum
/* @extends https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/discum/gateway/gateway.py#L56
*/
DM_UPDATE: 13, // # Send used to get dm features
LAZY_REQUEST: 14, // # Send discord responds back with GUILD_MEMBER_LIST_UPDATE type SYNC...
LOBBY_CONNECT: 15,
LOBBY_DISCONNECT: 16,
LOBBY_VOICE_STATE_UPDATE: 17, // # Receive
STREAM_CREATE: 18,
STREAM_DELETE: 19,
STREAM_WATCH: 20,
STREAM_PING: 21, // # Send
STREAM_SET_PAUSED: 22,
REQUEST_APPLICATION_COMMANDS: 24, // # Send request application/bot cmds (user, message, and slash cmds)
DM_UPDATE: 13, // # Send used to get dm features
LAZY_REQUEST: 14, // # Send discord responds back with GUILD_MEMBER_LIST_UPDATE type SYNC...
LOBBY_CONNECT: 15,
LOBBY_DISCONNECT: 16,
LOBBY_VOICE_STATE_UPDATE: 17, // # Receive
STREAM_CREATE: 18,
STREAM_DELETE: 19,
STREAM_WATCH: 20,
STREAM_PING: 21, // # Send
STREAM_SET_PAUSED: 22,
REQUEST_APPLICATION_COMMANDS: 24, // # Send request application/bot cmds (user, message, and slash cmds)
};
exports.Events = {
RATE_LIMIT: 'rateLimit',
INVALID_REQUEST_WARNING: 'invalidRequestWarning',
API_RESPONSE: 'apiResponse',
API_REQUEST: 'apiRequest',
CLIENT_READY: 'ready',
/**
* @deprecated See {@link https://github.com/discord/discord-api-docs/issues/3690 this issue} for more information.
*/
APPLICATION_COMMAND_CREATE: 'applicationCommandCreate',
/**
* @deprecated See {@link https://github.com/discord/discord-api-docs/issues/3690 this issue} for more information.
*/
APPLICATION_COMMAND_DELETE: 'applicationCommandDelete',
/**
* @deprecated See {@link https://github.com/discord/discord-api-docs/issues/3690 this issue} for more information.
*/
APPLICATION_COMMAND_UPDATE: 'applicationCommandUpdate',
GUILD_CREATE: 'guildCreate',
GUILD_DELETE: 'guildDelete',
GUILD_UPDATE: 'guildUpdate',
GUILD_UNAVAILABLE: 'guildUnavailable',
GUILD_MEMBER_ADD: 'guildMemberAdd',
GUILD_MEMBER_REMOVE: 'guildMemberRemove',
GUILD_MEMBER_UPDATE: 'guildMemberUpdate',
GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable',
GUILD_MEMBERS_CHUNK: 'guildMembersChunk',
GUILD_MEMBER_LIST_UPDATE: 'guildMemberListUpdate',
GUILD_INTEGRATIONS_UPDATE: 'guildIntegrationsUpdate',
GUILD_ROLE_CREATE: 'roleCreate',
GUILD_ROLE_DELETE: 'roleDelete',
INVITE_CREATE: 'inviteCreate',
INVITE_DELETE: 'inviteDelete',
GUILD_ROLE_UPDATE: 'roleUpdate',
GUILD_EMOJI_CREATE: 'emojiCreate',
GUILD_EMOJI_DELETE: 'emojiDelete',
GUILD_EMOJI_UPDATE: 'emojiUpdate',
GUILD_BAN_ADD: 'guildBanAdd',
GUILD_BAN_REMOVE: 'guildBanRemove',
CHANNEL_CREATE: 'channelCreate',
CHANNEL_DELETE: 'channelDelete',
CHANNEL_UPDATE: 'channelUpdate',
CHANNEL_PINS_UPDATE: 'channelPinsUpdate',
MESSAGE_CREATE: 'messageCreate',
MESSAGE_DELETE: 'messageDelete',
MESSAGE_UPDATE: 'messageUpdate',
MESSAGE_BULK_DELETE: 'messageDeleteBulk',
MESSAGE_REACTION_ADD: 'messageReactionAdd',
MESSAGE_REACTION_REMOVE: 'messageReactionRemove',
MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll',
MESSAGE_REACTION_REMOVE_EMOJI: 'messageReactionRemoveEmoji',
THREAD_CREATE: 'threadCreate',
THREAD_DELETE: 'threadDelete',
THREAD_UPDATE: 'threadUpdate',
THREAD_LIST_SYNC: 'threadListSync',
THREAD_MEMBER_UPDATE: 'threadMemberUpdate',
THREAD_MEMBERS_UPDATE: 'threadMembersUpdate',
USER_UPDATE: 'userUpdate',
PRESENCE_UPDATE: 'presenceUpdate',
VOICE_SERVER_UPDATE: 'voiceServerUpdate',
VOICE_STATE_UPDATE: 'voiceStateUpdate',
TYPING_START: 'typingStart',
WEBHOOKS_UPDATE: 'webhookUpdate',
INTERACTION_CREATE: 'interactionCreate',
INTERACTION_SUCCESS: 'interactionSuccess',
INTERACTION_FAILED: 'interactionFailed',
ERROR: 'error',
WARN: 'warn',
DEBUG: 'debug',
CACHE_SWEEP: 'cacheSweep',
SHARD_DISCONNECT: 'shardDisconnect',
SHARD_ERROR: 'shardError',
SHARD_RECONNECTING: 'shardReconnecting',
SHARD_READY: 'shardReady',
SHARD_RESUME: 'shardResume',
INVALIDATED: 'invalidated',
RAW: 'raw',
STAGE_INSTANCE_CREATE: 'stageInstanceCreate',
STAGE_INSTANCE_UPDATE: 'stageInstanceUpdate',
STAGE_INSTANCE_DELETE: 'stageInstanceDelete',
GUILD_STICKER_CREATE: 'stickerCreate',
GUILD_STICKER_DELETE: 'stickerDelete',
GUILD_STICKER_UPDATE: 'stickerUpdate',
GUILD_SCHEDULED_EVENT_CREATE: 'guildScheduledEventCreate',
GUILD_SCHEDULED_EVENT_UPDATE: 'guildScheduledEventUpdate',
GUILD_SCHEDULED_EVENT_DELETE: 'guildScheduledEventDelete',
GUILD_SCHEDULED_EVENT_USER_ADD: 'guildScheduledEventUserAdd',
GUILD_SCHEDULED_EVENT_USER_REMOVE: 'guildScheduledEventUserRemove',
RELATIONSHIP_ADD: 'relationshipAdd',
RELATIONSHIP_REMOVE: 'relationshipRemove',
/* Add */
UNHANDLED_PACKET: 'unhandledPacket',
RATE_LIMIT: 'rateLimit',
INVALID_REQUEST_WARNING: 'invalidRequestWarning',
API_RESPONSE: 'apiResponse',
API_REQUEST: 'apiRequest',
CLIENT_READY: 'ready',
/**
* @deprecated See {@link https://github.com/discord/discord-api-docs/issues/3690 this issue} for more information.
*/
APPLICATION_COMMAND_CREATE: 'applicationCommandCreate',
/**
* @deprecated See {@link https://github.com/discord/discord-api-docs/issues/3690 this issue} for more information.
*/
APPLICATION_COMMAND_DELETE: 'applicationCommandDelete',
/**
* @deprecated See {@link https://github.com/discord/discord-api-docs/issues/3690 this issue} for more information.
*/
APPLICATION_COMMAND_UPDATE: 'applicationCommandUpdate',
GUILD_CREATE: 'guildCreate',
GUILD_DELETE: 'guildDelete',
GUILD_UPDATE: 'guildUpdate',
GUILD_UNAVAILABLE: 'guildUnavailable',
GUILD_MEMBER_ADD: 'guildMemberAdd',
GUILD_MEMBER_REMOVE: 'guildMemberRemove',
GUILD_MEMBER_UPDATE: 'guildMemberUpdate',
GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable',
GUILD_MEMBERS_CHUNK: 'guildMembersChunk',
GUILD_MEMBER_LIST_UPDATE: 'guildMemberListUpdate',
GUILD_INTEGRATIONS_UPDATE: 'guildIntegrationsUpdate',
GUILD_ROLE_CREATE: 'roleCreate',
GUILD_ROLE_DELETE: 'roleDelete',
INVITE_CREATE: 'inviteCreate',
INVITE_DELETE: 'inviteDelete',
GUILD_ROLE_UPDATE: 'roleUpdate',
GUILD_EMOJI_CREATE: 'emojiCreate',
GUILD_EMOJI_DELETE: 'emojiDelete',
GUILD_EMOJI_UPDATE: 'emojiUpdate',
GUILD_BAN_ADD: 'guildBanAdd',
GUILD_BAN_REMOVE: 'guildBanRemove',
CHANNEL_CREATE: 'channelCreate',
CHANNEL_DELETE: 'channelDelete',
CHANNEL_UPDATE: 'channelUpdate',
CHANNEL_PINS_UPDATE: 'channelPinsUpdate',
MESSAGE_CREATE: 'messageCreate',
MESSAGE_DELETE: 'messageDelete',
MESSAGE_UPDATE: 'messageUpdate',
MESSAGE_BULK_DELETE: 'messageDeleteBulk',
MESSAGE_REACTION_ADD: 'messageReactionAdd',
MESSAGE_REACTION_REMOVE: 'messageReactionRemove',
MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll',
MESSAGE_REACTION_REMOVE_EMOJI: 'messageReactionRemoveEmoji',
THREAD_CREATE: 'threadCreate',
THREAD_DELETE: 'threadDelete',
THREAD_UPDATE: 'threadUpdate',
THREAD_LIST_SYNC: 'threadListSync',
THREAD_MEMBER_UPDATE: 'threadMemberUpdate',
THREAD_MEMBERS_UPDATE: 'threadMembersUpdate',
USER_UPDATE: 'userUpdate',
PRESENCE_UPDATE: 'presenceUpdate',
VOICE_SERVER_UPDATE: 'voiceServerUpdate',
VOICE_STATE_UPDATE: 'voiceStateUpdate',
TYPING_START: 'typingStart',
WEBHOOKS_UPDATE: 'webhookUpdate',
INTERACTION_CREATE: 'interactionCreate',
INTERACTION_SUCCESS: 'interactionSuccess',
INTERACTION_FAILED: 'interactionFailed',
ERROR: 'error',
WARN: 'warn',
DEBUG: 'debug',
CACHE_SWEEP: 'cacheSweep',
SHARD_DISCONNECT: 'shardDisconnect',
SHARD_ERROR: 'shardError',
SHARD_RECONNECTING: 'shardReconnecting',
SHARD_READY: 'shardReady',
SHARD_RESUME: 'shardResume',
INVALIDATED: 'invalidated',
RAW: 'raw',
STAGE_INSTANCE_CREATE: 'stageInstanceCreate',
STAGE_INSTANCE_UPDATE: 'stageInstanceUpdate',
STAGE_INSTANCE_DELETE: 'stageInstanceDelete',
GUILD_STICKER_CREATE: 'stickerCreate',
GUILD_STICKER_DELETE: 'stickerDelete',
GUILD_STICKER_UPDATE: 'stickerUpdate',
GUILD_SCHEDULED_EVENT_CREATE: 'guildScheduledEventCreate',
GUILD_SCHEDULED_EVENT_UPDATE: 'guildScheduledEventUpdate',
GUILD_SCHEDULED_EVENT_DELETE: 'guildScheduledEventDelete',
GUILD_SCHEDULED_EVENT_USER_ADD: 'guildScheduledEventUserAdd',
GUILD_SCHEDULED_EVENT_USER_REMOVE: 'guildScheduledEventUserRemove',
RELATIONSHIP_ADD: 'relationshipAdd',
RELATIONSHIP_REMOVE: 'relationshipRemove',
/* Add */
UNHANDLED_PACKET: 'unhandledPacket',
};
exports.ShardEvents = {
@@ -1330,8 +1330,8 @@ exports.RelationshipTypes = createEnum([null, 'FRIEND', 'BLOCKED', 'INCOMING_REQ
exports.Relationship = {
0: 'NONE',
1: 'FRIEND',
2: 'BLOCKED',
1: 'FRIEND',
2: 'BLOCKED',
3: 'INCOMING_REQUEST',
4: 'OUTGOING_REQUEST',
};
@@ -1374,7 +1374,7 @@ exports.HypeSquadOptions = createEnum(['LEAVE', 'HOUSE_BRAVERY', 'HOUSE_BRILLIAN
exports._cleanupSymbol = Symbol('djsCleanup');
function keyMirror(arr) {
let tmp = Object.create(null);
const tmp = Object.create(null);
for (const value of arr) tmp[value] = value;
return tmp;
}

View File

@@ -132,7 +132,7 @@ class Options extends null {
*/
static createDefault() {
return {
jsonTransformer: (object) => JSONBig.stringify(object),
jsonTransformer: object => JSONBig.stringify(object),
checkUpdate: true,
readyStatus: false,
autoCookie: true,
@@ -143,14 +143,7 @@ class Options extends null {
messageSweepInterval: 0,
invalidRequestWarningInterval: 0,
intents: 65535,
partials: [
'USER',
'CHANNEL',
'GUILD_MEMBER',
'MESSAGE',
'REACTION',
'GUILD_SCHEDULED_EVENT',
], // Enable the partials
partials: ['USER', 'CHANNEL', 'GUILD_MEMBER', 'MESSAGE', 'REACTION', 'GUILD_SCHEDULED_EVENT'], // Enable the partials
restWsBridgeTimeout: 5_000,
restRequestTimeout: 15_000,
restGlobalRateLimit: 0,
@@ -165,9 +158,9 @@ class Options extends null {
large_threshold: 50,
compress: false,
properties: {
//$os: 'iPhone14,5',
//$browser: 'Discord iOS',
//$device: 'iPhone14,5 OS 15.2',
// $os: 'iPhone14,5',
// $browser: 'Discord iOS',
// $device: 'iPhone14,5 OS 15.2',
$os: 'Windows',
$browser: 'Discord Client',
$device: 'ASUS ROG Phone 5',
@@ -182,8 +175,7 @@ class Options extends null {
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
Referer: 'https://discord.com/channels/@me',
'Sec-Ch-Ua':
'"Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100',
'Sec-Ch-Ua': '"Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"Windows"',
'Sec-Fetch-Dest': 'empty',

47
tsconfig.json Normal file
View File

@@ -0,0 +1,47 @@
{
// Mapped from https://www.typescriptlang.org/tsconfig
"compilerOptions": {
// Type Checking
"allowUnreachableCode": false,
"allowUnusedLabels": false,
// if true: conflicts with discord-api-types
"exactOptionalPropertyTypes": false,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"useUnknownInCatchVariables": true,
// Modules
"module": "CommonJS",
"moduleResolution": "node",
"resolveJsonModule": true,
// Emit
"declaration": false,
"importHelpers": true,
"importsNotUsedAsValues": "error",
"inlineSources": false,
"newLine": "lf",
"noEmitHelpers": true,
"outDir": "dist",
"preserveConstEnums": true,
"removeComments": false,
"sourceMap": false,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
// Language and Environment
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"ESNext"
],
"target": "ES2020",
"useDefineForClassFields": true,
// Output Formatting
"pretty": false,
// Completeness
"skipLibCheck": false,
"skipDefaultLibCheck": true
}
}

60
typings/enums.d.ts vendored
View File

@@ -30,36 +30,36 @@ export const enum relationshipsType {
}
export const enum localeSetting {
DANISH = 'da',
GERMAN = 'de',
ENGLISH_UK = 'en-GB',
ENGLISH_US = 'en-US',
SPANISH = 'es-ES',
FRENCH = 'fr',
CROATIAN = 'hr',
ITALIAN = 'it',
LITHUANIAN = 'lt',
HUNGARIAN = 'hu',
DUTCH = 'nl',
NORWEGIAN = 'no',
POLISH = 'pl',
BRAZILIAN_PORTUGUESE = 'pt-BR',
ROMANIA_ROMANIAN = 'ro',
FINNISH = 'fi',
SWEDISH = 'sv-SE',
VIETNAMESE = 'vi',
TURKISH = 'tr',
CZECH = 'cs',
GREEK = 'el',
BULGARIAN = 'bg',
RUSSIAN = 'ru',
UKRAINIAN = 'uk',
HINDI = 'hi',
THAI = 'th',
CHINA_CHINESE = 'zh-CN',
JAPANESE = 'ja',
TAIWAN_CHINESE = 'zh-TW',
KOREAN = 'ko',
DANISH = 'da',
GERMAN = 'de',
ENGLISH_UK = 'en-GB',
ENGLISH_US = 'en-US',
SPANISH = 'es-ES',
FRENCH = 'fr',
CROATIAN = 'hr',
ITALIAN = 'it',
LITHUANIAN = 'lt',
HUNGARIAN = 'hu',
DUTCH = 'nl',
NORWEGIAN = 'no',
POLISH = 'pl',
BRAZILIAN_PORTUGUESE = 'pt-BR',
ROMANIA_ROMANIAN = 'ro',
FINNISH = 'fi',
SWEDISH = 'sv-SE',
VIETNAMESE = 'vi',
TURKISH = 'tr',
CZECH = 'cs',
GREEK = 'el',
BULGARIAN = 'bg',
RUSSIAN = 'ru',
UKRAINIAN = 'uk',
HINDI = 'hi',
THAI = 'th',
CHINA_CHINESE = 'zh-CN',
JAPANESE = 'ja',
TAIWAN_CHINESE = 'zh-TW',
KOREAN = 'ko',
}
export const enum ApplicationCommandTypes {

366
typings/index.d.ts vendored
View File

@@ -147,7 +147,7 @@ import {
RawWidgetData,
RawWidgetMemberData,
} from './rawDataTypes';
import { RelationshipType } from '../src/util/Constants';
import { RelationshipTypes } from '../src/util/Constants';
//#region Classes
@@ -1008,7 +1008,7 @@ export class Guild extends AnonymousGuild {
public setIcon(icon: BufferResolvable | Base64Resolvable | null, reason?: string): Promise<Guild>;
public setName(name: string, reason?: string): Promise<Guild>;
public setOwner(owner: GuildMemberResolvable, reason?: string): Promise<Guild>;
public setPosition(position: number, type: FOLDER | HOME, folderID?: FolderID): Promise<Guild>;
public setPosition(position: number, type: 'FOLDER' | 'HOME', folderID?: FolderID): Promise<Guild>;
public setPreferredLocale(preferredLocale: string, reason?: string): Promise<Guild>;
public setPublicUpdatesChannel(publicUpdatesChannel: TextChannelResolvable | null, reason?: string): Promise<Guild>;
/** @deprecated Use {@link RoleManager.setPositions} instead */
@@ -1019,7 +1019,12 @@ export class Guild extends AnonymousGuild {
public setSystemChannelFlags(systemChannelFlags: SystemChannelFlagsResolvable, reason?: string): Promise<Guild>;
public setVerificationLevel(verificationLevel: VerificationLevel | number, reason?: string): Promise<Guild>;
public setPremiumProgressBarEnabled(enabled?: boolean, reason?: string): Promise<Guild>;
public setCommunity(stats: boolean, publicUpdatesChannel: TextChannelResolvable, rulesChannel: TextChannelResolvable, reason?: string): Promise<Guild>;
public setCommunity(
stats: boolean,
publicUpdatesChannel: TextChannelResolvable,
rulesChannel: TextChannelResolvable,
reason?: string,
): Promise<Guild>;
public setWidgetSettings(settings: GuildWidgetSettingsData, reason?: string): Promise<Guild>;
public toJSON(): unknown;
}
@@ -1043,17 +1048,17 @@ export class GuildAuditLogs<T extends GuildAuditLogsResolvable = 'ALL'> {
export class GuildAuditLogsEntry<
TActionRaw extends GuildAuditLogsResolvable = 'ALL',
TAction = TActionRaw extends keyof GuildAuditLogsIds
? GuildAuditLogsIds[TActionRaw]
: TActionRaw extends null
? 'ALL'
: TActionRaw,
? GuildAuditLogsIds[TActionRaw]
: TActionRaw extends null
? 'ALL'
: TActionRaw,
TActionType extends GuildAuditLogsActionType = TAction extends keyof GuildAuditLogsTypes
? GuildAuditLogsTypes[TAction][1]
: 'ALL',
? GuildAuditLogsTypes[TAction][1]
: 'ALL',
TTargetType extends GuildAuditLogsTarget = TAction extends keyof GuildAuditLogsTypes
? GuildAuditLogsTypes[TAction][0]
: 'UNKNOWN',
> {
? GuildAuditLogsTypes[TAction][0]
: 'UNKNOWN',
> {
private constructor(logs: GuildAuditLogs, guild: Guild, data: RawGuildAuditLogEntryData);
public action: TAction;
public actionType: TActionType;
@@ -1291,7 +1296,7 @@ export class HTTPError extends Error {
}
// tslint:disable-next-line:no-empty-interface - Merge RateLimitData into RateLimitError to not have to type it again
export interface RateLimitError extends RateLimitData { }
export interface RateLimitError extends RateLimitData {}
export class RateLimitError extends Error {
private constructor(data: RateLimitData);
public name: 'RateLimitError';
@@ -1344,7 +1349,7 @@ export type CacheTypeReducer<
RawType = CachedType,
PresentType = CachedType | RawType,
Fallback = PresentType | null,
> = [State] extends ['cached']
> = [State] extends ['cached']
? CachedType
: [State] extends ['raw']
? RawType
@@ -1490,25 +1495,25 @@ export class LimitedCollection<K, V> extends Collection<K, V> {
export type MessageCollectorOptionsParams<T extends MessageComponentTypeResolvable, Cached extends boolean = boolean> =
| {
componentType?: T;
} & MessageComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>;
componentType?: T;
} & MessageComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>;
export type MessageChannelCollectorOptionsParams<
T extends MessageComponentTypeResolvable,
Cached extends boolean = boolean,
> =
> =
| {
componentType?: T;
} & MessageChannelComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>;
componentType?: T;
} & MessageChannelComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>;
export type AwaitMessageCollectorOptionsParams<
T extends MessageComponentTypeResolvable,
Cached extends boolean = boolean,
> =
> =
| { componentType?: T } & Pick<
InteractionCollectorOptions<MappedInteractionTypes<Cached>[T]>,
keyof AwaitMessageComponentOptions<any>
>;
InteractionCollectorOptions<MappedInteractionTypes<Cached>[T]>,
keyof AwaitMessageComponentOptions<any>
>;
export interface StringMappedInteractionTypes<Cached extends CacheType = CacheType> {
BUTTON: ButtonInteraction<Cached>;
@@ -1600,8 +1605,11 @@ export class Message<Cached extends boolean = boolean> extends Base {
public unpin(): Promise<Message>;
public inGuild(): this is Message<true> & this;
// Added
public clickButton(buttonID: String<MessageButton.customId>): Promise<pending>
public selectMenu(menuID: String<MessageSelectMenu.customId> | Array<options>, options: Array<String>): Promise<pending>
public clickButton(buttonID: String<MessageButton.customId>): Promise<pending>;
public selectMenu(
menuID: String<MessageSelectMenu.customId> | Array<options>,
options: Array<String>,
): Promise<pending>;
public contextMenu(botID: DiscordBotID, commandName: String<ApplicationCommand.name>): Promise;
}
@@ -1717,7 +1725,7 @@ export class MessageComponentInteraction<Cached extends CacheType = CacheType> e
export class MessageContextMenuInteraction<
Cached extends CacheType = CacheType,
> extends ContextMenuInteraction<Cached> {
> extends ContextMenuInteraction<Cached> {
public readonly targetMessage: NonNullable<CommandInteractionOption<Cached>['message']>;
public inGuild(): this is MessageContextMenuInteraction<'present'>;
public inCachedGuild(): this is MessageContextMenuInteraction<'cached'>;
@@ -2973,7 +2981,7 @@ export class ApplicationCommandManager<
ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>,
PermissionsOptionsExtras = { guild: GuildResolvable },
PermissionsGuildType = null,
> extends CachedManager<Snowflake, ApplicationCommandScope, ApplicationCommandResolvable> {
> extends CachedManager<Snowflake, ApplicationCommandScope, ApplicationCommandResolvable> {
protected constructor(client: Client, iterable?: Iterable<unknown>, user: User);
public permissions: ApplicationCommandPermissionsManager<
{ command?: ApplicationCommandResolvable } & PermissionsOptionsExtras,
@@ -3020,8 +3028,11 @@ export class ApplicationCommandPermissionsManager<
FullPermissionsOptions,
GuildType,
CommandIdType,
> extends BaseManager {
private constructor(manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand, user: User);
> extends BaseManager {
private constructor(
manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand,
user: User,
);
private manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand;
public client: Client;
@@ -3037,13 +3048,13 @@ export class ApplicationCommandPermissionsManager<
public remove(
options:
| (FetchSingleOptions & {
users: UserResolvable | UserResolvable[];
roles?: RoleResolvable | RoleResolvable[];
})
users: UserResolvable | UserResolvable[];
roles?: RoleResolvable | RoleResolvable[];
})
| (FetchSingleOptions & {
users?: UserResolvable | UserResolvable[];
roles: RoleResolvable | RoleResolvable[];
}),
users?: UserResolvable | UserResolvable[];
roles: RoleResolvable | RoleResolvable[];
}),
): Promise<ApplicationCommandPermissions[]>;
public set(
options: FetchSingleOptions & { permissions: ApplicationCommandPermissionData[] },
@@ -3092,8 +3103,16 @@ export class ClientUserSettingManager {
public afkTimeout: number | null; // second
public stickerAnimationMode: stickerAnimationMode;
public showEmojiReactions: boolean | null;
public customStatus: { text?: string, expires_at?: string | null, emoji_name?: string, emoji_id?: Snowflake | null, status?: PresenceStatusData } | object;
public addFriendFrom: { all?: boolean, mutual_friends?: boolean, mututal_guilds?: boolean } | object;
public customStatus:
| {
text?: string;
expires_at?: string | null;
emoji_name?: string;
emoji_id?: Snowflake | null;
status?: PresenceStatusData;
}
| object;
public addFriendFrom: { all?: boolean; mutual_friends?: boolean; mututal_guilds?: boolean } | object;
public guildMetadata: Collection<Snowflake, object>;
public disableDMfromServer: Collection<Snowflake, boolean>;
public fetch(): Promise<RawUserSettingsData>;
@@ -3227,7 +3246,7 @@ export class GuildScheduledEventManager extends CachedManager<
public fetch(): Promise<Collection<Snowflake, GuildScheduledEvent>>;
public fetch<
T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions,
>(options?: T): Promise<GuildScheduledEventManagerFetchResult<T>>;
>(options?: T): Promise<GuildScheduledEventManagerFetchResult<T>>;
public edit<S extends GuildScheduledEventStatus, T extends GuildScheduledEventSetStatusArg<S>>(
guildScheduledEvent: GuildScheduledEventResolvable,
options: GuildScheduledEventEditOptions<S, T>,
@@ -3757,12 +3776,12 @@ export interface ApplicationCommandChannelOption extends BaseApplicationCommandO
export interface ApplicationCommandAutocompleteOption extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type:
| 'STRING'
| 'NUMBER'
| 'INTEGER'
| ApplicationCommandOptionTypes.STRING
| ApplicationCommandOptionTypes.NUMBER
| ApplicationCommandOptionTypes.INTEGER;
| 'STRING'
| 'NUMBER'
| 'INTEGER'
| ApplicationCommandOptionTypes.STRING
| ApplicationCommandOptionTypes.NUMBER
| ApplicationCommandOptionTypes.INTEGER;
autocomplete: true;
}
@@ -3912,11 +3931,11 @@ export interface BaseFetchOptions {
}
export interface guildSearchInteraction {
type?: ApplicationCommandTypes,
query?: String | void,
limit?: Number,
offset?: Number,
botID?: Array<User.id>,
type?: ApplicationCommandTypes;
query?: String | void;
limit?: Number;
offset?: Number;
botID?: Array<User.id>;
}
export interface BaseMessageComponentOptions {
@@ -3970,8 +3989,8 @@ export type CacheFactory = (
export type CacheWithLimitsOptions = {
[K in keyof Caches]?: Caches[K][0]['prototype'] extends DataManager<infer K, infer V, any>
? LimitedCollectionOptions<K, V> | number
: never;
? LimitedCollectionOptions<K, V> | number
: never;
};
export interface CategoryCreateChannelOptions {
@@ -4089,7 +4108,7 @@ export interface ClientEvents extends BaseClientEvents {
members: Collection<Snowflake, GuildMember>,
guild: Guild,
data: {}, // see: https://luna.gitlab.io/discord-unofficial-docs/lazy_guilds.html
]
];
guildUpdate: [oldGuild: Guild, newGuild: Guild];
inviteCreate: [invite: Invite];
inviteDelete: [invite: Invite];
@@ -4127,9 +4146,9 @@ export interface ClientEvents extends BaseClientEvents {
webhookUpdate: [channel: TextChannel | NewsChannel];
/** @deprecated Use interactionCreate instead */
interaction: [interaction: Interaction];
interactionCreate: [interaction: Interaction | { nonce: Snowflake, id: Snowflake }];
interactionSuccess: [interaction: { nonce: Snowflake, id: Snowflake }];
interactionFailed: [interaction: { nonce: Snowflake, id: Snowflake }];
interactionCreate: [interaction: Interaction | { nonce: Snowflake; id: Snowflake }];
interactionSuccess: [interaction: { nonce: Snowflake; id: Snowflake }];
interactionFailed: [interaction: { nonce: Snowflake; id: Snowflake }];
shardDisconnect: [closeEvent: CloseEvent, shardId: number];
shardError: [error: Error, shardId: number];
shardReady: [shardId: number, unavailableGuilds: Set<Snowflake> | undefined];
@@ -4146,20 +4165,9 @@ export interface ClientEvents extends BaseClientEvents {
guildScheduledEventDelete: [guildScheduledEvent: GuildScheduledEvent];
guildScheduledEventUserAdd: [guildScheduledEvent: GuildScheduledEvent, user: User];
guildScheduledEventUserRemove: [guildScheduledEvent: GuildScheduledEvent, user: User];
relationshipAdd: [
id: Snowflake,
type: RelationshipType,
user: User,
];
relationshipRemove: [
id: Snowflake,
type: RelationshipType,
user: User,
];
unhandledPacket: [
packet: { op: GatewayOpcodes | number, d?: any, s?: number, t?: string },
shard: WebSocketShard,
];
relationshipAdd: [id: Snowflake, type: RelationshipTypes, user: User];
relationshipRemove: [id: Snowflake, type: RelationshipTypes, user: User];
unhandledPacket: [packet: { op: GatewayOpcodes | number; d?: any; s?: number; t?: string }, shard: WebSocketShard];
}
export interface ClientFetchInviteOptions {
@@ -4339,80 +4347,80 @@ export interface ConstantsEvents {
/** @deprecated See [this issue](https://github.com/discord/discord-api-docs/issues/3690) for more information. */
APPLICATION_COMMAND_DELETE: 'applicationCommandDelete';
/** @deprecated See [this issue](https://github.com/discord/discord-api-docs/issues/3690) for more information. */
APPLICATION_COMMAND_UPDATE: 'applicationCommandUpdate',
GUILD_CREATE: 'guildCreate',
GUILD_DELETE: 'guildDelete',
GUILD_UPDATE: 'guildUpdate',
GUILD_UNAVAILABLE: 'guildUnavailable',
GUILD_MEMBER_ADD: 'guildMemberAdd',
GUILD_MEMBER_REMOVE: 'guildMemberRemove',
GUILD_MEMBER_UPDATE: 'guildMemberUpdate',
GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable',
GUILD_MEMBERS_CHUNK: 'guildMembersChunk',
GUILD_MEMBER_LIST_UPDATE: 'guildMemberListUpdate',
GUILD_INTEGRATIONS_UPDATE: 'guildIntegrationsUpdate',
GUILD_ROLE_CREATE: 'roleCreate',
GUILD_ROLE_DELETE: 'roleDelete',
INVITE_CREATE: 'inviteCreate',
INVITE_DELETE: 'inviteDelete',
GUILD_ROLE_UPDATE: 'roleUpdate',
GUILD_EMOJI_CREATE: 'emojiCreate',
GUILD_EMOJI_DELETE: 'emojiDelete',
GUILD_EMOJI_UPDATE: 'emojiUpdate',
GUILD_BAN_ADD: 'guildBanAdd',
GUILD_BAN_REMOVE: 'guildBanRemove',
CHANNEL_CREATE: 'channelCreate',
CHANNEL_DELETE: 'channelDelete',
CHANNEL_UPDATE: 'channelUpdate',
CHANNEL_PINS_UPDATE: 'channelPinsUpdate',
MESSAGE_CREATE: 'messageCreate',
MESSAGE_DELETE: 'messageDelete',
MESSAGE_UPDATE: 'messageUpdate',
MESSAGE_BULK_DELETE: 'messageDeleteBulk',
MESSAGE_REACTION_ADD: 'messageReactionAdd',
MESSAGE_REACTION_REMOVE: 'messageReactionRemove',
MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll',
MESSAGE_REACTION_REMOVE_EMOJI: 'messageReactionRemoveEmoji',
THREAD_CREATE: 'threadCreate',
THREAD_DELETE: 'threadDelete',
THREAD_UPDATE: 'threadUpdate',
THREAD_LIST_SYNC: 'threadListSync',
THREAD_MEMBER_UPDATE: 'threadMemberUpdate',
THREAD_MEMBERS_UPDATE: 'threadMembersUpdate',
USER_UPDATE: 'userUpdate',
PRESENCE_UPDATE: 'presenceUpdate',
VOICE_SERVER_UPDATE: 'voiceServerUpdate',
VOICE_STATE_UPDATE: 'voiceStateUpdate',
TYPING_START: 'typingStart',
WEBHOOKS_UPDATE: 'webhookUpdate',
INTERACTION_CREATE: 'interactionCreate',
INTERACTION_SUCCESS: 'interactionSuccess',
INTERACTION_FAILED: 'interactionFailed',
ERROR: 'error',
WARN: 'warn',
DEBUG: 'debug',
CACHE_SWEEP: 'cacheSweep',
SHARD_DISCONNECT: 'shardDisconnect',
SHARD_ERROR: 'shardError',
SHARD_RECONNECTING: 'shardReconnecting',
SHARD_READY: 'shardReady',
SHARD_RESUME: 'shardResume',
INVALIDATED: 'invalidated',
RAW: 'raw',
STAGE_INSTANCE_CREATE: 'stageInstanceCreate',
STAGE_INSTANCE_UPDATE: 'stageInstanceUpdate',
STAGE_INSTANCE_DELETE: 'stageInstanceDelete',
GUILD_STICKER_CREATE: 'stickerCreate',
GUILD_STICKER_DELETE: 'stickerDelete',
GUILD_STICKER_UPDATE: 'stickerUpdate',
GUILD_SCHEDULED_EVENT_CREATE: 'guildScheduledEventCreate',
GUILD_SCHEDULED_EVENT_UPDATE: 'guildScheduledEventUpdate',
GUILD_SCHEDULED_EVENT_DELETE: 'guildScheduledEventDelete',
GUILD_SCHEDULED_EVENT_USER_ADD: 'guildScheduledEventUserAdd',
GUILD_SCHEDULED_EVENT_USER_REMOVE: 'guildScheduledEventUserRemove',
RELATIONSHIP_ADD: 'relationshipAdd',
RELATIONSHIP_REMOVE: 'relationshipRemove',
UNHANDLED_PACKET: 'unhandledPacket',
APPLICATION_COMMAND_UPDATE: 'applicationCommandUpdate';
GUILD_CREATE: 'guildCreate';
GUILD_DELETE: 'guildDelete';
GUILD_UPDATE: 'guildUpdate';
GUILD_UNAVAILABLE: 'guildUnavailable';
GUILD_MEMBER_ADD: 'guildMemberAdd';
GUILD_MEMBER_REMOVE: 'guildMemberRemove';
GUILD_MEMBER_UPDATE: 'guildMemberUpdate';
GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable';
GUILD_MEMBERS_CHUNK: 'guildMembersChunk';
GUILD_MEMBER_LIST_UPDATE: 'guildMemberListUpdate';
GUILD_INTEGRATIONS_UPDATE: 'guildIntegrationsUpdate';
GUILD_ROLE_CREATE: 'roleCreate';
GUILD_ROLE_DELETE: 'roleDelete';
INVITE_CREATE: 'inviteCreate';
INVITE_DELETE: 'inviteDelete';
GUILD_ROLE_UPDATE: 'roleUpdate';
GUILD_EMOJI_CREATE: 'emojiCreate';
GUILD_EMOJI_DELETE: 'emojiDelete';
GUILD_EMOJI_UPDATE: 'emojiUpdate';
GUILD_BAN_ADD: 'guildBanAdd';
GUILD_BAN_REMOVE: 'guildBanRemove';
CHANNEL_CREATE: 'channelCreate';
CHANNEL_DELETE: 'channelDelete';
CHANNEL_UPDATE: 'channelUpdate';
CHANNEL_PINS_UPDATE: 'channelPinsUpdate';
MESSAGE_CREATE: 'messageCreate';
MESSAGE_DELETE: 'messageDelete';
MESSAGE_UPDATE: 'messageUpdate';
MESSAGE_BULK_DELETE: 'messageDeleteBulk';
MESSAGE_REACTION_ADD: 'messageReactionAdd';
MESSAGE_REACTION_REMOVE: 'messageReactionRemove';
MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll';
MESSAGE_REACTION_REMOVE_EMOJI: 'messageReactionRemoveEmoji';
THREAD_CREATE: 'threadCreate';
THREAD_DELETE: 'threadDelete';
THREAD_UPDATE: 'threadUpdate';
THREAD_LIST_SYNC: 'threadListSync';
THREAD_MEMBER_UPDATE: 'threadMemberUpdate';
THREAD_MEMBERS_UPDATE: 'threadMembersUpdate';
USER_UPDATE: 'userUpdate';
PRESENCE_UPDATE: 'presenceUpdate';
VOICE_SERVER_UPDATE: 'voiceServerUpdate';
VOICE_STATE_UPDATE: 'voiceStateUpdate';
TYPING_START: 'typingStart';
WEBHOOKS_UPDATE: 'webhookUpdate';
INTERACTION_CREATE: 'interactionCreate';
INTERACTION_SUCCESS: 'interactionSuccess';
INTERACTION_FAILED: 'interactionFailed';
ERROR: 'error';
WARN: 'warn';
DEBUG: 'debug';
CACHE_SWEEP: 'cacheSweep';
SHARD_DISCONNECT: 'shardDisconnect';
SHARD_ERROR: 'shardError';
SHARD_RECONNECTING: 'shardReconnecting';
SHARD_READY: 'shardReady';
SHARD_RESUME: 'shardResume';
INVALIDATED: 'invalidated';
RAW: 'raw';
STAGE_INSTANCE_CREATE: 'stageInstanceCreate';
STAGE_INSTANCE_UPDATE: 'stageInstanceUpdate';
STAGE_INSTANCE_DELETE: 'stageInstanceDelete';
GUILD_STICKER_CREATE: 'stickerCreate';
GUILD_STICKER_DELETE: 'stickerDelete';
GUILD_STICKER_UPDATE: 'stickerUpdate';
GUILD_SCHEDULED_EVENT_CREATE: 'guildScheduledEventCreate';
GUILD_SCHEDULED_EVENT_UPDATE: 'guildScheduledEventUpdate';
GUILD_SCHEDULED_EVENT_DELETE: 'guildScheduledEventDelete';
GUILD_SCHEDULED_EVENT_USER_ADD: 'guildScheduledEventUserAdd';
GUILD_SCHEDULED_EVENT_USER_REMOVE: 'guildScheduledEventUserRemove';
RELATIONSHIP_ADD: 'relationshipAdd';
RELATIONSHIP_REMOVE: 'relationshipRemove';
UNHANDLED_PACKET: 'unhandledPacket';
}
export interface ConstantsOpcodes {
@@ -4750,20 +4758,20 @@ export interface GuildAuditLogsEntryExtraField {
MESSAGE_UNPIN: { channel: GuildTextBasedChannel | { id: Snowflake }; messageId: Snowflake };
MEMBER_DISCONNECT: { count: number };
CHANNEL_OVERWRITE_CREATE:
| Role
| GuildMember
| { id: Snowflake; name: string; type: OverwriteTypes.role }
| { id: Snowflake; type: OverwriteTypes.member };
| Role
| GuildMember
| { id: Snowflake; name: string; type: OverwriteTypes.role }
| { id: Snowflake; type: OverwriteTypes.member };
CHANNEL_OVERWRITE_UPDATE:
| Role
| GuildMember
| { id: Snowflake; name: string; type: OverwriteTypes.role }
| { id: Snowflake; type: OverwriteTypes.member };
| Role
| GuildMember
| { id: Snowflake; name: string; type: OverwriteTypes.role }
| { id: Snowflake; type: OverwriteTypes.member };
CHANNEL_OVERWRITE_DELETE:
| Role
| GuildMember
| { id: Snowflake; name: string; type: OverwriteTypes.role }
| { id: Snowflake; type: OverwriteTypes.member };
| Role
| GuildMember
| { id: Snowflake; name: string; type: OverwriteTypes.role }
| { id: Snowflake; type: OverwriteTypes.member };
STAGE_INSTANCE_CREATE: StageChannel | { id: Snowflake };
STAGE_INSTANCE_DELETE: StageChannel | { id: Snowflake };
STAGE_INSTANCE_UPDATE: StageChannel | { id: Snowflake };
@@ -4776,8 +4784,8 @@ export interface GuildAuditLogsEntryTargetField<TActionType extends GuildAuditLo
INVITE: Invite;
MESSAGE: TActionType extends 'MESSAGE_BULK_DELETE' ? Guild | { id: Snowflake } : User;
INTEGRATION: Integration;
CHANNEL: NonThreadGuildBasedChannel | { id: Snowflake;[x: string]: unknown };
THREAD: ThreadChannel | { id: Snowflake;[x: string]: unknown };
CHANNEL: NonThreadGuildBasedChannel | { id: Snowflake; [x: string]: unknown };
THREAD: ThreadChannel | { id: Snowflake; [x: string]: unknown };
STAGE_INSTANCE: StageInstance;
STICKER: Sticker;
GUILD_SCHEDULED_EVENT: GuildScheduledEvent;
@@ -4963,7 +4971,7 @@ export interface GuildScheduledEventCreateOptions {
export interface GuildScheduledEventEditOptions<
S extends GuildScheduledEventStatus,
T extends GuildScheduledEventSetStatusArg<S>,
> extends Omit<Partial<GuildScheduledEventCreateOptions>, 'channel'> {
> extends Omit<Partial<GuildScheduledEventCreateOptions>, 'channel'> {
channel?: GuildVoiceChannelResolvable | null;
status?: T | number;
}
@@ -4980,14 +4988,14 @@ export type GuildScheduledEventEntityType = keyof typeof GuildScheduledEventEnti
export type GuildScheduledEventManagerFetchResult<
T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions,
> = T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions
> = T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions
? GuildScheduledEvent
: Collection<Snowflake, GuildScheduledEvent>;
export type GuildScheduledEventManagerFetchSubscribersResult<T extends FetchGuildScheduledEventSubscribersOptions> =
T extends { withMember: true }
? Collection<Snowflake, GuildScheduledEventUser<true>>
: Collection<Snowflake, GuildScheduledEventUser<false>>;
? Collection<Snowflake, GuildScheduledEventUser<true>>
: Collection<Snowflake, GuildScheduledEventUser<false>>;
export type GuildScheduledEventPrivacyLevel = keyof typeof GuildScheduledEventPrivacyLevels;
@@ -5538,24 +5546,24 @@ export type Partialize<
N extends keyof T | null = null,
M extends keyof T | null = null,
E extends keyof T | '' = '',
> = {
readonly client: Client;
id: Snowflake;
partial: true;
} & {
[K in keyof Omit<T, 'client' | 'id' | 'partial' | E>]: K extends N ? null : K extends M ? T[K] | null : T[K];
};
> = {
readonly client: Client;
id: Snowflake;
partial: true;
} & {
[K in keyof Omit<T, 'client' | 'id' | 'partial' | E>]: K extends N ? null : K extends M ? T[K] | null : T[K];
};
export interface PartialDMChannel extends Partialize<DMChannel, null, null, 'lastMessageId'> {
lastMessageId: undefined;
}
export interface PartialGuildMember extends Partialize<GuildMember, 'joinedAt' | 'joinedTimestamp'> { }
export interface PartialGuildMember extends Partialize<GuildMember, 'joinedAt' | 'joinedTimestamp'> {}
export interface PartialMessage
extends Partialize<Message, 'type' | 'system' | 'pinned' | 'tts', 'content' | 'cleanContent' | 'author'> { }
extends Partialize<Message, 'type' | 'system' | 'pinned' | 'tts', 'content' | 'cleanContent' | 'author'> {}
export interface PartialMessageReaction extends Partialize<MessageReaction, 'count'> { }
export interface PartialMessageReaction extends Partialize<MessageReaction, 'count'> {}
export interface PartialOverwriteData {
id: Snowflake | number;
@@ -5570,7 +5578,7 @@ export interface PartialRoleData extends RoleData {
export type PartialTypes = 'USER' | 'CHANNEL' | 'GUILD_MEMBER' | 'MESSAGE' | 'REACTION' | 'GUILD_SCHEDULED_EVENT';
export interface PartialUser extends Partialize<User, 'username' | 'tag' | 'discriminator'> { }
export interface PartialUser extends Partialize<User, 'username' | 'tag' | 'discriminator'> {}
export type PresenceStatusData = ClientPresenceStatus | 'invisible';
@@ -5595,9 +5603,9 @@ export interface RawUserSettingsData {
allow_accessibility_detection?: boolean;
animate_emoji?: boolean;
animate_stickers?: number;
contact_sync_enabled:? boolean;
contact_sync_enabled: ?boolean;
convert_emoticons?: boolean;
custom_status?: { text?: string, expires_at?: string | null, emoji_name?: string, emoji_id?: Snowflake | null };
custom_status?: { text?: string; expires_at?: string | null; emoji_name?: string; emoji_id?: Snowflake | null };
default_guilds_restricted?: boolean;
detect_platform_accounts?: boolean;
developer_mode?: boolean;
@@ -5605,10 +5613,10 @@ export interface RawUserSettingsData {
enable_tts_command?: boolean;
explicit_content_filter?: DMScanLevel;
friend_discovery_flags?: number;
friend_source_flags?: { all?: boolean, mutual_friends?: boolean, mututal_guilds?: boolean };
friend_source_flags?: { all?: boolean; mutual_friends?: boolean; mututal_guilds?: boolean };
gif_auto_play?: boolean;
guild_folders?: Array<{ id?: Snowflake, guild_ids?: Array<Snowflake>, name?: string }>;
guild_positions?: Array;
guild_folders?: Array<{ id?: Snowflake; guild_ids?: Array<Snowflake>; name?: string }>;
guild_positions?: Array<T>;
inline_attachment_media?: boolean;
inline_embed_media?: boolean;
locale?: string;
@@ -5792,8 +5800,8 @@ export interface SweeperDefinitions {
export type SweeperOptions = {
[K in keyof SweeperDefinitions]?: SweeperDefinitions[K][2] extends true
? SweepOptions<SweeperDefinitions[K][0], SweeperDefinitions[K][1]> | LifetimeSweepOptions
: SweepOptions<SweeperDefinitions[K][0], SweeperDefinitions[K][1]>;
? SweepOptions<SweeperDefinitions[K][0], SweeperDefinitions[K][1]> | LifetimeSweepOptions
: SweepOptions<SweeperDefinitions[K][0], SweeperDefinitions[K][1]>;
};
export interface LimitedCollectionOptions<K, V> {