Skip to content
This repository has been archived by the owner on Nov 22, 2023. It is now read-only.

Commit

Permalink
Remove node-fetch in favor of axios
Browse files Browse the repository at this point in the history
node-fetch/node-fetch#1141 and node-fetch/node-fetch#810 should be proof these lads are high on acids
  • Loading branch information
ImRodry committed Sep 1, 2021
1 parent 18bd384 commit 6ce33eb
Show file tree
Hide file tree
Showing 8 changed files with 147 additions and 124 deletions.
47 changes: 0 additions & 47 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions package.json
Expand Up @@ -20,7 +20,6 @@
"countryjs": "^1.8.0",
"discord.js": "^13.2.0-dev.1630325279.581921f",
"mongodb": "^4.1.1",
"node-fetch": "^2.6.1",
"puppeteer": "^10.2.0",
"source-map-support": "^0.5.19",
"typescript": "^4.4.2",
Expand All @@ -32,7 +31,6 @@
},
"devDependencies": {
"@types/countryjs": "^1.8.1",
"@types/node-fetch": "^2.5.12",
"@types/uuid": "^8.3.1",
"dotenv": "^10.0.0",
"rimraf": "^3.0.2"
Expand Down
105 changes: 66 additions & 39 deletions src/commands/Utility/hypixelstats.ts
@@ -1,5 +1,5 @@
import Discord from "discord.js"
import fetch, { FetchError } from "node-fetch"
import axios from "axios"
import { db, DbUser } from "../../lib/dbclient"
import { Command, client, GetStringFunction } from "../../index"
import { fetchSettings, getUUID, updateRoles } from "../../lib/util"
Expand Down Expand Up @@ -63,9 +63,9 @@ const command: Command = {

await interaction.deferReply()
// make a request to the slothpixel api (hypixel api but we dont need an api key)
const playerJson = await fetch(`https://api.slothpixel.me/api/players/${uuid}`, fetchSettings).then(res => res.json())
const playerJson = await axios.get<PlayerJson>(`https://api.slothpixel.me/api/players/${uuid}`, fetchSettings).then(res => res.data)
.catch(e => {
if (e instanceof FetchError) {
if (e.code === "ECONNABORTED") { //this means the request timed out
console.error("Slothpixel is down, sending error.")
throw "apiError"
} else throw e
Expand All @@ -90,13 +90,17 @@ const command: Command = {
color = parseColorCode(playerJson.rank_formatted)
rank = playerJson.rank_formatted.replace(/&([0-9]|[a-z])/g, "")
}
const username = playerJson.username.replaceAll("_", "\\_") // change the nickname in a way that doesn't accidentally mess up the formatting in the embed

// change the nickname in a way that doesn't accidentally mess up the formatting in the embed
const username = playerJson.username.replaceAll("_", "\\_")

//Update user's roles if they're verified
const uuidDb = await db.collection<DbUser>("users").findOne({ uuid: playerJson.uuid })
if (uuidDb) updateRoles(client.guilds.cache.get("549503328472530974")!.members.cache.get(uuidDb.id)!, playerJson)

const stats = async () => {
const skinRender = `https://mc-heads.net/body/${playerJson.uuid}/left`

const stats = () => {
//Define each value
let online: string
if (playerJson.online) online = getString("online")
Expand All @@ -106,15 +110,13 @@ const command: Command = {
if (!playerJson.last_game) last_seen = getString("lastGameHidden")
else last_seen = getString("lastSeen", { game: playerJson.last_game.replace(/([A-Z]+)/g, " $1").trim() })

let lastLoginSelector: string
if (playerJson.online) lastLoginSelector = "last_login"
else lastLoginSelector = "last_logout"
const lastLoginLogout = playerJson.online ? playerJson.last_login : playerJson.last_logout

let locale: string = getString("region.dateLocale", "global")
if (locale.startsWith("crwdns")) locale = getString("region.dateLocale", "global", "en")

let lastLogin: string
if (playerJson[lastLoginSelector]) lastLogin = `<t:${Math.round(new Date(playerJson[lastLoginSelector]).getTime() / 1000)}:F>`
if (lastLoginLogout) lastLogin = `<t:${Math.round(new Date(lastLoginLogout).getTime() / 1000)}:F>`
else lastLogin = getString("lastLoginHidden")

let firstLogin: string
Expand All @@ -125,22 +127,22 @@ const command: Command = {
.setColor(color)
.setAuthor(getString("moduleName"))
.setTitle(`${rank} ${username}`)
.setThumbnail(`https://mc-heads.net/body/${playerJson.uuid}/left`)
.setThumbnail(skinRender)
.setDescription(`${getString("description", { username: username, link: `(https://api.slothpixel.me/api/players/${uuid})` })}\n${uuidDb ? `${getString("userVerified", { user: `<@!${uuidDb.id}>` })}\n` : ""}${getString("updateNotice")}\n${getString("otherStats")}`)
.addFields(
{ name: getString("networkLevel"), value: Math.abs(playerJson.level).toLocaleString(locale), inline: true },
{ name: getString("ap"), value: playerJson.achievement_points.toLocaleString(locale), inline: true },
{ name: getString("first_login"), value: firstLogin, inline: true },

{ name: getString("language"), value: getString(playerJson.language), inline: true },
{ name: online, value: last_seen, inline: true },
{ name: getString(lastLoginSelector), value: lastLogin, inline: true }

{ name: getString(playerJson.online ? "last_login" : "last_logout"), value: lastLogin, inline: true }
)
.setFooter(`${executedBy} | ${credits}`, interaction.user.displayAvatarURL({ format: "png", dynamic: true }))
return statsEmbed
}

const social = async () => {
const social = () => {
const socialMedia = playerJson.links

let twitter: string
Expand Down Expand Up @@ -172,7 +174,7 @@ const command: Command = {
if (socialMedia.DISCORD) {
if (!socialMedia.DISCORD.includes("discord.gg")) discord = socialMedia.DISCORD.replaceAll("_", "\\_")
else {
await interaction.client.fetchInvite(socialMedia.DISCORD)
interaction.client.fetchInvite(socialMedia.DISCORD)
.then(invite => {
if (allowedGuildIDs.includes(invite.guild?.id!)) discord = `[${getString("link")}](${invite.url})`
else {
Expand All @@ -196,7 +198,7 @@ const command: Command = {
.setColor(color)
.setAuthor(getString("moduleName"))
.setTitle(`${rank} ${username}`)
.setThumbnail(`https://mc-heads.net/body/${playerJson.uuid}/left`)
.setThumbnail(skinRender)
.setDescription(`${getString("socialMedia", { username: username, link: `(https://api.slothpixel.me/api/players/${uuid})` })}\n${uuidDb ? `${getString("userVerified", { user: `<@!${uuidDb.id}>` })}\n` : ""}${getString("updateNotice")}\n${getString("otherStats")}`)
.addFields(
{ name: "Twitter", value: twitter, inline: true },
Expand Down Expand Up @@ -242,8 +244,8 @@ const command: Command = {
content: getString("pagination.notYours", { command: `/${this.name}` }, "global", userDb.lang),
ephemeral: true
})
else if (option === "stats") embed = await stats()
else if (option === "social") embed = await social()
else if (option === "stats") embed = stats()
else if (option === "social") embed = social()
optionsSelect.options.forEach(o => o.default = option === o.value)
await menuInteraction.update({ embeds: [embed], components: [{ type: "ACTION_ROW", components: [optionsSelect] }] })
})
Expand All @@ -255,29 +257,54 @@ const command: Command = {
}
}

function parseColorCode(rank: string): Discord.HexColorString {
const colorCode: string = rank.substring(1, 2)
const colorsJson: {
[key: string]: Discord.HexColorString
} = {
"0": "#000000",
"1": "#0000AA",
"2": "#00AA00",
"3": "#00AAAA",
"4": "#AA0000",
"5": "#AA00AA",
"6": "#FFAA00",
"7": "#AAAAAA",
"8": "#555555",
"9": "#5555FF",
a: "#55FF55",
b: "#55FFFF",
c: "#FF5555",
d: "#FF55FF",
e: "#FFFF55",
f: "#FFFFFF"
}
function parseColorCode(color: string): Discord.HexColorString {
const colorCode: string = color.substring(1, 2).toLowerCase(),
colorsJson: {
[key: string]: Discord.HexColorString
} = {
"0": "#000000",
"1": "#0000AA",
"2": "#00AA00",
"3": "#00AAAA",
"4": "#AA0000",
"5": "#AA00AA",
"6": "#FFAA00",
"7": "#AAAAAA",
"8": "#555555",
"9": "#5555FF",
a: "#55FF55",
b: "#55FFFF",
c: "#FF5555",
d: "#FF55FF",
e: "#FFFF55",
f: "#FFFFFF"
}
return colorsJson[colorCode]
}

export default command

export interface PlayerJson {
error?: string
uuid: string
username: string
online: boolean
rank: string
rank_formatted: string
prefix: string | null
level: number
achievement_points: number
first_login: number
last_login: number | null
last_logout: number | null
last_game: string | null
language: string
links: {
TWITTER: string | null
YOUTUBE: string | null
INSTAGRAM: string | null
TWITCH: string | null
DISCORD: string | null
HYPIXEL: string | null
}
}
7 changes: 4 additions & 3 deletions src/commands/Utility/hypixelverify.ts
@@ -1,9 +1,10 @@
import Discord from "discord.js"
import { successColor, errorColor } from "../../config.json"
import fetch, { FetchError } from "node-fetch"
import axios from "axios"
import { db, DbUser } from "../../lib/dbclient"
import { fetchSettings, getUUID, updateRoles } from "../../lib/util"
import type { Command, GetStringFunction } from "../../index"
import { PlayerJson } from "./hypixelstats"

const command: Command = {
name: "hypixelverify",
Expand Down Expand Up @@ -31,9 +32,9 @@ const command: Command = {

await interaction.deferReply()
// make a response to the slothpixel api (hypixel api but we dont need an api key)
const json = await fetch(`https://api.slothpixel.me/api/players/${uuid}`, fetchSettings).then(res => res.json())
const json = await axios.get<PlayerJson>(`https://api.slothpixel.me/api/players/${uuid}`, fetchSettings).then(res => res.data)
.catch(e => {
if (e instanceof FetchError) {
if (e.code === "ECONNABORTED") { //this means the request timed out
console.error("slothpixel is down, sending error.")
throw "apiError"
} else throw e
Expand Down

0 comments on commit 6ce33eb

Please sign in to comment.