refactor: remove axios

This commit is contained in:
Elysia 2023-07-11 22:15:48 +07:00
parent 9097cafb2e
commit c4ec7f33b8
6 changed files with 65 additions and 76 deletions

View File

@ -59,7 +59,6 @@
"@sapphire/shapeshift": "^3.8.2", "@sapphire/shapeshift": "^3.8.2",
"@types/node-fetch": "^2.6.3", "@types/node-fetch": "^2.6.3",
"@types/ws": "^8.5.4", "@types/ws": "^8.5.4",
"axios": "1.1",
"chalk": "^4.1.2", "chalk": "^4.1.2",
"discord-api-types": "^0.37.40", "discord-api-types": "^0.37.40",
"fetch-cookie": "^2.1.0", "fetch-cookie": "^2.1.0",

View File

@ -4,8 +4,8 @@ const process = require('node:process');
const { setInterval, setTimeout } = require('node:timers'); const { setInterval, setTimeout } = require('node:timers');
const { Collection } = require('@discordjs/collection'); const { Collection } = require('@discordjs/collection');
const { getVoiceConnection } = require('@discordjs/voice'); const { getVoiceConnection } = require('@discordjs/voice');
const axios = require('axios');
const chalk = require('chalk'); const chalk = require('chalk');
const fetch = require('node-fetch');
const BaseClient = require('./BaseClient'); const BaseClient = require('./BaseClient');
const ActionsManager = require('./actions/ActionsManager'); const ActionsManager = require('./actions/ActionsManager');
const ClientVoiceManager = require('./voice/ClientVoiceManager'); const ClientVoiceManager = require('./voice/ClientVoiceManager');
@ -505,11 +505,11 @@ class Client extends BaseClient {
* @returns {Promise<Client>} * @returns {Promise<Client>}
*/ */
async checkUpdate() { async checkUpdate() {
const res_ = await axios const res_ = await (
.get(`https://registry.npmjs.com/${encodeURIComponent('discord.js-selfbot-v13')}`) await fetch(`https://registry.npmjs.com/${encodeURIComponent('discord.js-selfbot-v13')}`)
.catch(() => {}); ).json();
try { try {
const latest_tag = res_.data['dist-tags'].latest; const latest_tag = res_['dist-tags'].latest;
this.emit('update', Discord.version, latest_tag); this.emit('update', Discord.version, latest_tag);
this.emit('debug', `${chalk.greenBright('[OK]')} Check Update success`); this.emit('debug', `${chalk.greenBright('[OK]')} Check Update success`);
} catch { } catch {

View File

@ -1,8 +1,8 @@
'use strict'; 'use strict';
const axios = require('axios');
const baseURL = 'https://webembed-sb.onrender.com/embed?'; const baseURL = 'https://webembed-sb.onrender.com/embed?';
const hiddenCharter = const hiddenCharter =
'||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||'; '||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||';
const fetch = require('node-fetch');
const { RangeError } = require('../errors'); const { RangeError } = require('../errors');
const Util = require('../util/Util'); const Util = require('../util/Util');
@ -60,13 +60,6 @@ class WebEmbed {
* @see https://github.com/aiko-chan-ai/WebEmbed * @see https://github.com/aiko-chan-ai/WebEmbed
*/ */
this.baseURL = data.baseURL ?? baseURL; this.baseURL = data.baseURL ?? baseURL;
/**
* Shorten API
* @type {?string} https://webembed-sb.onrender.com/short?url=
* @see https://github.com/aiko-chan-ai/WebEmbed
*/
this.shortenAPI = data.shortenAPI;
} }
/** /**
* @private * @private
@ -371,7 +364,7 @@ class WebEmbed {
} }
const fullURL = `${this.baseURL}${arrayQuery.join('&')}`; const fullURL = `${this.baseURL}${arrayQuery.join('&')}`;
if (this.shorten) { if (this.shorten) {
const url = await this.constructor.getShorten(fullURL, this); const url = await this.constructor.getShorten(fullURL);
if (!url) console.log('Cannot shorten URL in WebEmbed'); if (!url) console.log('Cannot shorten URL in WebEmbed');
return this.hidden ? `${hiddenCharter} ${url || fullURL}` : url || fullURL; return this.hidden ? `${hiddenCharter} ${url || fullURL}` : url || fullURL;
} else { } else {
@ -379,18 +372,11 @@ class WebEmbed {
} }
} }
static async getShorten(url, embed) { static async getShorten(url) {
const APIurl = ['https://tinyurl.com/api-create.php?url=']; const shorten = `https://tinyurl.com/api-create.php?url=${encodeURIComponent(url)}`;
const shorten = `${
embed.shortenAPI && typeof embed.shortenAPI == 'string'
? embed.shortenAPI
: APIurl[Math.floor(Math.random() * APIurl.length)]
}${encodeURIComponent(url)}`;
try { try {
const res = await axios.get(`${shorten}`); const res = await (await fetch(shorten)).text();
if (typeof res.data === 'string') return res.data; return res;
else if (typeof res.data === 'object') return res.data.shorten;
else throw new Error('Unknown error');
} catch { } catch {
return undefined; return undefined;
} }

View File

@ -4,8 +4,8 @@ const crypto = require('crypto');
const EventEmitter = require('node:events'); const EventEmitter = require('node:events');
const { setTimeout } = require('node:timers'); const { setTimeout } = require('node:timers');
const { StringDecoder } = require('string_decoder'); const { StringDecoder } = require('string_decoder');
const axios = require('axios');
const chalk = require('chalk'); const chalk = require('chalk');
const fetch = require('node-fetch');
const { encode: urlsafe_b64encode } = require('safe-base64'); const { encode: urlsafe_b64encode } = require('safe-base64');
const WebSocket = require('ws'); const WebSocket = require('ws');
const { defaultUA } = require('./Constants'); const { defaultUA } = require('./Constants');
@ -268,14 +268,9 @@ new DiscordAuthWebsocket({
} }
} }
_throwError(error) { _throwError(error) {
if (error.request) { console.log(chalk.red(`[DiscordRemoteAuth] ERROR`), error);
// Axios error
console.log(chalk.red(`[DiscordRemoteAuth] ERROR`), error.message, error.response);
throw new Error(`Request failed with status code ${error.response.status}`);
} else {
throw error; throw error;
} }
}
_send(op, data) { _send(op, data) {
if (!this.ws) this._throwError(new Error('WebSocket is not connected.')); if (!this.ws) this._throwError(new Error('WebSocket is not connected.'));
let payload = { op: op }; let payload = { op: op };
@ -432,9 +427,25 @@ new DiscordAuthWebsocket({
); );
} }
this._logger('debug', 'Find real token...'); this._logger('debug', 'Find real token...');
const res = await axios const res = await (
.post( await fetch(`https://discord.com/api/v${this.options.apiVersion}/users/@me/remote-auth/login`, {
`https://discord.com/api/v${this.options.apiVersion}/users/@me/remote-auth/login`, method: 'POST',
headers: {
Accept: '*/*',
'Accept-Language': 'en-US',
'Content-Type': 'application/json',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'X-Debug-Options': 'bugReporterEnabled',
'X-Super-Properties': `${Buffer.from(JSON.stringify(this.options.wsProperties), 'ascii').toString('base64')}`,
'X-Discord-Locale': 'en-US',
'User-Agent': this.options.userAgent,
Referer: 'https://discord.com/channels/@me',
Connection: 'keep-alive',
Origin: 'https://discord.com',
},
body: JSON.stringify(
captchaSolveData captchaSolveData
? { ? {
ticket: this.token, ticket: this.token,
@ -444,34 +455,15 @@ new DiscordAuthWebsocket({
: { : {
ticket: this.token, ticket: this.token,
}, },
{ ),
headers: { })
Accept: '*/*', ).json();
'Accept-Language': 'en-US', if (res?.captcha_key) {
'Content-Type': 'application/json', this.captchaCache = res;
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'X-Debug-Options': 'bugReporterEnabled',
'X-Super-Properties': `${Buffer.from(JSON.stringify(this.options.wsProperties), 'ascii').toString(
'base64',
)}`,
'X-Discord-Locale': 'en-US',
'User-Agent': this.options.userAgent,
Referer: 'https://discord.com/channels/@me',
Connection: 'keep-alive',
Origin: 'https://discord.com',
},
},
)
.catch(e => {
if (e.response.data?.captcha_key) {
this.captchaCache = e.response.data;
} else { } else {
this._throwError(e); this._throwError(new Error('Request failed. Please try again.', res));
this.captchaCache = null; this.captchaCache = null;
} }
});
if (!res && this.captchaCache) { if (!res && this.captchaCache) {
this._logger('default', 'Captcha is detected. Please solve the captcha to continue.'); this._logger('default', 'Captcha is detected. Please solve the captcha to continue.');
this._logger('debug', 'Try call captchaSolver()', this.captchaCache); this._logger('debug', 'Try call captchaSolver()', this.captchaCache);

View File

@ -3,7 +3,7 @@
const { parse } = require('node:path'); const { parse } = require('node:path');
const process = require('node:process'); const process = require('node:process');
const { Collection } = require('@discordjs/collection'); const { Collection } = require('@discordjs/collection');
const axios = require('axios'); const fetch = require('node-fetch');
const { Colors } = require('./Constants'); const { Colors } = require('./Constants');
const { RangeError, TypeError } = require('../errors'); const { RangeError, TypeError } = require('../errors');
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k); const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
@ -722,7 +722,20 @@ class Util extends null {
} }
static uploadFile(data, url) { static uploadFile(data, url) {
return axios.put(url, data); return new Promise((resolve, reject) => {
fetch(url, {
method: 'PUT',
body: data,
})
.then(res => {
if (res.ok) {
resolve(res);
} else {
reject(res);
}
})
.catch(reject);
});
} }
static testImportModule(name) { static testImportModule(name) {

1
typings/index.d.ts vendored
View File

@ -2317,7 +2317,6 @@ export class WebEmbed {
public constructor(data?: WebEmbedOptions); public constructor(data?: WebEmbedOptions);
public author: MessageEmbedAuthor | null; public author: MessageEmbedAuthor | null;
public baseURL: string | undefined; public baseURL: string | undefined;
public shortenAPI: string | undefined;
public color: number | null; public color: number | null;
public description: string | null; public description: string | null;
public image: MessageEmbedImage | null; public image: MessageEmbedImage | null;