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", "main": "./src/index.js",
"types": "./typings/index.d.ts", "types": "./typings/index.d.ts",
"scripts": { "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": [ "files": [
"src", "src",

View File

@@ -251,10 +251,10 @@ class Client extends BaseClient {
url: 'https://discord.com/api/v9/experiments', url: 'https://discord.com/api/v9/experiments',
headers: this.options.http.headers, headers: this.options.http.headers,
}) })
.then((res) => { .then(res => {
if (!'set-cookie' in res.headers) return; if (!'set-cookie' in res.headers) return;
res.headers['set-cookie'].map((line) => { res.headers['set-cookie'].map(line => {
line.split('; ').map((arr) => { line.split('; ').map(arr => {
if ( if (
arr.startsWith('Expires') || arr.startsWith('Expires') ||
arr.startsWith('Path') || arr.startsWith('Path') ||
@@ -275,11 +275,8 @@ class Client extends BaseClient {
this.emit(Events.DEBUG, `Added Cookie: ${cookie}`); this.emit(Events.DEBUG, `Added Cookie: ${cookie}`);
this.emit(Events.DEBUG, `Added Fingerprint: ${res.data.fingerprint}`); this.emit(Events.DEBUG, `Added Fingerprint: ${res.data.fingerprint}`);
}) })
.catch((err) => { .catch(err => {
this.emit( this.emit(Events.DEBUG, `Finding Cookie and Fingerprint failed: ${err.message}`);
Events.DEBUG,
`Finding Cookie and Fingerprint failed: ${err.message}`,
);
}); });
} }

View File

@@ -60,7 +60,10 @@ class InteractionCreateAction extends Action {
InteractionType = AutocompleteInteraction; InteractionType = AutocompleteInteraction;
break; break;
default: 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; return;
} }

View File

@@ -217,7 +217,7 @@ class WebSocketManager extends EventEmitter {
this.shardQueue.add(shard); this.shardQueue.add(shard);
if (shard.sessionId) { 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(); this.reconnect();
} else { } else {
shard.destroy({ reset: true, emit: false, log: false }); shard.destroy({ reset: true, emit: false, log: false });
@@ -279,7 +279,7 @@ class WebSocketManager extends EventEmitter {
} catch (error) { } catch (error) {
this.debug(`Couldn't reconnect or fetch information about the gateway. ${error}`); this.debug(`Couldn't reconnect or fetch information about the gateway. ${error}`);
if (error.httpStatus !== 401) { 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); await sleep(5_000);
this.reconnecting = false; this.reconnecting = false;
return this.reconnect(); return this.reconnect();

View File

@@ -13,7 +13,7 @@ let zlib;
try { try {
zlib = require('zlib-sync'); zlib = require('zlib-sync');
} catch { } // eslint-disable-line no-empty } catch {} // eslint-disable-line no-empty
/** /**
* Represents a Shard's WebSocket connection * Represents a Shard's WebSocket connection
@@ -487,7 +487,8 @@ class WebSocketShard extends EventEmitter {
() => { () => {
this.debug( this.debug(
`Shard ${hasGuildsIntent ? 'did' : 'will'} not receive any more guild packets` + `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
}`, }`,
); );

View File

@@ -6,5 +6,5 @@ module.exports = (client, { d: data }) => {
const user = client.users.cache.get(command.application_id); const user = client.users.cache.get(command.application_id);
if (!user) continue; if (!user) continue;
user.applications._add(command, true); user.applications._add(command, true);
}; }
}; };

View File

@@ -16,17 +16,19 @@ module.exports = (client, { d: data }) => {
const member = member_.member; const member = member_.member;
if (!member) continue; if (!member) continue;
members.set(member.user.id, guild.members._add(member)); members.set(member.user.id, guild.members._add(member));
if (member.presence) if (member.presence) {
guild.presences._add(Object.assign(member.presence, { guild })); guild.presences._add(Object.assign(member.presence, { guild }));
} }
}
} else if (object.op == 'INVALIDATE') { } else if (object.op == 'INVALIDATE') {
console.warn(`Invalidate [${object.range[0]}, ${object.range[1]}]`); console.warn(`Invalidate [${object.range[0]}, ${object.range[1]}]`);
} else if (object.op == 'UPDATE' || object.op == 'INSERT') { } else if (object.op == 'UPDATE' || object.op == 'INSERT') {
const member = object.item.member; const member = object.item.member;
if (!member) continue; if (!member) continue;
members.set(member.user.id, guild.members._add(member)); members.set(member.user.id, guild.members._add(member));
if (member.presence) if (member.presence) {
guild.presences._add(Object.assign(member.presence, { guild })); guild.presences._add(Object.assign(member.presence, { guild }));
}
} else if (object.op == 'DELETE') { } else if (object.op == 'DELETE') {
// nothing; // nothing;
} }

View File

@@ -5,49 +5,31 @@ const chalk = require('chalk');
const axios = require('axios'); const axios = require('axios');
const Discord = require('../../../index'); const Discord = require('../../../index');
const RichPresence = require('discord-rpc-contructor'); const RichPresence = require('discord-rpc-contructor');
const { ChannelTypes } = require('../../../util/Constants');
const checkUpdate = async () => { const checkUpdate = async () => {
const res_ = await axios.get( const res_ = await axios.get(`https://registry.npmjs.com/${encodeURIComponent('discord.js-selfbot-v13')}`);
`https://registry.npmjs.com/${encodeURIComponent(
'discord.js-selfbot-v13',
)}`,
);
const lastest_tag = res_.data['dist-tags'].latest; const lastest_tag = res_.data['dist-tags'].latest;
// Checking if the package is outdated // Checking if the package is outdated
// Stable version // Stable version
if (lastest_tag !== Discord.version && Discord.version.includes('-') == false) { if (lastest_tag !== Discord.version && Discord.version.includes('-') == false) {
return console.log(`${chalk.yellowBright( return console.log(`${chalk.yellowBright('[WARNING]')} New Discord.js-selfbot-v13 version.
'[WARNING]', Old Version: ${chalk.redBright(Discord.version)} => New Version: ${chalk.greenBright(lastest_tag)}`);
)} New Discord.js-selfbot-v13 version.
Old Version: ${chalk.redBright(
Discord.version,
)} => New Version: ${chalk.greenBright(lastest_tag)}`);
} }
return console.log( return console.log(
`${chalk.greenBright( `${chalk.greenBright('[OK]')} Discord.js-selfbot-v13 is up to date. Version: ${chalk.blueBright(Discord.version)}`,
'[OK]',
)} Discord.js-selfbot-v13 is up to date. Version: ${chalk.blueBright(
Discord.version,
)}`,
); );
}; };
const customStatusAuto = async (client) => { const customStatusAuto = async client => {
let custom_status; let custom_status;
if ( if (client.setting.rawSetting.custom_status?.text || res.rawSetting.custom_status?.emoji_name) {
client.setting.rawSetting.custom_status?.text ||
res.rawSetting.custom_status?.emoji_name
) {
custom_status = new RichPresence.CustomStatus(); custom_status = new RichPresence.CustomStatus();
if (client.setting.rawSetting.custom_status.emoji_id) { if (client.setting.rawSetting.custom_status.emoji_id) {
const emoji = await client.emojis.resolve( const emoji = await client.emojis.resolve(client.setting.rawSetting.custom_status.emoji_id);
client.setting.rawSetting.custom_status.emoji_id,
);
if (emoji) custom_status.setDiscordEmoji(emoji); if (emoji) custom_status.setDiscordEmoji(emoji);
} else { } else {
custom_status.setUnicodeEmoji( custom_status.setUnicodeEmoji(client.setting.rawSetting.custom_status.emoji_name);
client.setting.rawSetting.custom_status.emoji_name,
);
} }
custom_status.setState(client.setting.rawSetting.custom_status?.text); custom_status.setState(client.setting.rawSetting.custom_status?.text);
client.user.setPresence({ client.user.setPresence({
@@ -55,9 +37,10 @@ const customStatusAuto = async (client) => {
status: client.setting.rawSetting.status, status: client.setting.rawSetting.status,
}); });
} }
} };
module.exports = (client, { d: data }, shard) => { module.exports = (client, { d: data }, shard) => {
console.log(data.private_channels);
if (client.options.checkUpdate) { if (client.options.checkUpdate) {
try { try {
checkUpdate(); checkUpdate();
@@ -84,6 +67,10 @@ module.exports = (client, { d: data }, shard) => {
client.user.notes.set(userid, note); client.user.notes.set(userid, note);
} }
for (const private_channel of data.private_channels) {
client.channels._add(private_channel);
}
if (client.options.readyStatus) { if (client.options.readyStatus) {
customStatusAuto(client); customStatusAuto(client);
} }

View File

@@ -18,10 +18,7 @@ const handlers = Object.fromEntries([
['GUILD_MEMBER_UPDATE', require('./GUILD_MEMBER_UPDATE')], ['GUILD_MEMBER_UPDATE', require('./GUILD_MEMBER_UPDATE')],
['GUILD_MEMBERS_CHUNK', require('./GUILD_MEMBERS_CHUNK')], ['GUILD_MEMBERS_CHUNK', require('./GUILD_MEMBERS_CHUNK')],
['GUILD_MEMBER_LIST_UPDATE', require('./GUILD_MEMBER_LIST_UPDATE.js')], ['GUILD_MEMBER_LIST_UPDATE', require('./GUILD_MEMBER_LIST_UPDATE.js')],
[ ['GUILD_APPLICATION_COMMANDS_UPDATE', require('./GUILD_APPLICATION_COMMANDS_UPDATE.js')],
'GUILD_APPLICATION_COMMANDS_UPDATE',
require('./GUILD_APPLICATION_COMMANDS_UPDATE.js'),
],
['GUILD_INTEGRATIONS_UPDATE', require('./GUILD_INTEGRATIONS_UPDATE')], ['GUILD_INTEGRATIONS_UPDATE', require('./GUILD_INTEGRATIONS_UPDATE')],
['GUILD_ROLE_CREATE', require('./GUILD_ROLE_CREATE')], ['GUILD_ROLE_CREATE', require('./GUILD_ROLE_CREATE')],
['GUILD_ROLE_DELETE', require('./GUILD_ROLE_DELETE')], ['GUILD_ROLE_DELETE', require('./GUILD_ROLE_DELETE')],
@@ -47,7 +44,7 @@ const handlers = Object.fromEntries([
['THREAD_LIST_SYNC', require('./THREAD_LIST_SYNC')], ['THREAD_LIST_SYNC', require('./THREAD_LIST_SYNC')],
['THREAD_MEMBER_UPDATE', require('./THREAD_MEMBER_UPDATE')], ['THREAD_MEMBER_UPDATE', require('./THREAD_MEMBER_UPDATE')],
['THREAD_MEMBERS_UPDATE', require('./THREAD_MEMBERS_UPDATE')], ['THREAD_MEMBERS_UPDATE', require('./THREAD_MEMBERS_UPDATE')],
['USER_SETTINGS_UPDATE', require('./USER_SETTINGS_UPDATE')], // opcode 0 ['USER_SETTINGS_UPDATE', require('./USER_SETTINGS_UPDATE')], // Opcode 0
// USER_SETTINGS_PROTO_UPDATE // opcode 0 // USER_SETTINGS_PROTO_UPDATE // opcode 0
['MESSAGE_ACK', require('./MESSAGE_ACK')], ['MESSAGE_ACK', require('./MESSAGE_ACK')],
['USER_NOTE_UPDATE', require('./USER_NOTE_UPDATE')], ['USER_NOTE_UPDATE', require('./USER_NOTE_UPDATE')],
@@ -67,14 +64,8 @@ const handlers = Object.fromEntries([
['GUILD_SCHEDULED_EVENT_CREATE', require('./GUILD_SCHEDULED_EVENT_CREATE')], ['GUILD_SCHEDULED_EVENT_CREATE', require('./GUILD_SCHEDULED_EVENT_CREATE')],
['GUILD_SCHEDULED_EVENT_UPDATE', require('./GUILD_SCHEDULED_EVENT_UPDATE')], ['GUILD_SCHEDULED_EVENT_UPDATE', require('./GUILD_SCHEDULED_EVENT_UPDATE')],
['GUILD_SCHEDULED_EVENT_DELETE', require('./GUILD_SCHEDULED_EVENT_DELETE')], ['GUILD_SCHEDULED_EVENT_DELETE', require('./GUILD_SCHEDULED_EVENT_DELETE')],
[ ['GUILD_SCHEDULED_EVENT_USER_ADD', require('./GUILD_SCHEDULED_EVENT_USER_ADD')],
'GUILD_SCHEDULED_EVENT_USER_ADD', ['GUILD_SCHEDULED_EVENT_USER_REMOVE', require('./GUILD_SCHEDULED_EVENT_USER_REMOVE')],
require('./GUILD_SCHEDULED_EVENT_USER_ADD'),
],
[
'GUILD_SCHEDULED_EVENT_USER_REMOVE',
require('./GUILD_SCHEDULED_EVENT_USER_REMOVE'),
],
]); ]);
module.exports = handlers; module.exports = handlers;

View File

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

View File

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

View File

@@ -49,7 +49,10 @@ class ApplicationCommandPermissionsManager extends BaseManager {
* @private * @private
*/ */
permissionsPath(guildId, commandId) { 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); * .catch(console.error);
*/ */
async set({ guild, command, permissions, fullPermissions } = {}) { 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); const { guildId, commandId } = this._validateOptions(guild, command);
if (commandId) { if (commandId) {
@@ -223,7 +226,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
* .catch(console.error); * .catch(console.error);
*/ */
async add({ guild, command, permissions }) { 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); const { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable'); if (!commandId) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable');
if (!Array.isArray(permissions)) { if (!Array.isArray(permissions)) {
@@ -275,13 +278,13 @@ class ApplicationCommandPermissionsManager extends BaseManager {
* .catch(console.error); * .catch(console.error);
*/ */
async remove({ guild, command, users, roles }) { 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); const { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable'); if (!commandId) throw new TypeError('INVALID_TYPE', 'command', 'ApplicationCommandResolvable');
if (!users && !roles) throw new TypeError('INVALID_TYPE', 'users OR roles', 'Array or Resolvable', true); if (!users && !roles) throw new TypeError('INVALID_TYPE', 'users OR roles', 'Array or Resolvable', true);
let resolvedIds = []; const resolvedIds = [];
if (Array.isArray(users)) { if (Array.isArray(users)) {
users.forEach(user => { users.forEach(user => {
const userId = this.client.users.resolveId(user); const userId = this.client.users.resolveId(user);

View File

@@ -132,7 +132,7 @@ class ChannelManager extends CachedManager {
console.log(recipients); console.log(recipients);
if (recipients.length < 2 || recipients.length > 9) throw new Error('Invalid Users length (2 - 9)'); 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({ 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 }); return this._add(data, null, { cache: true, allowUnknownGuild: true });
} }

View File

@@ -4,7 +4,7 @@ const CachedManager = require('./CachedManager');
const { default: Collection } = require('@discordjs/collection'); const { default: Collection } = require('@discordjs/collection');
const { Error, TypeError } = require('../errors/DJSError'); const { Error, TypeError } = require('../errors/DJSError');
const { remove } = require('lodash'); 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. * Manages API methods for users and stores their cache.
* @extends {CachedManager} * @extends {CachedManager}
@@ -128,18 +128,14 @@ class ClientUserSettingManager extends CachedManager {
if ('friend_source_flags' in data) { if ('friend_source_flags' in data) {
this.addFriendFrom = { this.addFriendFrom = {
all: data.friend_source_flags.all || false, all: data.friend_source_flags.all || false,
mutual_friends: mutual_friends: data.friend_source_flags.all ? true : data.friend_source_flags.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,
mutual_guilds:
data.friend_source_flags.all ? true : data.friend_source_flags.mutual_guilds,
}; };
} }
if ('guild_folders' in data) { if ('guild_folders' in data) {
const data_ = data.guild_positions.map((guildId, i) => { const data_ = data.guild_positions.map((guildId, i) => {
// Find folder // Find folder
const folderIndex = data.guild_folders.findIndex((obj) => const folderIndex = data.guild_folders.findIndex(obj => obj.guild_ids.includes(guildId));
obj.guild_ids.includes(guildId),
);
const metadata = { const metadata = {
guildId: guildId, guildId: guildId,
guildIndex: i, guildIndex: i,
@@ -154,7 +150,7 @@ class ClientUserSettingManager extends CachedManager {
this.guildMetadata = new Collection(data_); this.guildMetadata = new Collection(data_);
} }
if ('restricted_guilds' in data) { if ('restricted_guilds' in data) {
data.restricted_guilds.map((guildId) => { data.restricted_guilds.map(guildId => {
const guild = this.client.guilds.cache.get(guildId); const guild = this.client.guilds.cache.get(guildId);
if (!guild) return; if (!guild) return;
guild.disableDM = true; guild.disableDM = true;
@@ -194,17 +190,9 @@ class ClientUserSettingManager extends CachedManager {
*/ */
async setDisplayCompactMode(value) { async setDisplayCompactMode(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD'); if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
if ( if (typeof value !== 'boolean' && typeof value !== 'null' && typeof value !== 'undefined') {
typeof value !== 'boolean' && throw new TypeError('INVALID_TYPE', 'value', 'boolean | null | undefined', true);
typeof value !== 'null' && }
typeof value !== 'undefined'
)
throw new TypeError(
'INVALID_TYPE',
'value',
'boolean | null | undefined',
true,
);
if (!value) value = !this.compactMode; if (!value) value = !this.compactMode;
if (value !== this.compactMode) { if (value !== this.compactMode) {
await this.edit({ message_display_compact: value }); await this.edit({ message_display_compact: value });
@@ -219,21 +207,11 @@ class ClientUserSettingManager extends CachedManager {
async setTheme(value) { async setTheme(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD'); if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
const validValues = ['dark', 'light']; const validValues = ['dark', 'light'];
if ( if (typeof value !== 'string' && typeof value !== 'null' && typeof value !== 'undefined') {
typeof value !== 'string' && throw new TypeError('INVALID_TYPE', 'value', 'string | null | undefined', true);
typeof value !== 'null' && }
typeof value !== 'undefined'
)
throw new TypeError(
'INVALID_TYPE',
'value',
'string | null | undefined',
true,
);
if (!validValues.includes(value)) { if (!validValues.includes(value)) {
value == validValues[0] value == validValues[0] ? (value = validValues[1]) : (value = validValues[0]);
? (value = validValues[1])
: (value = validValues[0]);
} }
if (value !== this.theme) { if (value !== this.theme) {
await this.edit({ theme: value }); await this.edit({ theme: value });
@@ -277,8 +255,9 @@ class ClientUserSettingManager extends CachedManager {
*/ */
async setLocale(value) { async setLocale(value) {
if (this.client.bot) throw new Error('INVALID_BOT_METHOD'); if (this.client.bot) throw new Error('INVALID_BOT_METHOD');
if (typeof value !== 'string') if (typeof value !== 'string') {
throw new TypeError('INVALID_TYPE', 'value', 'string', true); throw new TypeError('INVALID_TYPE', 'value', 'string', true);
}
if (!localeObject[value]) throw new Error('INVALID_LOCALE'); if (!localeObject[value]) throw new Error('INVALID_LOCALE');
if (localeObject[value] !== this.locale) { if (localeObject[value] !== this.locale) {
await this.edit({ locale: localeObject[value] }); await this.edit({ locale: localeObject[value] });
@@ -318,11 +297,8 @@ class ClientUserSettingManager extends CachedManager {
async guildChangePosition(guildId, newPosition, type, folderId) { async guildChangePosition(guildId, newPosition, type, folderId) {
// get Guild default position // get Guild default position
// Escape // Escape
const oldGuildFolderPosition = this.rawSetting.guild_folders.findIndex( const oldGuildFolderPosition = this.rawSetting.guild_folders.findIndex(value => value.guild_ids.includes(guildId));
(value) => value.guild_ids.includes(guildId), const newGuildFolderPosition = this.rawSetting.guild_folders.findIndex(value =>
);
const newGuildFolderPosition = this.rawSetting.guild_folders.findIndex(
(value) =>
value.guild_ids.includes(this.rawSetting.guild_positions[newPosition]), value.guild_ids.includes(this.rawSetting.guild_positions[newPosition]),
); );
if (type == 2 || `${type}`.toUpperCase() == 'HOME') { if (type == 2 || `${type}`.toUpperCase() == 'HOME') {
@@ -330,10 +306,9 @@ class ClientUserSettingManager extends CachedManager {
// Check it is folder // Check it is folder
const folder = this.rawSetting.guild_folders[oldGuildFolderPosition]; const folder = this.rawSetting.guild_folders[oldGuildFolderPosition];
if (folder.id) { if (folder.id) {
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids = this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids = this.rawSetting.guild_folders[
this.rawSetting.guild_folders[
oldGuildFolderPosition oldGuildFolderPosition
].guild_ids.filter((v) => v !== guildId); ].guild_ids.filter(v => v !== guildId);
} }
this.rawSetting.guild_folders = this._move( this.rawSetting.guild_folders = this._move(
this.rawSetting.guild_folders, this.rawSetting.guild_folders,
@@ -343,20 +318,17 @@ class ClientUserSettingManager extends CachedManager {
this.rawSetting.guild_folders[newGuildFolderPosition].id = null; this.rawSetting.guild_folders[newGuildFolderPosition].id = null;
} else if (type == 1 || `${type}`.toUpperCase() == 'FOLDER') { } else if (type == 1 || `${type}`.toUpperCase() == 'FOLDER') {
// Delete GuildID from oldFolder // Delete GuildID from oldFolder
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids = this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids = this.rawSetting.guild_folders[
this.rawSetting.guild_folders[oldGuildFolderPosition].guild_ids.filter( oldGuildFolderPosition
(v) => v !== guildId, ].guild_ids.filter(v => v !== guildId);
);
// Index new Folder // Index new Folder
const folderIndex = this.rawSetting.guild_folders.findIndex( const folderIndex = this.rawSetting.guild_folders.findIndex(value => value.id == folderId);
(value) => value.id == folderId,
);
const folder = this.rawSetting.guild_folders[folderIndex]; const folder = this.rawSetting.guild_folders[folderIndex];
folder.guild_ids.push(guildId); folder.guild_ids.push(guildId);
folder.guild_ids = [...new Set(folder.guild_ids)]; folder.guild_ids = [...new Set(folder.guild_ids)];
folder.guild_ids = this._move( folder.guild_ids = this._move(
folder.guild_ids, folder.guild_ids,
folder.guild_ids.findIndex((v) => v == guildId), folder.guild_ids.findIndex(v => v == guildId),
newPosition, newPosition,
); );
} }

View File

@@ -419,7 +419,12 @@ class GuildMemberManager extends CachedManager {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!query && !user_ids) query = ''; if (!query && !user_ids) query = '';
if (nonce.length > 32) throw new RangeError('MEMBER_FETCH_NONCE_LENGTH'); 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({ this.guild.shard.send({
op: Opcodes.REQUEST_GUILD_MEMBERS, op: Opcodes.REQUEST_GUILD_MEMBERS,
d: { d: {
@@ -435,20 +440,28 @@ class GuildMemberManager extends CachedManager {
let channel; let channel;
let channels = this.guild.channels.cache.filter(c => c.isText()); let channels = this.guild.channels.cache.filter(c => c.isText());
channels = channels.filter(c => c.permissionsFor(this.guild.me).has('VIEW_CHANNEL')); 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.'); if (!channels.size)
const channels_allowed_everyone = channels.filter((c) => 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'), c.permissionsFor(this.guild.roles.everyone).has('VIEW_CHANNEL'),
); );
channel = channels_allowed_everyone.first() ?? channels.first(); channel = channels_allowed_everyone.first() ?? channels.first();
// create array limit [0, 99] // create array limit [0, 99]
const list = []; const list = [];
let allMember = this.guild.memberCount; const allMember = this.guild.memberCount;
if (allMember < 100) { if (allMember < 100) {
list.push([[0, 99]]); list.push([[0, 99]]);
} else if (allMember < 200) { } else if (allMember < 200) {
list.push([[0, 99], [100, 199]]); list.push([
[0, 99],
[100, 199],
]);
} else if (allMember < 300) { } else if (allMember < 300) {
list.push([[0, 99], [100, 199], [200, 299]]); list.push([
[0, 99],
[100, 199],
[200, 299],
]);
} else { } else {
let x = 100; let x = 100;
for (let i = 0; i < allMember; i++) { for (let i = 0; i < allMember; i++) {
@@ -464,7 +477,8 @@ class GuildMemberManager extends CachedManager {
x = x + 200; x = x + 200;
} }
} }
Promise.all(list.map(async (l) => { Promise.all(
list.map(async l => {
this.guild.shard.send({ this.guild.shard.send({
op: Opcodes.LAZY_REQUEST, op: Opcodes.LAZY_REQUEST,
d: { d: {
@@ -477,7 +491,8 @@ class GuildMemberManager extends CachedManager {
}, },
}, },
}); });
})) }),
);
} }
const fetchedMembers = new Collection(); const fetchedMembers = new Collection();
let i = 0; let i = 0;

View File

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

View File

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

View File

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

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection'); const { Collection } = require('@discordjs/collection');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { Error } = require('../errors'); 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. * Manages API methods for users who reacted to a reaction and stores their cache.
* @extends {CachedManager} * @extends {CachedManager}

View File

@@ -89,8 +89,7 @@ class RelationshipsManager {
if (this.cache.get(id) === RelationshipTypes.FRIEND) return false; if (this.cache.get(id) === RelationshipTypes.FRIEND) return false;
// check if outgoing request // check if outgoing request
if (this.cache.get(id) === RelationshipTypes.OUTGOING_REQUEST) return false; if (this.cache.get(id) === RelationshipTypes.OUTGOING_REQUEST) return false;
await this.client.api await this.client.api.users['@me'].relationships[id].put({
.users['@me'].relationships[id].put({
data: { data: {
type: RelationshipTypes.FRIEND, type: RelationshipTypes.FRIEND,
}, },
@@ -102,8 +101,7 @@ class RelationshipsManager {
const id = this.resolveId(user); const id = this.resolveId(user);
// check // check
if (this.cache.get(id) === RelationshipTypes.BLOCKED) return false; if (this.cache.get(id) === RelationshipTypes.BLOCKED) return false;
await this.client.api await this.client.api.users['@me'].relationships[id].put({
.users['@me'].relationships[id].put({
data: { data: {
type: RelationshipTypes.BLOCKED, type: RelationshipTypes.BLOCKED,
}, },

View File

@@ -93,7 +93,10 @@ class UserManager extends CachedManager {
const data = await this.client.api.users(id).get(); const data = await this.client.api.users(id).get();
const userObject = this._add(data, cache); const userObject = this._add(data, cache);
await userObject.getProfile().catch(() => {}); 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; userObject.note = noteObject?.note ?? null;
return userObject; return userObject;
} }

View File

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

View File

@@ -18,7 +18,7 @@ class ClientApplication extends Application {
* The application command manager for this application * The application command manager for this application
* @type {ApplicationCommandManager} * @type {ApplicationCommandManager}
*/ */
this.commands = null // Selfbot this.commands = null; // Selfbot
} }
_patch(data) { _patch(data) {
@@ -97,7 +97,7 @@ class ClientApplication extends Application {
* @returns {Promise<ClientApplication>} * @returns {Promise<ClientApplication>}
*/ */
async fetch() { 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(); const app = await this.client.api.oauth2.applications('@me').get();
this._patch(app); this._patch(app);
return this; return this;

View File

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

View File

@@ -33,8 +33,7 @@ class ClientUser extends User {
* If the bot's {@link ClientApplication#owner Owner} has MFA enabled on their account * If the bot's {@link ClientApplication#owner Owner} has MFA enabled on their account
* @type {?boolean} * @type {?boolean}
*/ */
this.mfaEnabled = this.mfaEnabled = typeof data.mfa_enabled === 'boolean' ? data.mfa_enabled : null;
typeof data.mfa_enabled === 'boolean' ? data.mfa_enabled : null;
} else { } else {
this.mfaEnabled ??= null; this.mfaEnabled ??= null;
} }
@@ -80,15 +79,15 @@ class ClientUser extends User {
* @returns {Promise<ClientUser>} * @returns {Promise<ClientUser>}
*/ */
async edit(data) { async edit(data) {
if (typeof data.avatar !== 'undefined') if (typeof data.avatar !== 'undefined') {
data.avatar = await DataResolver.resolveImage(data.avatar); data.avatar = await DataResolver.resolveImage(data.avatar);
if (typeof data.banner !== 'undefined') }
if (typeof data.banner !== 'undefined') {
data.banner = await DataResolver.resolveImage(data.banner); data.banner = await DataResolver.resolveImage(data.banner);
}
const newData = await this.client.api.users('@me').patch({ data }); const newData = await this.client.api.users('@me').patch({ data });
this.client.token = newData.token; this.client.token = newData.token;
this.client.password = data?.password this.client.password = data?.password ? data?.password : this.client.password;
? data?.password
: this.client.password;
const { updated } = this.client.actions.UserUpdate.handle(newData); const { updated } = this.client.actions.UserUpdate.handle(newData);
return updated ?? this; return updated ?? this;
} }
@@ -107,8 +106,9 @@ class ClientUser extends User {
* .catch(console.error); * .catch(console.error);
*/ */
setUsername(username, password) { setUsername(username, password) {
if (!password && !this.client.password) if (!password && !this.client.password) {
throw new Error('A password is required to change a username.'); throw new Error('A password is required to change a username.');
}
return this.edit({ return this.edit({
username, username,
password: this.client.password ? this.client.password : password, password: this.client.password ? this.client.password : password,
@@ -139,10 +139,9 @@ class ClientUser extends User {
* .catch(console.error); * .catch(console.error);
*/ */
setBanner(banner) { setBanner(banner) {
if (this.nitroType !== 2) if (this.nitroType !== 2) {
throw new Error( throw new Error('You must be a Nitro Boosted User to change your banner.');
'You must be a Nitro Boosted User to change your banner.', }
);
return this.edit({ banner }); return this.edit({ banner });
} }
@@ -163,10 +162,13 @@ class ClientUser extends User {
async setHypeSquad(type) { async setHypeSquad(type) {
const id = typeof type === 'string' ? HypeSquadOptions[type] : type; const id = typeof type === 'string' ? HypeSquadOptions[type] : type;
if (!id && id !== 0) throw new Error('Invalid HypeSquad type.'); if (!id && id !== 0) throw new Error('Invalid HypeSquad type.');
if (id !== 0) return await this.client.api.hypesquad.online.post({ if (id !== 0) {
return await this.client.api.hypesquad.online.post({
data: { house_id: id }, data: { house_id: id },
}); });
else return await this.client.api.hypesquad.online.delete(); } else {
return await this.client.api.hypesquad.online.delete();
}
} }
/** /**
@@ -186,8 +188,9 @@ class ClientUser extends User {
*/ */
setDiscriminator(discriminator, password) { setDiscriminator(discriminator, password) {
if (!this.nitro) throw new Error('You must be a Nitro User to change your discriminator.'); if (!this.nitro) throw new Error('You must be a Nitro User to change your discriminator.');
if (!password && !this.client.password) if (!password && !this.client.password) {
throw new Error('A password is required to change a discriminator.'); throw new Error('A password is required to change a discriminator.');
}
return this.edit({ return this.edit({
discriminator, discriminator,
password: this.client.password ? this.client.password : password, password: this.client.password ? this.client.password : password,
@@ -212,8 +215,9 @@ class ClientUser extends User {
* @returns {Promise} * @returns {Promise}
*/ */
setEmail(email, password) { setEmail(email, password) {
if (!password && !this.client.password) if (!password && !this.client.password) {
throw new Error('A password is required to change a email.'); throw new Error('A password is required to change a email.');
}
return this.edit({ return this.edit({
email, email,
password: this.client.password ? this.client.password : password, password: this.client.password ? this.client.password : password,
@@ -227,8 +231,9 @@ class ClientUser extends User {
* @returns {Promise} * @returns {Promise}
*/ */
setPassword(oldPassword, newPassword) { setPassword(oldPassword, newPassword) {
if (!oldPassword && !this.client.password) if (!oldPassword && !this.client.password) {
throw new Error('A password is required to change a password.'); throw new Error('A password is required to change a password.');
}
if (!newPassword) throw new Error('New password is required.'); if (!newPassword) throw new Error('New password is required.');
return this.edit({ return this.edit({
password: this.client.password ? this.client.password : oldPassword, password: this.client.password ? this.client.password : oldPassword,
@@ -242,8 +247,9 @@ class ClientUser extends User {
* @returns {Promise} * @returns {Promise}
*/ */
async disableAccount(password) { async disableAccount(password) {
if (!password && !this.client.password) if (!password && !this.client.password) {
throw new Error('A password is required to disable an account.'); throw new Error('A password is required to disable an account.');
}
return await this.client.api.users['@me'].disable.post({ return await this.client.api.users['@me'].disable.post({
data: { data: {
password: this.client.password ? this.client.password : password, password: this.client.password ? this.client.password : password,
@@ -257,8 +263,9 @@ class ClientUser extends User {
* @returns {Promise} * @returns {Promise}
*/ */
async deleteAccount(password) { async deleteAccount(password) {
if (!password && !this.client.password) if (!password && !this.client.password) {
throw new Error('A password is required to delete an account.'); throw new Error('A password is required to delete an account.');
}
return await this.client.api.users['@me'].delete.post({ return await this.client.api.users['@me'].delete.post({
data: { data: {
password: this.client.password ? this.client.password : password, password: this.client.password ? this.client.password : password,
@@ -336,14 +343,11 @@ class ClientUser extends User {
* client.user.setActivity('discord.js', { type: 'WATCHING' }); * client.user.setActivity('discord.js', { type: 'WATCHING' });
*/ */
setActivity(name, options = {}) { setActivity(name, options = {}) {
if (!name) if (!name) {
return this.setPresence({ activities: [], shardId: options.shardId }); return this.setPresence({ activities: [], shardId: options.shardId });
}
const activity = Object.assign( const activity = Object.assign({}, options, typeof name === 'object' ? name : { name });
{},
options,
typeof name === 'object' ? name : { name },
);
return this.setPresence({ return this.setPresence({
activities: [activity], activities: [activity],
shardId: activity.shardId, shardId: activity.shardId,

View File

@@ -312,8 +312,7 @@ class Guild extends AnonymousGuild {
* The explicit content filter level of the guild * The explicit content filter level of the guild
* @type {ExplicitContentFilterLevel} * @type {ExplicitContentFilterLevel}
*/ */
this.explicitContentFilter = this.explicitContentFilter = ExplicitContentFilterLevels[data.explicit_content_filter];
ExplicitContentFilterLevels[data.explicit_content_filter];
} }
if ('mfa_level' in data) { if ('mfa_level' in data) {
@@ -337,8 +336,7 @@ class Guild extends AnonymousGuild {
* The default message notification level of the guild * The default message notification level of the guild
* @type {DefaultMessageNotificationLevel} * @type {DefaultMessageNotificationLevel}
*/ */
this.defaultMessageNotifications = this.defaultMessageNotifications = DefaultMessageNotificationLevels[data.default_message_notifications];
DefaultMessageNotificationLevels[data.default_message_notifications];
} }
if ('system_channel_flags' in data) { if ('system_channel_flags' in data) {
@@ -346,9 +344,7 @@ class Guild extends AnonymousGuild {
* The value set for the guild's system channel flags * The value set for the guild's system channel flags
* @type {Readonly<SystemChannelFlags>} * @type {Readonly<SystemChannelFlags>}
*/ */
this.systemChannelFlags = new SystemChannelFlags( this.systemChannelFlags = new SystemChannelFlags(data.system_channel_flags).freeze();
data.system_channel_flags,
).freeze();
} }
if ('max_members' in data) { if ('max_members' in data) {
@@ -504,8 +500,9 @@ class Guild extends AnonymousGuild {
* @type {GuildStickerManager} * @type {GuildStickerManager}
*/ */
this.stickers = new GuildStickerManager(this); this.stickers = new GuildStickerManager(this);
if (data.stickers) if (data.stickers) {
for (const sticker of data.stickers) this.stickers._add(sticker); for (const sticker of data.stickers) this.stickers._add(sticker);
}
} else if (data.stickers) { } else if (data.stickers) {
this.client.actions.GuildStickersUpdate.handle({ this.client.actions.GuildStickersUpdate.handle({
guild_id: this.id, guild_id: this.id,
@@ -529,15 +526,7 @@ class Guild extends AnonymousGuild {
* @returns {?string} * @returns {?string}
*/ */
discoverySplashURL({ format, size } = {}) { discoverySplashURL({ format, size } = {}) {
return ( return this.discoverySplash && this.client.rest.cdn.DiscoverySplash(this.id, this.discoverySplash, format, size);
this.discoverySplash &&
this.client.rest.cdn.DiscoverySplash(
this.id,
this.discoverySplash,
format,
size,
)
);
} }
/** /**
@@ -658,10 +647,12 @@ class Guild extends AnonymousGuild {
else if (type == 'USER') type = 2; else if (type == 'USER') type = 2;
else if (type == 'MESSAGE') type = 3; else if (type == 'MESSAGE') type = 3;
} }
if (type < 1 || type > 3) if (type < 1 || type > 3) {
throw new RangeError('Type must be 1, 2, 3'); throw new RangeError('Type must be 1, 2, 3');
if (typeof type !== 'number') }
if (typeof type !== 'number') {
throw new TypeError('Type must be a number | string'); throw new TypeError('Type must be a number | string');
}
this.shard.send({ this.shard.send({
op: Opcodes.REQUEST_APPLICATION_COMMANDS, op: Opcodes.REQUEST_APPLICATION_COMMANDS,
d: { d: {
@@ -689,11 +680,7 @@ class Guild extends AnonymousGuild {
async fetchIntegrations() { async fetchIntegrations() {
const data = await this.client.api.guilds(this.id).integrations.get(); const data = await this.client.api.guilds(this.id).integrations.get();
return data.reduce( return data.reduce(
(collection, integration) => (collection, integration) => collection.set(integration.id, new Integration(this.client, integration, this)),
collection.set(
integration.id,
new Integration(this.client, integration, this),
),
new Collection(), new Collection(),
); );
} }
@@ -705,10 +692,7 @@ class Guild extends AnonymousGuild {
*/ */
async fetchTemplates() { async fetchTemplates() {
const templates = await this.client.api.guilds(this.id).templates.get(); const templates = await this.client.api.guilds(this.id).templates.get();
return templates.reduce( return templates.reduce((col, data) => col.set(data.code, new GuildTemplate(this.client, data)), new Collection());
(col, data) => col.set(data.code, new GuildTemplate(this.client, data)),
new Collection(),
);
} }
/** /**
@@ -727,9 +711,7 @@ class Guild extends AnonymousGuild {
* @returns {Promise<GuildTemplate>} * @returns {Promise<GuildTemplate>}
*/ */
async createTemplate(name, description) { async createTemplate(name, description) {
const data = await this.client.api const data = await this.client.api.guilds(this.id).templates.post({ data: { name, description } });
.guilds(this.id)
.templates.post({ data: { name, description } });
return new GuildTemplate(this.client, data); return new GuildTemplate(this.client, data);
} }
@@ -784,8 +766,9 @@ class Guild extends AnonymousGuild {
async fetchWebhooks() { async fetchWebhooks() {
const apiHooks = await this.client.api.guilds(this.id).webhooks.get(); const apiHooks = await this.client.api.guilds(this.id).webhooks.get();
const hooks = new Collection(); const hooks = new Collection();
for (const hook of apiHooks) for (const hook of apiHooks) {
hooks.set(hook.id, new Webhook(this.client, hook)); hooks.set(hook.id, new Webhook(this.client, hook));
}
return hooks; return hooks;
} }
@@ -831,9 +814,7 @@ class Guild extends AnonymousGuild {
this.widgetChannelId = data.channel_id; this.widgetChannelId = data.channel_id;
return { return {
enabled: data.enabled, enabled: data.enabled,
channel: data.channel_id channel: data.channel_id ? this.channels.cache.get(data.channel_id) : null,
? this.channels.cache.get(data.channel_id)
: null,
}; };
} }
@@ -857,10 +838,12 @@ class Guild extends AnonymousGuild {
* .catch(console.error); * .catch(console.error);
*/ */
async fetchAuditLogs(options = {}) { async fetchAuditLogs(options = {}) {
if (options.before && options.before instanceof GuildAuditLogs.Entry) if (options.before && options.before instanceof GuildAuditLogs.Entry) {
options.before = options.before.id; options.before = options.before.id;
if (typeof options.type === 'string') }
if (typeof options.type === 'string') {
options.type = GuildAuditLogs.Actions[options.type]; options.type = GuildAuditLogs.Actions[options.type];
}
const data = await this.client.api.guilds(this.id)['audit-logs'].get({ const data = await this.client.api.guilds(this.id)['audit-logs'].get({
query: { query: {
@@ -938,23 +921,22 @@ class Guild extends AnonymousGuild {
_data.afk_channel_id = this.client.channels.resolveId(data.afkChannel); _data.afk_channel_id = this.client.channels.resolveId(data.afkChannel);
} }
if (typeof data.systemChannel !== 'undefined') { if (typeof data.systemChannel !== 'undefined') {
_data.system_channel_id = this.client.channels.resolveId( _data.system_channel_id = this.client.channels.resolveId(data.systemChannel);
data.systemChannel,
);
} }
if (data.afkTimeout) _data.afk_timeout = Number(data.afkTimeout); if (data.afkTimeout) _data.afk_timeout = Number(data.afkTimeout);
if (typeof data.icon !== 'undefined') if (typeof data.icon !== 'undefined') {
_data.icon = await DataResolver.resolveImage(data.icon); _data.icon = await DataResolver.resolveImage(data.icon);
if (data.owner) _data.owner_id = this.client.users.resolveId(data.owner);
if (typeof data.splash !== 'undefined')
_data.splash = await DataResolver.resolveImage(data.splash);
if (typeof data.discoverySplash !== 'undefined') {
_data.discovery_splash = await DataResolver.resolveImage(
data.discoverySplash,
);
} }
if (typeof data.banner !== 'undefined') if (data.owner) _data.owner_id = this.client.users.resolveId(data.owner);
if (typeof data.splash !== 'undefined') {
_data.splash = await DataResolver.resolveImage(data.splash);
}
if (typeof data.discoverySplash !== 'undefined') {
_data.discovery_splash = await DataResolver.resolveImage(data.discoverySplash);
}
if (typeof data.banner !== 'undefined') {
_data.banner = await DataResolver.resolveImage(data.banner); _data.banner = await DataResolver.resolveImage(data.banner);
}
if (typeof data.explicitContentFilter !== 'undefined') { if (typeof data.explicitContentFilter !== 'undefined') {
_data.explicit_content_filter = _data.explicit_content_filter =
typeof data.explicitContentFilter === 'number' typeof data.explicitContentFilter === 'number'
@@ -968,19 +950,13 @@ class Guild extends AnonymousGuild {
: DefaultMessageNotificationLevels[data.defaultMessageNotifications]; : DefaultMessageNotificationLevels[data.defaultMessageNotifications];
} }
if (typeof data.systemChannelFlags !== 'undefined') { if (typeof data.systemChannelFlags !== 'undefined') {
_data.system_channel_flags = SystemChannelFlags.resolve( _data.system_channel_flags = SystemChannelFlags.resolve(data.systemChannelFlags);
data.systemChannelFlags,
);
} }
if (typeof data.rulesChannel !== 'undefined') { if (typeof data.rulesChannel !== 'undefined') {
_data.rules_channel_id = this.client.channels.resolveId( _data.rules_channel_id = this.client.channels.resolveId(data.rulesChannel);
data.rulesChannel,
);
} }
if (typeof data.publicUpdatesChannel !== 'undefined') { if (typeof data.publicUpdatesChannel !== 'undefined') {
_data.public_updates_channel_id = this.client.channels.resolveId( _data.public_updates_channel_id = this.client.channels.resolveId(data.publicUpdatesChannel);
data.publicUpdatesChannel,
);
} }
if (typeof data.features !== 'undefined') { if (typeof data.features !== 'undefined') {
_data.features = data.features; _data.features = data.features;
@@ -989,11 +965,10 @@ class Guild extends AnonymousGuild {
_data.description = data.description; _data.description = data.description;
} }
if (data.preferredLocale) _data.preferred_locale = data.preferredLocale; if (data.preferredLocale) _data.preferred_locale = data.preferredLocale;
if ('premiumProgressBarEnabled' in data) if ('premiumProgressBarEnabled' in data) {
_data.premium_progress_bar_enabled = data.premiumProgressBarEnabled; _data.premium_progress_bar_enabled = data.premiumProgressBarEnabled;
const newData = await this.client.api }
.guilds(this.id) const newData = await this.client.api.guilds(this.id).patch({ data: _data, reason });
.patch({ data: _data, reason });
return this.client.actions.GuildUpdate.handle(newData).updated; return this.client.actions.GuildUpdate.handle(newData).updated;
} }
@@ -1047,7 +1022,7 @@ class Guild extends AnonymousGuild {
*/ */
async editWelcomeScreen(data) { async editWelcomeScreen(data) {
const { enabled, description, welcomeChannels } = data; const { enabled, description, welcomeChannels } = data;
const welcome_channels = welcomeChannels?.map((welcomeChannelData) => { const welcome_channels = welcomeChannels?.map(welcomeChannelData => {
const emoji = this.emojis.resolve(welcomeChannelData.emoji); const emoji = this.emojis.resolve(welcomeChannelData.emoji);
return { return {
emoji_id: emoji?.id, emoji_id: emoji?.id,
@@ -1057,9 +1032,7 @@ class Guild extends AnonymousGuild {
}; };
}); });
const patchData = await this.client.api const patchData = await this.client.api.guilds(this.id, 'welcome-screen').patch({
.guilds(this.id, 'welcome-screen')
.patch({
data: { data: {
welcome_channels, welcome_channels,
description, description,
@@ -1282,33 +1255,24 @@ class Guild extends AnonymousGuild {
async setPosition(position, type, folderID) { async setPosition(position, type, folderID) {
if (type == 1 || `${type}`.toUpperCase() === 'FOLDER') { if (type == 1 || `${type}`.toUpperCase() === 'FOLDER') {
folderID = folderID || this.folder.folderId; folderID = folderID || this.folder.folderId;
if (!['number', 'string'].includes(typeof folderID)) if (!['number', 'string'].includes(typeof folderID)) {
throw new TypeError('INVALID_TYPE', 'folderID', 'String | Number'); throw new TypeError('INVALID_TYPE', 'folderID', 'String | Number');
}
// Get Data from Folder ID // Get Data from Folder ID
const folder = await this.client.setting.rawSetting.guild_folders.find( const folder = await this.client.setting.rawSetting.guild_folders.find(obj => obj.id == folderID);
(obj) => obj.id == folderID,
);
if (!folder) throw new Error('FOLDER_NOT_FOUND'); if (!folder) throw new Error('FOLDER_NOT_FOUND');
if (folder.guild_ids.length - 1 < position || position < 0) if (folder.guild_ids.length - 1 < position || position < 0) {
throw new Error('FOLDER_POSITION_INVALID'); throw new Error('FOLDER_POSITION_INVALID');
}
if (position !== folder.guild_ids.indexOf(this.id)) { if (position !== folder.guild_ids.indexOf(this.id)) {
await this.client.setting.guildChangePosition( await this.client.setting.guildChangePosition(this.id, position, 1, folderID);
this.id,
position,
1,
folderID,
);
} }
} else if (type == 2 || `${type}`.toUpperCase() === 'HOME') { } else if (type == 2 || `${type}`.toUpperCase() === 'HOME') {
if (this.client.setting.guild_positions - 1 < position || position < 0) if (this.client.setting.guild_positions - 1 < position || position < 0) {
throw new Error('FOLDER_POSITION_INVALID'); throw new Error('FOLDER_POSITION_INVALID');
}
if (position !== this.position) { if (position !== this.position) {
await this.client.setting.guildChangePosition( await this.client.setting.guildChangePosition(this.id, position, 2, null);
this.id,
position,
2,
null,
);
} }
} else { } else {
throw new TypeError('INVALID_TYPE', 'type', '`Folder`| `Home`'); throw new TypeError('INVALID_TYPE', 'type', '`Folder`| `Home`');
@@ -1506,12 +1470,7 @@ class Guild extends AnonymousGuild {
* @param {TextChannelResolvable} rulesChannel * @param {TextChannelResolvable} rulesChannel
* @param {String} reason * @param {String} reason
*/ */
async setCommunity( async setCommunity(stats = true, publicUpdatesChannel = '1', rulesChannel = '1', reason) {
stats = true,
publicUpdatesChannel = '1',
rulesChannel = '1',
reason,
) {
if (stats) { if (stats) {
// Check everyone role // Check everyone role
const everyoneRole = this.roles.everyone; const everyoneRole = this.roles.everyone;
@@ -1526,10 +1485,7 @@ class Guild extends AnonymousGuild {
features: [...this.features, 'COMMUNITY'], features: [...this.features, 'COMMUNITY'],
publicUpdatesChannel, publicUpdatesChannel,
rulesChannel, rulesChannel,
verificationLevel: verificationLevel: VerificationLevels[this.verificationLevel] < 1 ? 'LOW' : this.verificationLevel, // Email
VerificationLevels[this.verificationLevel] < 1
? 'LOW'
: this.verificationLevel, // Email
}, },
reason, reason,
); );
@@ -1538,7 +1494,7 @@ class Guild extends AnonymousGuild {
{ {
publicUpdatesChannel: null, publicUpdatesChannel: null,
rulesChannel: null, rulesChannel: null,
features: this.features.filter((f) => f !== 'COMMUNITY'), features: this.features.filter(f => f !== 'COMMUNITY'),
preferredLocale: this.preferredLocale, preferredLocale: this.preferredLocale,
description: this.description, description: this.description,
}, },
@@ -1569,10 +1525,10 @@ class Guild extends AnonymousGuild {
* @readonly * @readonly
*/ */
get voiceAdapterCreator() { get voiceAdapterCreator() {
return (methods) => { return methods => {
this.client.voice.adapters.set(this.id, methods); this.client.voice.adapters.set(this.id, methods);
return { return {
sendPayload: (data) => { sendPayload: data => {
if (this.shard.status !== Status.READY) return false; if (this.shard.status !== Status.READY) return false;
this.shard.send(data); this.shard.send(data);
return true; return true;
@@ -1603,7 +1559,7 @@ class Guild extends AnonymousGuild {
const category = channel.type === ChannelTypes.GUILD_CATEGORY; const category = channel.type === ChannelTypes.GUILD_CATEGORY;
return Util.discordSort( return Util.discordSort(
this.channels.cache.filter( this.channels.cache.filter(
(c) => c =>
(['GUILD_TEXT', 'GUILD_NEWS', 'GUILD_STORE'].includes(channel.type) (['GUILD_TEXT', 'GUILD_NEWS', 'GUILD_STORE'].includes(channel.type)
? ['GUILD_TEXT', 'GUILD_NEWS', 'GUILD_STORE'].includes(c.type) ? ['GUILD_TEXT', 'GUILD_NEWS', 'GUILD_STORE'].includes(c.type)
: c.type === channel.type) && : c.type === channel.type) &&

View File

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

View File

@@ -20,7 +20,7 @@ const Permissions = require('../util/Permissions');
const SnowflakeUtil = require('../util/SnowflakeUtil'); const SnowflakeUtil = require('../util/SnowflakeUtil');
const Util = require('../util/Util'); const Util = require('../util/Util');
const { findBestMatch } = require('string-similarity'); // not check similarity const { findBestMatch } = require('string-similarity'); // not check similarity
//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<Message>} * @type {WeakSet<Message>}
@@ -140,7 +140,7 @@ class Message extends Base {
* A list of embeds in the message - e.g. YouTube Player * A list of embeds in the message - e.g. YouTube Player
* @type {MessageEmbed[]} * @type {MessageEmbed[]}
*/ */
this.embeds = data.embeds.map((e) => new Embed(e, true)); this.embeds = data.embeds.map(e => new Embed(e, true));
} else { } else {
this.embeds = this.embeds?.slice() ?? []; this.embeds = this.embeds?.slice() ?? [];
} }
@@ -150,9 +150,7 @@ class Message extends Base {
* A list of MessageActionRows in the message * A list of MessageActionRows in the message
* @type {MessageActionRow[]} * @type {MessageActionRow[]}
*/ */
this.components = data.components.map((c) => this.components = data.components.map(c => BaseMessageComponent.create(c, this.client));
BaseMessageComponent.create(c, this.client),
);
} else { } else {
this.components = this.components?.slice() ?? []; this.components = this.components?.slice() ?? [];
} }
@@ -165,14 +163,7 @@ class Message extends Base {
this.attachments = new Collection(); this.attachments = new Collection();
if (data.attachments) { if (data.attachments) {
for (const attachment of data.attachments) { for (const attachment of data.attachments) {
this.attachments.set( this.attachments.set(attachment.id, new MessageAttachment(attachment.url, attachment.filename, attachment));
attachment.id,
new MessageAttachment(
attachment.url,
attachment.filename,
attachment,
),
);
} }
} }
} else { } else {
@@ -185,10 +176,7 @@ class Message extends Base {
* @type {Collection<Snowflake, Sticker>} * @type {Collection<Snowflake, Sticker>}
*/ */
this.stickers = new Collection( this.stickers = new Collection(
(data.sticker_items ?? data.stickers)?.map((s) => [ (data.sticker_items ?? data.stickers)?.map(s => [s.id, new Sticker(this.client, s)]),
s.id,
new Sticker(this.client, s),
]),
); );
} else { } else {
this.stickers = new Collection(this.stickers); this.stickers = new Collection(this.stickers);
@@ -259,10 +247,7 @@ class Message extends Base {
* Supplemental application information for group activities * Supplemental application information for group activities
* @type {?ClientApplication} * @type {?ClientApplication}
*/ */
this.groupActivityApplication = new ClientApplication( this.groupActivityApplication = new ClientApplication(this.client, data.application);
this.client,
data.application,
);
} else { } else {
this.groupActivityApplication ??= null; this.groupActivityApplication ??= null;
} }
@@ -297,9 +282,7 @@ class Message extends Base {
if (this.member && data.member) { if (this.member && data.member) {
this.member._patch(data.member); this.member._patch(data.member);
} else if (data.member && this.guild && this.author) { } else if (data.member && this.guild && this.author) {
this.guild.members._add( this.guild.members._add(Object.assign(data.member, { user: this.author }));
Object.assign(data.member, { user: this.author }),
);
} }
if ('flags' in data) { if ('flags' in data) {
@@ -455,9 +438,7 @@ class Message extends Base {
* @readonly * @readonly
*/ */
get guild() { get guild() {
return ( return this.client.guilds.resolve(this.guildId) ?? this.channel?.guild ?? null;
this.client.guilds.resolve(this.guildId) ?? this.channel?.guild ?? null
);
} }
/** /**
@@ -486,8 +467,7 @@ class Message extends Base {
* @readonly * @readonly
*/ */
get url() { get url() {
return `https://discord.com/channels/${this.guildId ?? '@me'}/${this.channelId return `https://discord.com/channels/${this.guildId ?? '@me'}/${this.channelId}/${this.id}`;
}/${this.id}`;
} }
/** /**
@@ -498,9 +478,7 @@ class Message extends Base {
*/ */
get cleanContent() { get cleanContent() {
// eslint-disable-next-line eqeqeq // eslint-disable-next-line eqeqeq
return this.content != null return this.content != null ? Util.cleanContent(this.content, this.channel) : null;
? Util.cleanContent(this.content, this.channel)
: null;
} }
/** /**
@@ -612,9 +590,7 @@ class Message extends Base {
*/ */
get editable() { get editable() {
const precheck = Boolean( const precheck = Boolean(
this.author.id === this.client.user.id && this.author.id === this.client.user.id && !deletedMessages.has(this) && (!this.guild || this.channel?.viewable),
!deletedMessages.has(this) &&
(!this.guild || this.channel?.viewable),
); );
// Regardless of permissions thread messages cannot be edited if // Regardless of permissions thread messages cannot be edited if
// the thread is locked. // the thread is locked.
@@ -665,9 +641,7 @@ class Message extends Base {
!deletedMessages.has(this) && !deletedMessages.has(this) &&
(!this.guild || (!this.guild ||
(channel?.viewable && (channel?.viewable &&
channel channel?.permissionsFor(this.client.user)?.has(Permissions.FLAGS.MANAGE_MESSAGES, false))),
?.permissionsFor(this.client.user)
?.has(Permissions.FLAGS.MANAGE_MESSAGES, false))),
); );
} }
@@ -692,9 +666,7 @@ class Message extends Base {
get crosspostable() { get crosspostable() {
const bitfield = const bitfield =
Permissions.FLAGS.SEND_MESSAGES | Permissions.FLAGS.SEND_MESSAGES |
(this.author.id === this.client.user.id (this.author.id === this.client.user.id ? Permissions.defaultBit : Permissions.FLAGS.MANAGE_MESSAGES);
? Permissions.defaultBit
: Permissions.FLAGS.MANAGE_MESSAGES);
const { channel } = this; const { channel } = this;
return Boolean( return Boolean(
channel?.type === 'GUILD_NEWS' && channel?.type === 'GUILD_NEWS' &&
@@ -854,8 +826,7 @@ class Message extends Base {
data = MessagePayload.create(this, options, { data = MessagePayload.create(this, options, {
reply: { reply: {
messageReference: this, messageReference: this,
failIfNotExists: failIfNotExists: options?.failIfNotExists ?? this.client.options.failIfNotExists,
options?.failIfNotExists ?? this.client.options.failIfNotExists,
}, },
}); });
} }
@@ -894,8 +865,9 @@ class Message extends Base {
if (!['GUILD_TEXT', 'GUILD_NEWS'].includes(this.channel.type)) { if (!['GUILD_TEXT', 'GUILD_NEWS'].includes(this.channel.type)) {
return Promise.reject(new Error('MESSAGE_THREAD_PARENT')); return Promise.reject(new Error('MESSAGE_THREAD_PARENT'));
} }
if (this.hasThread) if (this.hasThread) {
return Promise.reject(new Error('MESSAGE_EXISTING_THREAD')); return Promise.reject(new Error('MESSAGE_EXISTING_THREAD'));
}
return this.channel.threads.create({ ...options, startMessage: this }); return this.channel.threads.create({ ...options, startMessage: this });
} }
@@ -915,8 +887,9 @@ class Message extends Base {
*/ */
fetchWebhook() { fetchWebhook() {
if (!this.webhookId) return Promise.reject(new Error('WEBHOOK_MESSAGE')); if (!this.webhookId) return Promise.reject(new Error('WEBHOOK_MESSAGE'));
if (this.webhookId === this.applicationId) if (this.webhookId === this.applicationId) {
return Promise.reject(new Error('WEBHOOK_APPLICATION')); return Promise.reject(new Error('WEBHOOK_APPLICATION'));
}
return this.client.fetchWebhook(this.webhookId); return this.client.fetchWebhook(this.webhookId);
} }
@@ -951,11 +924,7 @@ class Message extends Base {
* @returns {?MessageActionRowComponent} * @returns {?MessageActionRowComponent}
*/ */
resolveComponent(customId) { resolveComponent(customId) {
return ( return this.components.flatMap(row => row.components).find(component => component.customId === customId) ?? null;
this.components
.flatMap((row) => row.components)
.find((component) => component.customId === customId) ?? null
);
} }
/** /**
@@ -969,10 +938,9 @@ class Message extends Base {
equals(message, rawData) { equals(message, rawData) {
if (!message) return false; if (!message) return false;
const embedUpdate = !message.author && !message.attachments; const embedUpdate = !message.author && !message.attachments;
if (embedUpdate) if (embedUpdate) {
return ( return this.id === message.id && this.embeds.length === message.embeds.length;
this.id === message.id && this.embeds.length === message.embeds.length }
);
let equal = let equal =
this.id === message.id && this.id === message.id &&
@@ -1030,18 +998,16 @@ class Message extends Base {
* @returns {Promise<pending>} * @returns {Promise<pending>}
*/ */
async clickButton(buttonID) { async clickButton(buttonID) {
if (typeof buttonID !== 'string') if (typeof buttonID !== 'string') {
throw new TypeError('BUTTON_ID_NOT_STRING'); throw new TypeError('BUTTON_ID_NOT_STRING');
}
if (!this.components[0]) throw new TypeError('MESSAGE_NO_COMPONENTS'); if (!this.components[0]) throw new TypeError('MESSAGE_NO_COMPONENTS');
let button; let button;
await Promise.all( await Promise.all(
this.components.map(async (row) => { this.components.map(async row => {
await Promise.all( await Promise.all(
row.components.map(async (interactionComponent) => { row.components.map(async interactionComponent => {
if ( if (interactionComponent.type == 'BUTTON' && interactionComponent.customId == buttonID) {
interactionComponent.type == 'BUTTON' &&
interactionComponent.customId == buttonID
) {
button = interactionComponent; button = interactionComponent;
} }
}), }),
@@ -1062,7 +1028,7 @@ class Message extends Base {
let menuCorrect; let menuCorrect;
let menuCount = 0; let menuCount = 0;
await Promise.all( await Promise.all(
this.components.map(async (row) => { this.components.map(async row => {
const firstElement = row.components[0]; // Because 1 row has only 1 menu; const firstElement = row.components[0]; // Because 1 row has only 1 menu;
if (firstElement.type == 'SELECT_MENU') { if (firstElement.type == 'SELECT_MENU') {
menuCount++; menuCount++;
@@ -1091,31 +1057,31 @@ class Message extends Base {
*/ */
async contextMenu(botID, commandName) { async contextMenu(botID, commandName) {
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(() => { }); const user = await this.client.users.fetch(botID).catch(() => {});
if (!user || !user.bot || !user.applications) if (!user || !user.bot || !user.applications) {
throw new Error( throw new Error('BotID is not a bot or does not have an application slash command');
'BotID is not a bot or does not have an application slash command', }
); if (!commandName || typeof commandName !== 'string') {
if (!commandName || typeof commandName !== 'string')
throw new Error('Command name is required'); throw new Error('Command name is required');
}
const listApplication = const listApplication =
user.applications.cache.size == 0 user.applications.cache.size == 0 ? await user.applications.fetch() : user.applications.cache;
? await user.applications.fetch()
: user.applications.cache;
let contextCMD; let contextCMD;
await Promise.all( await Promise.all(
listApplication.map(async (application) => { listApplication.map(async application => {
if (commandName == application.name && application.type !== 'CHAT_INPUT') if (commandName == application.name && application.type !== 'CHAT_INPUT') {
contextCMD = application; contextCMD = application;
}
}), }),
); );
if (!contextCMD) if (!contextCMD) {
throw new Error( throw new Error(
`Command ${commandName} is not found\nList command avalible: ${listApplication `Command ${commandName} is not found\nList command avalible: ${listApplication
.filter((a) => a.type !== 'CHAT_INPUT') .filter(a => a.type !== 'CHAT_INPUT')
.map((a) => a.name) .map(a => a.name)
.join(', ')}`, .join(', ')}`,
); );
}
return contextCMD.sendContextMenu(this, true); return contextCMD.sendContextMenu(this, true);
} }
} }

View File

@@ -168,10 +168,9 @@ class MessageButton extends BaseMessageComponent {
* @returns {boolean} * @returns {boolean}
*/ */
async click(message) { 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 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: { data: {
type: 3, // ? type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs guild_id: message.guild?.id ?? null, // In DMs
@@ -181,11 +180,10 @@ class MessageButton extends BaseMessageComponent {
session_id: message.client.session_id, session_id: message.client.session_id,
data: { data: {
component_type: 2, // Button component_type: 2, // Button
custom_id: this.customId custom_id: this.customId,
}, },
} },
} });
)
return true; return true;
} }
} }

View File

@@ -194,9 +194,7 @@ class MessagePayload {
this.options.embeds = [this.options.embeds]; this.options.embeds = [this.options.embeds];
} }
const webembeds = this.options.embeds.filter( const webembeds = this.options.embeds.filter(e => e instanceof WebEmbed);
(e) => e instanceof WebEmbed,
);
this.options.embeds = this.options.embeds.filter(e => e instanceof MessageEmbed); this.options.embeds = this.options.embeds.filter(e => e instanceof MessageEmbed);
if (webembeds.length > 0) { if (webembeds.length > 0) {
@@ -214,9 +212,10 @@ class MessagePayload {
} }
// Check content // Check content
if (content.length > 2000) { 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'); throw new RangeError('MESSAGE_EMBED_LINK_LENGTH');
} }
} }

View File

@@ -218,21 +218,28 @@ class MessageSelectMenu extends BaseMessageComponent {
async select(message, values = []) { async select(message, values = []) {
// Github copilot is the best :)) // Github copilot is the best :))
// POST data from https://github.com/phamleduy04 // POST data from https://github.com/phamleduy04
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 (!Array.isArray(values)) throw new TypeError("[INVALID_VALUES] Please pass an array of values"); 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 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 // 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.minValues)
if (values.length > this.maxValues) throw new RangeError("[SELECT_MENU_MAX_VALUES] The maximum number of values is " + this.maxValues); 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 validValue = this.options.map(obj => obj.value);
const check_ = await values.find(element => { const check_ = await values.find(element => {
if (typeof element !== 'string') return true; if (typeof element !== 'string') return true;
if (!validValue.includes(element)) return true; if (!validValue.includes(element)) return true;
return false; return false;
}) });
if (check_) throw new RangeError("[SELECT_MENU_INVALID_VALUE] The value " + check_ + " is invalid. Please use a valid value " + validValue.join(', ')); if (check_)
await message.client.api.interactions.post( 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: { data: {
type: 3, // ? type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs guild_id: message.guild?.id ?? null, // In DMs
@@ -246,9 +253,8 @@ class MessageSelectMenu extends BaseMessageComponent {
type: 3, // Select Menu type: 3, // Select Menu
values, values,
}, },
} },
} });
)
return true; return true;
} }
} }

View File

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

View File

@@ -57,11 +57,7 @@ class User extends Base {
*/ */
this.bot = Boolean(data.bot); this.bot = Boolean(data.bot);
if (this.bot == true) { if (this.bot == true) {
this.applications = new ApplicationCommandManager( this.applications = new ApplicationCommandManager(this.client, undefined, this);
this.client,
undefined,
this,
);
} }
} else if (!this.partial && typeof this.bot !== 'boolean') { } else if (!this.partial && typeof this.bot !== 'boolean') {
this.bot = false; this.bot = false;
@@ -149,8 +145,9 @@ class User extends Base {
_ProfilePatch(data) { _ProfilePatch(data) {
if (!data) return; if (!data) return;
if (data.connected_accounts.length > 0) if (data.connected_accounts.length > 0) {
this.connectedAccounts = data.connected_accounts; this.connectedAccounts = data.connected_accounts;
}
if ('premium_since' in data) { if ('premium_since' in data) {
const date = new Date(data.premium_since); const date = new Date(data.premium_since);
@@ -162,9 +159,7 @@ class User extends Base {
this.premiumGuildSince = date.getTime(); this.premiumGuildSince = date.getTime();
} }
this.mutualGuilds = new Collection( this.mutualGuilds = new Collection(data.mutual_guilds.map(obj => [obj.id, obj]));
data.mutual_guilds.map((obj) => [obj.id, obj]),
);
} }
/** /**
@@ -195,10 +190,7 @@ class User extends Base {
* @returns {Promise<User>} the user object * @returns {Promise<User>} the user object
*/ */
async sendFriendRequest() { async sendFriendRequest() {
return this.client.relationships.sendFriendRequest( return this.client.relationships.sendFriendRequest(this.username, this.discriminator);
this.username,
this.discriminator,
);
} }
/** /**
* Blocks the user * Blocks the user
@@ -258,13 +250,7 @@ class User extends Base {
*/ */
avatarURL({ format, size, dynamic } = {}) { avatarURL({ format, size, dynamic } = {}) {
if (!this.avatar) return null; if (!this.avatar) return null;
return this.client.rest.cdn.Avatar( return this.client.rest.cdn.Avatar(this.id, this.avatar, format, size, dynamic);
this.id,
this.avatar,
format,
size,
dynamic,
);
} }
/** /**
@@ -305,16 +291,11 @@ class User extends Base {
* @returns {?string} * @returns {?string}
*/ */
bannerURL({ format, size, dynamic } = {}) { bannerURL({ format, size, dynamic } = {}) {
if (typeof this.banner === 'undefined') if (typeof this.banner === 'undefined') {
throw new Error('USER_BANNER_NOT_FETCHED'); throw new Error('USER_BANNER_NOT_FETCHED');
}
if (!this.banner) return null; if (!this.banner) return null;
return this.client.rest.cdn.Banner( return this.client.rest.cdn.Banner(this.id, this.banner, format, size, dynamic);
this.id,
this.banner,
format,
size,
dynamic,
);
} }
/** /**
@@ -323,9 +304,7 @@ class User extends Base {
* @readonly * @readonly
*/ */
get tag() { get tag() {
return typeof this.username === 'string' return typeof this.username === 'string' ? `${this.username}#${this.discriminator}` : null;
? `${this.username}#${this.discriminator}`
: null;
} }
/** /**

View File

@@ -217,11 +217,7 @@ class WebEmbed {
* @returns {MessageEmbed} * @returns {MessageEmbed}
*/ */
setDescription(description) { setDescription(description) {
this.description = Util.verifyString( this.description = Util.verifyString(description, RangeError, 'EMBED_DESCRIPTION');
description,
RangeError,
'EMBED_DESCRIPTION',
);
return this; return this;
} }
@@ -301,9 +297,7 @@ class WebEmbed {
arrayQuery.push(`url=${encodeURIComponent(this.url)}`); arrayQuery.push(`url=${encodeURIComponent(this.url)}`);
} }
if (this.color) { if (this.color) {
arrayQuery.push( arrayQuery.push(`color=${encodeURIComponent('#' + this.color.toString(16))}`);
`color=${encodeURIComponent('#' + this.color.toString(16))}`,
);
} }
if (this.image?.url) { if (this.image?.url) {
arrayQuery.push(`image=${encodeURIComponent(this.image.url)}`); arrayQuery.push(`image=${encodeURIComponent(this.image.url)}`);
@@ -312,20 +306,20 @@ class WebEmbed {
arrayQuery.push(`video=${encodeURIComponent(this.video.url)}`); arrayQuery.push(`video=${encodeURIComponent(this.video.url)}`);
} }
if (this.author) { if (this.author) {
if (this.author.name) if (this.author.name) {
arrayQuery.push(`author_name=${encodeURIComponent(this.author.name)}`); arrayQuery.push(`author_name=${encodeURIComponent(this.author.name)}`);
if (this.author.url) }
if (this.author.url) {
arrayQuery.push(`author_url=${encodeURIComponent(this.author.url)}`); arrayQuery.push(`author_url=${encodeURIComponent(this.author.url)}`);
} }
}
if (this.provider) { if (this.provider) {
if (this.provider.name) if (this.provider.name) {
arrayQuery.push( arrayQuery.push(`provider_name=${encodeURIComponent(this.provider.name)}`);
`provider_name=${encodeURIComponent(this.provider.name)}`, }
); if (this.provider.url) {
if (this.provider.url) arrayQuery.push(`provider_url=${encodeURIComponent(this.provider.url)}`);
arrayQuery.push( }
`provider_url=${encodeURIComponent(this.provider.url)}`,
);
} }
if (this.thumbnail?.url) { if (this.thumbnail?.url) {
arrayQuery.push(`image=${encodeURIComponent(this.thumbnail.url)}`); arrayQuery.push(`image=${encodeURIComponent(this.thumbnail.url)}`);
@@ -334,9 +328,7 @@ class WebEmbed {
if (this.shorten) { if (this.shorten) {
const url = await getShorten(fullURL); const url = await getShorten(fullURL);
if (!url) console.log('Cannot shorten URL in WebEmbed'); if (!url) console.log('Cannot shorten URL in WebEmbed');
return this.hidden return this.hidden ? `${hiddenCharter} ${url || fullURL}` : url || fullURL;
? `${hiddenCharter} ${url || fullURL}`
: url || fullURL;
} else { } else {
return this.hidden ? `${hiddenCharter} ${fullURL}` : fullURL; return this.hidden ? `${hiddenCharter} ${fullURL}` : fullURL;
} }
@@ -344,27 +336,23 @@ class WebEmbed {
} }
// Credit: https://www.npmjs.com/package/node-url-shortener + google :)) // Credit: https://www.npmjs.com/package/node-url-shortener + google :))
const getShorten = async (url) => { const getShorten = async url => {
const APIurl = [ const APIurl = [
// 'https://is.gd/create.php?format=simple&url=', :( // 'https://is.gd/create.php?format=simple&url=', :(
'https://tinyurl.com/api-create.php?url=', 'https://tinyurl.com/api-create.php?url=',
'https://sagiri-fansub.tk/api/v1/short?url=', // my api, pls don't ddos :( 'https://sagiri-fansub.tk/api/v1/short?url=', // my api, pls don't ddos :(
'https://lazuee.ga/api/v1/shorten?url=' 'https://lazuee.ga/api/v1/shorten?url=',
// 'https://cdpt.in/shorten?url=', Redirects 5s :( // 'https://cdpt.in/shorten?url=', Redirects 5s :(
]; ];
try { try {
const res = await axios.get( const res = await axios.get(`${APIurl[Math.floor(Math.random() * APIurl.length)]}${encodeURIComponent(url)}`);
`${
APIurl[Math.floor(Math.random() * APIurl.length)]
}${encodeURIComponent(url)}`,
);
if (typeof res.data == 'string') return res.data; if (typeof res.data == 'string') return res.data;
else if (typeof res.data == 'object') return res.data.shorten; else if (typeof res.data == 'object') return res.data.shorten;
else throw null; else throw null;
} catch { } catch {
return void 0; return void 0;
} }
} };
module.exports = WebEmbed; module.exports = WebEmbed;
module.exports.hiddenEmbed = hiddenCharter; module.exports.hiddenEmbed = hiddenCharter;

View File

@@ -319,10 +319,7 @@ class Webhook {
if (options instanceof MessagePayload) { if (options instanceof MessagePayload) {
messagePayload = await options.resolveData(); messagePayload = await options.resolveData();
} else { } else {
messagePayload = await MessagePayload.create( messagePayload = await MessagePayload.create(message instanceof Message ? message : this, options).resolveData();
message instanceof Message ? message : this,
options,
).resolveData();
} }
const { data, files } = await messagePayload.resolveFiles(); const { data, files } = await messagePayload.resolveFiles();

View File

@@ -4,104 +4,104 @@ const process = require('node:process');
const Package = (exports.Package = require('../../package.json')); const Package = (exports.Package = require('../../package.json'));
const { Error, RangeError, TypeError } = require('../errors'); const { Error, RangeError, TypeError } = require('../errors');
const listUserAgent = [ 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/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.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) 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 (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 (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 (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 (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 (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 (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.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 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 (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 (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 (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 (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 (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/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 (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 (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; 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 (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 (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 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 (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 (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 (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 (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/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 (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 (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 (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 (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_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 (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 (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 (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 (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 (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) 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 (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; 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) 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 (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_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 (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 (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_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 (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 (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 (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 (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 (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; 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; 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 (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 (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 (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_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.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 (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/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 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 (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) 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 (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.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 (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) 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 (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 (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 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 (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_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 (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 (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 (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: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 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 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/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 (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 (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) 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; 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/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/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 (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 (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 (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/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/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 (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/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 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/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 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 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1',
] ];
exports.DMScanLevel = { exports.DMScanLevel = {
0: 'NOT_SCAN', 0: 'NOT_SCAN',
@@ -1374,7 +1374,7 @@ exports.HypeSquadOptions = createEnum(['LEAVE', 'HOUSE_BRAVERY', 'HOUSE_BRILLIAN
exports._cleanupSymbol = Symbol('djsCleanup'); exports._cleanupSymbol = Symbol('djsCleanup');
function keyMirror(arr) { function keyMirror(arr) {
let tmp = Object.create(null); const tmp = Object.create(null);
for (const value of arr) tmp[value] = value; for (const value of arr) tmp[value] = value;
return tmp; return tmp;
} }

View File

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

266
typings/index.d.ts vendored
View File

@@ -147,7 +147,7 @@ import {
RawWidgetData, RawWidgetData,
RawWidgetMemberData, RawWidgetMemberData,
} from './rawDataTypes'; } from './rawDataTypes';
import { RelationshipType } from '../src/util/Constants'; import { RelationshipTypes } from '../src/util/Constants';
//#region Classes //#region Classes
@@ -1008,7 +1008,7 @@ export class Guild extends AnonymousGuild {
public setIcon(icon: BufferResolvable | Base64Resolvable | null, reason?: string): Promise<Guild>; public setIcon(icon: BufferResolvable | Base64Resolvable | null, reason?: string): Promise<Guild>;
public setName(name: string, reason?: string): Promise<Guild>; public setName(name: string, reason?: string): Promise<Guild>;
public setOwner(owner: GuildMemberResolvable, 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 setPreferredLocale(preferredLocale: string, reason?: string): Promise<Guild>;
public setPublicUpdatesChannel(publicUpdatesChannel: TextChannelResolvable | null, reason?: string): Promise<Guild>; public setPublicUpdatesChannel(publicUpdatesChannel: TextChannelResolvable | null, reason?: string): Promise<Guild>;
/** @deprecated Use {@link RoleManager.setPositions} instead */ /** @deprecated Use {@link RoleManager.setPositions} instead */
@@ -1019,7 +1019,12 @@ export class Guild extends AnonymousGuild {
public setSystemChannelFlags(systemChannelFlags: SystemChannelFlagsResolvable, reason?: string): Promise<Guild>; public setSystemChannelFlags(systemChannelFlags: SystemChannelFlagsResolvable, reason?: string): Promise<Guild>;
public setVerificationLevel(verificationLevel: VerificationLevel | number, reason?: string): Promise<Guild>; public setVerificationLevel(verificationLevel: VerificationLevel | number, reason?: string): Promise<Guild>;
public setPremiumProgressBarEnabled(enabled?: boolean, 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 setWidgetSettings(settings: GuildWidgetSettingsData, reason?: string): Promise<Guild>;
public toJSON(): unknown; public toJSON(): unknown;
} }
@@ -1053,7 +1058,7 @@ export class GuildAuditLogsEntry<
TTargetType extends GuildAuditLogsTarget = TAction extends keyof GuildAuditLogsTypes TTargetType extends GuildAuditLogsTarget = TAction extends keyof GuildAuditLogsTypes
? GuildAuditLogsTypes[TAction][0] ? GuildAuditLogsTypes[TAction][0]
: 'UNKNOWN', : 'UNKNOWN',
> { > {
private constructor(logs: GuildAuditLogs, guild: Guild, data: RawGuildAuditLogEntryData); private constructor(logs: GuildAuditLogs, guild: Guild, data: RawGuildAuditLogEntryData);
public action: TAction; public action: TAction;
public actionType: TActionType; 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 // 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 { export class RateLimitError extends Error {
private constructor(data: RateLimitData); private constructor(data: RateLimitData);
public name: 'RateLimitError'; public name: 'RateLimitError';
@@ -1344,7 +1349,7 @@ export type CacheTypeReducer<
RawType = CachedType, RawType = CachedType,
PresentType = CachedType | RawType, PresentType = CachedType | RawType,
Fallback = PresentType | null, Fallback = PresentType | null,
> = [State] extends ['cached'] > = [State] extends ['cached']
? CachedType ? CachedType
: [State] extends ['raw'] : [State] extends ['raw']
? RawType ? RawType
@@ -1496,7 +1501,7 @@ export type MessageCollectorOptionsParams<T extends MessageComponentTypeResolvab
export type MessageChannelCollectorOptionsParams< export type MessageChannelCollectorOptionsParams<
T extends MessageComponentTypeResolvable, T extends MessageComponentTypeResolvable,
Cached extends boolean = boolean, Cached extends boolean = boolean,
> = > =
| { | {
componentType?: T; componentType?: T;
} & MessageChannelComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>; } & MessageChannelComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>;
@@ -1504,7 +1509,7 @@ export type MessageChannelCollectorOptionsParams<
export type AwaitMessageCollectorOptionsParams< export type AwaitMessageCollectorOptionsParams<
T extends MessageComponentTypeResolvable, T extends MessageComponentTypeResolvable,
Cached extends boolean = boolean, Cached extends boolean = boolean,
> = > =
| { componentType?: T } & Pick< | { componentType?: T } & Pick<
InteractionCollectorOptions<MappedInteractionTypes<Cached>[T]>, InteractionCollectorOptions<MappedInteractionTypes<Cached>[T]>,
keyof AwaitMessageComponentOptions<any> keyof AwaitMessageComponentOptions<any>
@@ -1600,8 +1605,11 @@ export class Message<Cached extends boolean = boolean> extends Base {
public unpin(): Promise<Message>; public unpin(): Promise<Message>;
public inGuild(): this is Message<true> & this; public inGuild(): this is Message<true> & this;
// Added // Added
public clickButton(buttonID: String<MessageButton.customId>): Promise<pending> public clickButton(buttonID: String<MessageButton.customId>): Promise<pending>;
public selectMenu(menuID: String<MessageSelectMenu.customId> | Array<options>, options: Array<String>): Promise<pending> public selectMenu(
menuID: String<MessageSelectMenu.customId> | Array<options>,
options: Array<String>,
): Promise<pending>;
public contextMenu(botID: DiscordBotID, commandName: String<ApplicationCommand.name>): Promise; public contextMenu(botID: DiscordBotID, commandName: String<ApplicationCommand.name>): Promise;
} }
@@ -1717,7 +1725,7 @@ export class MessageComponentInteraction<Cached extends CacheType = CacheType> e
export class MessageContextMenuInteraction< export class MessageContextMenuInteraction<
Cached extends CacheType = CacheType, Cached extends CacheType = CacheType,
> extends ContextMenuInteraction<Cached> { > extends ContextMenuInteraction<Cached> {
public readonly targetMessage: NonNullable<CommandInteractionOption<Cached>['message']>; public readonly targetMessage: NonNullable<CommandInteractionOption<Cached>['message']>;
public inGuild(): this is MessageContextMenuInteraction<'present'>; public inGuild(): this is MessageContextMenuInteraction<'present'>;
public inCachedGuild(): this is MessageContextMenuInteraction<'cached'>; public inCachedGuild(): this is MessageContextMenuInteraction<'cached'>;
@@ -2973,7 +2981,7 @@ export class ApplicationCommandManager<
ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>, ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>,
PermissionsOptionsExtras = { guild: GuildResolvable }, PermissionsOptionsExtras = { guild: GuildResolvable },
PermissionsGuildType = null, PermissionsGuildType = null,
> extends CachedManager<Snowflake, ApplicationCommandScope, ApplicationCommandResolvable> { > extends CachedManager<Snowflake, ApplicationCommandScope, ApplicationCommandResolvable> {
protected constructor(client: Client, iterable?: Iterable<unknown>, user: User); protected constructor(client: Client, iterable?: Iterable<unknown>, user: User);
public permissions: ApplicationCommandPermissionsManager< public permissions: ApplicationCommandPermissionsManager<
{ command?: ApplicationCommandResolvable } & PermissionsOptionsExtras, { command?: ApplicationCommandResolvable } & PermissionsOptionsExtras,
@@ -3020,8 +3028,11 @@ export class ApplicationCommandPermissionsManager<
FullPermissionsOptions, FullPermissionsOptions,
GuildType, GuildType,
CommandIdType, CommandIdType,
> extends BaseManager { > extends BaseManager {
private constructor(manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand, user: User); private constructor(
manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand,
user: User,
);
private manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand; private manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand;
public client: Client; public client: Client;
@@ -3092,8 +3103,16 @@ export class ClientUserSettingManager {
public afkTimeout: number | null; // second public afkTimeout: number | null; // second
public stickerAnimationMode: stickerAnimationMode; public stickerAnimationMode: stickerAnimationMode;
public showEmojiReactions: boolean | null; public showEmojiReactions: boolean | null;
public customStatus: { text?: string, expires_at?: string | null, emoji_name?: string, emoji_id?: Snowflake | null, status?: PresenceStatusData } | object; public customStatus:
public addFriendFrom: { all?: boolean, mutual_friends?: boolean, mututal_guilds?: boolean } | object; | {
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 guildMetadata: Collection<Snowflake, object>;
public disableDMfromServer: Collection<Snowflake, boolean>; public disableDMfromServer: Collection<Snowflake, boolean>;
public fetch(): Promise<RawUserSettingsData>; public fetch(): Promise<RawUserSettingsData>;
@@ -3912,11 +3931,11 @@ export interface BaseFetchOptions {
} }
export interface guildSearchInteraction { export interface guildSearchInteraction {
type?: ApplicationCommandTypes, type?: ApplicationCommandTypes;
query?: String | void, query?: String | void;
limit?: Number, limit?: Number;
offset?: Number, offset?: Number;
botID?: Array<User.id>, botID?: Array<User.id>;
} }
export interface BaseMessageComponentOptions { export interface BaseMessageComponentOptions {
@@ -4089,7 +4108,7 @@ export interface ClientEvents extends BaseClientEvents {
members: Collection<Snowflake, GuildMember>, members: Collection<Snowflake, GuildMember>,
guild: Guild, guild: Guild,
data: {}, // see: https://luna.gitlab.io/discord-unofficial-docs/lazy_guilds.html data: {}, // see: https://luna.gitlab.io/discord-unofficial-docs/lazy_guilds.html
] ];
guildUpdate: [oldGuild: Guild, newGuild: Guild]; guildUpdate: [oldGuild: Guild, newGuild: Guild];
inviteCreate: [invite: Invite]; inviteCreate: [invite: Invite];
inviteDelete: [invite: Invite]; inviteDelete: [invite: Invite];
@@ -4127,9 +4146,9 @@ export interface ClientEvents extends BaseClientEvents {
webhookUpdate: [channel: TextChannel | NewsChannel]; webhookUpdate: [channel: TextChannel | NewsChannel];
/** @deprecated Use interactionCreate instead */ /** @deprecated Use interactionCreate instead */
interaction: [interaction: Interaction]; interaction: [interaction: Interaction];
interactionCreate: [interaction: Interaction | { nonce: Snowflake, id: Snowflake }]; interactionCreate: [interaction: Interaction | { nonce: Snowflake; id: Snowflake }];
interactionSuccess: [interaction: { nonce: Snowflake, id: Snowflake }]; interactionSuccess: [interaction: { nonce: Snowflake; id: Snowflake }];
interactionFailed: [interaction: { nonce: Snowflake, id: Snowflake }]; interactionFailed: [interaction: { nonce: Snowflake; id: Snowflake }];
shardDisconnect: [closeEvent: CloseEvent, shardId: number]; shardDisconnect: [closeEvent: CloseEvent, shardId: number];
shardError: [error: Error, shardId: number]; shardError: [error: Error, shardId: number];
shardReady: [shardId: number, unavailableGuilds: Set<Snowflake> | undefined]; shardReady: [shardId: number, unavailableGuilds: Set<Snowflake> | undefined];
@@ -4146,20 +4165,9 @@ export interface ClientEvents extends BaseClientEvents {
guildScheduledEventDelete: [guildScheduledEvent: GuildScheduledEvent]; guildScheduledEventDelete: [guildScheduledEvent: GuildScheduledEvent];
guildScheduledEventUserAdd: [guildScheduledEvent: GuildScheduledEvent, user: User]; guildScheduledEventUserAdd: [guildScheduledEvent: GuildScheduledEvent, user: User];
guildScheduledEventUserRemove: [guildScheduledEvent: GuildScheduledEvent, user: User]; guildScheduledEventUserRemove: [guildScheduledEvent: GuildScheduledEvent, user: User];
relationshipAdd: [ relationshipAdd: [id: Snowflake, type: RelationshipTypes, user: User];
id: Snowflake, relationshipRemove: [id: Snowflake, type: RelationshipTypes, user: User];
type: RelationshipType, unhandledPacket: [packet: { op: GatewayOpcodes | number; d?: any; s?: number; t?: string }, shard: WebSocketShard];
user: User,
];
relationshipRemove: [
id: Snowflake,
type: RelationshipType,
user: User,
];
unhandledPacket: [
packet: { op: GatewayOpcodes | number, d?: any, s?: number, t?: string },
shard: WebSocketShard,
];
} }
export interface ClientFetchInviteOptions { 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. */ /** @deprecated See [this issue](https://github.com/discord/discord-api-docs/issues/3690) for more information. */
APPLICATION_COMMAND_DELETE: 'applicationCommandDelete'; APPLICATION_COMMAND_DELETE: 'applicationCommandDelete';
/** @deprecated See [this issue](https://github.com/discord/discord-api-docs/issues/3690) for more information. */ /** @deprecated See [this issue](https://github.com/discord/discord-api-docs/issues/3690) for more information. */
APPLICATION_COMMAND_UPDATE: 'applicationCommandUpdate', APPLICATION_COMMAND_UPDATE: 'applicationCommandUpdate';
GUILD_CREATE: 'guildCreate', GUILD_CREATE: 'guildCreate';
GUILD_DELETE: 'guildDelete', GUILD_DELETE: 'guildDelete';
GUILD_UPDATE: 'guildUpdate', GUILD_UPDATE: 'guildUpdate';
GUILD_UNAVAILABLE: 'guildUnavailable', GUILD_UNAVAILABLE: 'guildUnavailable';
GUILD_MEMBER_ADD: 'guildMemberAdd', GUILD_MEMBER_ADD: 'guildMemberAdd';
GUILD_MEMBER_REMOVE: 'guildMemberRemove', GUILD_MEMBER_REMOVE: 'guildMemberRemove';
GUILD_MEMBER_UPDATE: 'guildMemberUpdate', GUILD_MEMBER_UPDATE: 'guildMemberUpdate';
GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable', GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable';
GUILD_MEMBERS_CHUNK: 'guildMembersChunk', GUILD_MEMBERS_CHUNK: 'guildMembersChunk';
GUILD_MEMBER_LIST_UPDATE: 'guildMemberListUpdate', GUILD_MEMBER_LIST_UPDATE: 'guildMemberListUpdate';
GUILD_INTEGRATIONS_UPDATE: 'guildIntegrationsUpdate', GUILD_INTEGRATIONS_UPDATE: 'guildIntegrationsUpdate';
GUILD_ROLE_CREATE: 'roleCreate', GUILD_ROLE_CREATE: 'roleCreate';
GUILD_ROLE_DELETE: 'roleDelete', GUILD_ROLE_DELETE: 'roleDelete';
INVITE_CREATE: 'inviteCreate', INVITE_CREATE: 'inviteCreate';
INVITE_DELETE: 'inviteDelete', INVITE_DELETE: 'inviteDelete';
GUILD_ROLE_UPDATE: 'roleUpdate', GUILD_ROLE_UPDATE: 'roleUpdate';
GUILD_EMOJI_CREATE: 'emojiCreate', GUILD_EMOJI_CREATE: 'emojiCreate';
GUILD_EMOJI_DELETE: 'emojiDelete', GUILD_EMOJI_DELETE: 'emojiDelete';
GUILD_EMOJI_UPDATE: 'emojiUpdate', GUILD_EMOJI_UPDATE: 'emojiUpdate';
GUILD_BAN_ADD: 'guildBanAdd', GUILD_BAN_ADD: 'guildBanAdd';
GUILD_BAN_REMOVE: 'guildBanRemove', GUILD_BAN_REMOVE: 'guildBanRemove';
CHANNEL_CREATE: 'channelCreate', CHANNEL_CREATE: 'channelCreate';
CHANNEL_DELETE: 'channelDelete', CHANNEL_DELETE: 'channelDelete';
CHANNEL_UPDATE: 'channelUpdate', CHANNEL_UPDATE: 'channelUpdate';
CHANNEL_PINS_UPDATE: 'channelPinsUpdate', CHANNEL_PINS_UPDATE: 'channelPinsUpdate';
MESSAGE_CREATE: 'messageCreate', MESSAGE_CREATE: 'messageCreate';
MESSAGE_DELETE: 'messageDelete', MESSAGE_DELETE: 'messageDelete';
MESSAGE_UPDATE: 'messageUpdate', MESSAGE_UPDATE: 'messageUpdate';
MESSAGE_BULK_DELETE: 'messageDeleteBulk', MESSAGE_BULK_DELETE: 'messageDeleteBulk';
MESSAGE_REACTION_ADD: 'messageReactionAdd', MESSAGE_REACTION_ADD: 'messageReactionAdd';
MESSAGE_REACTION_REMOVE: 'messageReactionRemove', MESSAGE_REACTION_REMOVE: 'messageReactionRemove';
MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll', MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll';
MESSAGE_REACTION_REMOVE_EMOJI: 'messageReactionRemoveEmoji', MESSAGE_REACTION_REMOVE_EMOJI: 'messageReactionRemoveEmoji';
THREAD_CREATE: 'threadCreate', THREAD_CREATE: 'threadCreate';
THREAD_DELETE: 'threadDelete', THREAD_DELETE: 'threadDelete';
THREAD_UPDATE: 'threadUpdate', THREAD_UPDATE: 'threadUpdate';
THREAD_LIST_SYNC: 'threadListSync', THREAD_LIST_SYNC: 'threadListSync';
THREAD_MEMBER_UPDATE: 'threadMemberUpdate', THREAD_MEMBER_UPDATE: 'threadMemberUpdate';
THREAD_MEMBERS_UPDATE: 'threadMembersUpdate', THREAD_MEMBERS_UPDATE: 'threadMembersUpdate';
USER_UPDATE: 'userUpdate', USER_UPDATE: 'userUpdate';
PRESENCE_UPDATE: 'presenceUpdate', PRESENCE_UPDATE: 'presenceUpdate';
VOICE_SERVER_UPDATE: 'voiceServerUpdate', VOICE_SERVER_UPDATE: 'voiceServerUpdate';
VOICE_STATE_UPDATE: 'voiceStateUpdate', VOICE_STATE_UPDATE: 'voiceStateUpdate';
TYPING_START: 'typingStart', TYPING_START: 'typingStart';
WEBHOOKS_UPDATE: 'webhookUpdate', WEBHOOKS_UPDATE: 'webhookUpdate';
INTERACTION_CREATE: 'interactionCreate', INTERACTION_CREATE: 'interactionCreate';
INTERACTION_SUCCESS: 'interactionSuccess', INTERACTION_SUCCESS: 'interactionSuccess';
INTERACTION_FAILED: 'interactionFailed', INTERACTION_FAILED: 'interactionFailed';
ERROR: 'error', ERROR: 'error';
WARN: 'warn', WARN: 'warn';
DEBUG: 'debug', DEBUG: 'debug';
CACHE_SWEEP: 'cacheSweep', CACHE_SWEEP: 'cacheSweep';
SHARD_DISCONNECT: 'shardDisconnect', SHARD_DISCONNECT: 'shardDisconnect';
SHARD_ERROR: 'shardError', SHARD_ERROR: 'shardError';
SHARD_RECONNECTING: 'shardReconnecting', SHARD_RECONNECTING: 'shardReconnecting';
SHARD_READY: 'shardReady', SHARD_READY: 'shardReady';
SHARD_RESUME: 'shardResume', SHARD_RESUME: 'shardResume';
INVALIDATED: 'invalidated', INVALIDATED: 'invalidated';
RAW: 'raw', RAW: 'raw';
STAGE_INSTANCE_CREATE: 'stageInstanceCreate', STAGE_INSTANCE_CREATE: 'stageInstanceCreate';
STAGE_INSTANCE_UPDATE: 'stageInstanceUpdate', STAGE_INSTANCE_UPDATE: 'stageInstanceUpdate';
STAGE_INSTANCE_DELETE: 'stageInstanceDelete', STAGE_INSTANCE_DELETE: 'stageInstanceDelete';
GUILD_STICKER_CREATE: 'stickerCreate', GUILD_STICKER_CREATE: 'stickerCreate';
GUILD_STICKER_DELETE: 'stickerDelete', GUILD_STICKER_DELETE: 'stickerDelete';
GUILD_STICKER_UPDATE: 'stickerUpdate', GUILD_STICKER_UPDATE: 'stickerUpdate';
GUILD_SCHEDULED_EVENT_CREATE: 'guildScheduledEventCreate', GUILD_SCHEDULED_EVENT_CREATE: 'guildScheduledEventCreate';
GUILD_SCHEDULED_EVENT_UPDATE: 'guildScheduledEventUpdate', GUILD_SCHEDULED_EVENT_UPDATE: 'guildScheduledEventUpdate';
GUILD_SCHEDULED_EVENT_DELETE: 'guildScheduledEventDelete', GUILD_SCHEDULED_EVENT_DELETE: 'guildScheduledEventDelete';
GUILD_SCHEDULED_EVENT_USER_ADD: 'guildScheduledEventUserAdd', GUILD_SCHEDULED_EVENT_USER_ADD: 'guildScheduledEventUserAdd';
GUILD_SCHEDULED_EVENT_USER_REMOVE: 'guildScheduledEventUserRemove', GUILD_SCHEDULED_EVENT_USER_REMOVE: 'guildScheduledEventUserRemove';
RELATIONSHIP_ADD: 'relationshipAdd', RELATIONSHIP_ADD: 'relationshipAdd';
RELATIONSHIP_REMOVE: 'relationshipRemove', RELATIONSHIP_REMOVE: 'relationshipRemove';
UNHANDLED_PACKET: 'unhandledPacket', UNHANDLED_PACKET: 'unhandledPacket';
} }
export interface ConstantsOpcodes { export interface ConstantsOpcodes {
@@ -4776,8 +4784,8 @@ export interface GuildAuditLogsEntryTargetField<TActionType extends GuildAuditLo
INVITE: Invite; INVITE: Invite;
MESSAGE: TActionType extends 'MESSAGE_BULK_DELETE' ? Guild | { id: Snowflake } : User; MESSAGE: TActionType extends 'MESSAGE_BULK_DELETE' ? Guild | { id: Snowflake } : User;
INTEGRATION: Integration; INTEGRATION: Integration;
CHANNEL: NonThreadGuildBasedChannel | { id: Snowflake;[x: string]: unknown }; CHANNEL: NonThreadGuildBasedChannel | { id: Snowflake; [x: string]: unknown };
THREAD: ThreadChannel | { id: Snowflake;[x: string]: unknown }; THREAD: ThreadChannel | { id: Snowflake; [x: string]: unknown };
STAGE_INSTANCE: StageInstance; STAGE_INSTANCE: StageInstance;
STICKER: Sticker; STICKER: Sticker;
GUILD_SCHEDULED_EVENT: GuildScheduledEvent; GUILD_SCHEDULED_EVENT: GuildScheduledEvent;
@@ -4963,7 +4971,7 @@ export interface GuildScheduledEventCreateOptions {
export interface GuildScheduledEventEditOptions< export interface GuildScheduledEventEditOptions<
S extends GuildScheduledEventStatus, S extends GuildScheduledEventStatus,
T extends GuildScheduledEventSetStatusArg<S>, T extends GuildScheduledEventSetStatusArg<S>,
> extends Omit<Partial<GuildScheduledEventCreateOptions>, 'channel'> { > extends Omit<Partial<GuildScheduledEventCreateOptions>, 'channel'> {
channel?: GuildVoiceChannelResolvable | null; channel?: GuildVoiceChannelResolvable | null;
status?: T | number; status?: T | number;
} }
@@ -4980,7 +4988,7 @@ export type GuildScheduledEventEntityType = keyof typeof GuildScheduledEventEnti
export type GuildScheduledEventManagerFetchResult< export type GuildScheduledEventManagerFetchResult<
T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions, T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions,
> = T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions > = T extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions
? GuildScheduledEvent ? GuildScheduledEvent
: Collection<Snowflake, GuildScheduledEvent>; : Collection<Snowflake, GuildScheduledEvent>;
@@ -5538,24 +5546,24 @@ export type Partialize<
N extends keyof T | null = null, N extends keyof T | null = null,
M extends keyof T | null = null, M extends keyof T | null = null,
E extends keyof T | '' = '', E extends keyof T | '' = '',
> = { > = {
readonly client: Client; readonly client: Client;
id: Snowflake; id: Snowflake;
partial: true; partial: true;
} & { } & {
[K in keyof Omit<T, 'client' | 'id' | 'partial' | E>]: K extends N ? null : K extends M ? T[K] | null : T[K]; [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'> { export interface PartialDMChannel extends Partialize<DMChannel, null, null, 'lastMessageId'> {
lastMessageId: undefined; lastMessageId: undefined;
} }
export interface PartialGuildMember extends Partialize<GuildMember, 'joinedAt' | 'joinedTimestamp'> { } export interface PartialGuildMember extends Partialize<GuildMember, 'joinedAt' | 'joinedTimestamp'> {}
export interface PartialMessage 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 { export interface PartialOverwriteData {
id: Snowflake | number; 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 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'; export type PresenceStatusData = ClientPresenceStatus | 'invisible';
@@ -5595,9 +5603,9 @@ export interface RawUserSettingsData {
allow_accessibility_detection?: boolean; allow_accessibility_detection?: boolean;
animate_emoji?: boolean; animate_emoji?: boolean;
animate_stickers?: number; animate_stickers?: number;
contact_sync_enabled:? boolean; contact_sync_enabled: ?boolean;
convert_emoticons?: 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; default_guilds_restricted?: boolean;
detect_platform_accounts?: boolean; detect_platform_accounts?: boolean;
developer_mode?: boolean; developer_mode?: boolean;
@@ -5605,10 +5613,10 @@ export interface RawUserSettingsData {
enable_tts_command?: boolean; enable_tts_command?: boolean;
explicit_content_filter?: DMScanLevel; explicit_content_filter?: DMScanLevel;
friend_discovery_flags?: number; 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; gif_auto_play?: boolean;
guild_folders?: Array<{ id?: Snowflake, guild_ids?: Array<Snowflake>, name?: string }>; guild_folders?: Array<{ id?: Snowflake; guild_ids?: Array<Snowflake>; name?: string }>;
guild_positions?: Array; guild_positions?: Array<T>;
inline_attachment_media?: boolean; inline_attachment_media?: boolean;
inline_embed_media?: boolean; inline_embed_media?: boolean;
locale?: string; locale?: string;