Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix some NaN, sharding, presence errors and everything #1280

Closed
wants to merge 13 commits into from
12 changes: 6 additions & 6 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"rss-parser": "^3.7.0",
"runeterra": "0.0.6",
"samp-query": "^0.1.5",
"sinesp-api": "^2.0.2",
"sinesp-api": "^3.0.0",
"snoowrap": "^1.21.0",
"splitargs": "0.0.7",
"steamapi": "^2.0.7",
Expand Down
10 changes: 10 additions & 0 deletions src/apis/Covid19.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ module.exports = class Covid19 extends APIWrapper {
return this.request('countries', country)
}

async getCountryVaccine (country) {
const vaccineData = await this.request('vaccine/coverage/countries', `${country}?lastdays=1`)
return vaccineData.data
}

async getWorldwideVaccine () {
const vaccineData = await this.request('vaccine/coverage', `?lastdays=1`)
return vaccineData.data
}

async getWorldwide () {
return this.request('all')
}
Expand Down
2 changes: 1 addition & 1 deletion src/apis/GoogleSearch.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { APIWrapper } = require('../')
const fetch = require('node-fetch')

module.exports = class CrowdinAPI extends APIWrapper {
module.exports = class GoogleSearchAPI extends APIWrapper {
constructor () {
super({
name: 'gsearch',
Expand Down
6 changes: 2 additions & 4 deletions src/commands/bot/botinfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ module.exports = class BotInfo extends Command {

async run ({ channel, author, t, language }) {
const uptime = moment.duration(process.uptime() * 1000).format('d[d] h[h] m[m] s[s]')
const shardGuildCounts = await this.client.shard.fetchClientValues('guilds.cache.size')
const totalGuildCount = shardGuildCounts.reduce((total, current) => total + current)
const shardUserCounts = await this.client.shard.fetchClientValues('users.cache.size')
const totalUserCount = shardUserCounts.reduce((total, current) => total + current)
const totalGuildCount = await this.client.shard.broadcastEval('this.guilds.cache.size').then((res) => res.reduce((a, b) => a + b, 0))
const totalUserCount = await this.client.shard.broadcastEval('this.guilds.cache.reduce((a, g) => a + g.memberCount, 0)').then((res) => res.reduce((a, b) => a + b, 0))
channel.send(
new SwitchbladeEmbed(author)
.setAuthor(this.client.user.username, this.client.user.displayAvatarURL({ format: 'png' }))
Expand Down
1 change: 1 addition & 0 deletions src/commands/government/searchplate.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ module.exports = class searchPlate extends Command {
async run ({ t, author, channel, message }, plt) {
channel.startTyping()
const plate = await this.client.apis.sinesp.searchPlate(plt)
console.log(plate)
try {
// vv i know that's actually hardcoded :hahaa:
const carpic = await this.client.apis.gsearch.searchImage(`${plate.modelo} ${plate.anoModelo} a venda&imgSize=medium`)
Expand Down
2 changes: 2 additions & 0 deletions src/commands/misc/covid/countries.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module.exports = class CovidCountries extends Command {
moment.locale(language)
try {
const { data } = await this.client.apis.covid.getCountry(country)
const vaccineData = await this.client.apis.covid.getCountryVaccine(country)
channel.send(
new SwitchbladeEmbed(author)
.setThumbnail(data.countryInfo.flag)
Expand All @@ -31,6 +32,7 @@ module.exports = class CovidCountries extends Command {
.addField(t('commands:covid.deaths'), MiscUtils.formatNumber(data.deaths, language), true)
.addField(t('commands:covid.recovered'), MiscUtils.formatNumber(data.recovered, language), true)
.addField(t('commands:covid.oneCasePerPeople'), MiscUtils.formatNumber(data.oneCasePerPeople, language), true)
.addField(t('commands:covid.vaccinated'), MiscUtils.formatNumber(vaccineData.timeline[Object.keys(vaccineData.timeline)[0]], language), true)
.setFooter(t('commands:covid.updatedAt'))
.setTimestamp(data.updated)
)
Expand Down
3 changes: 3 additions & 0 deletions src/commands/misc/covid/worldwide.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ module.exports = class CovidWorldwide extends Command {
moment.locale(language)
try {
const { data } = await this.client.apis.covid.getWorldwide()
const vaccineData = await this.client.apis.covid.getWorldwideVaccine()
channel.send(
new SwitchbladeEmbed(author)
.setColor(Constants.GENERIC_RED_COLOR)
Expand All @@ -26,6 +27,8 @@ module.exports = class CovidWorldwide extends Command {
.addField(t('commands:covid.recovered'), MiscUtils.formatNumber(data.recovered, language), true)
.addField(t('commands:covid.casesPerOneMillion'), MiscUtils.formatNumber(data.casesPerOneMillion, language), true)
.addField(t('commands:covid.subcommands.worldwide.affectedCountries'), MiscUtils.formatNumber(data.affectedCountries, language), true)
.addField(t('commands:covid.vaccinated'), MiscUtils.formatNumber(vaccineData[Object.keys(vaccineData)[0]], language), true)

.setFooter(t('commands:covid.updatedAt'))
.setTimestamp(data.updated)
)
Expand Down
2 changes: 1 addition & 1 deletion src/commands/moderation/move.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module.exports = class Move extends Command {
type: 'messageLink',
sameGuildOnly: true,
forceExists: true,
linkChannelUserPermission: ['VIEW_MESSAGES'],
linkChannelUserPermission: ['VIEW_CHANNEL'],
linkChannelBotPermission: ['MANAGE_MESSAGES'],
missingError: 'commands:move.missingMessageLink'
}, {
Expand Down
30 changes: 18 additions & 12 deletions src/commands/utility/userinfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,29 @@ module.exports = class UserInfo extends Command {
full: true,
required: false,
acceptBot: true,
acceptSelf: true
acceptSelf: true,
acceptPartial: true
}]
}, client)
}

run ({ t, guild, member: author, channel, language }, member = author) {
async run ({ t, guild, member: author, channel, language }, member = author) {
moment.locale(language)
channel.send(
new SwitchbladeEmbed()
.setTitle(member.displayName)
.setThumbnail(member.user.displayAvatarURL({ format: 'png' }))
.addField(t('commands:userinfo.tag'), member.user.tag, true)
.addField(t('commands:userinfo.id'), member.id, true)
.addField(t('commands:userinfo.status'), t(`commands:userinfo.${member.presence.status}`, { status: this.getEmoji(member.presence.status) }), true)
.addField(t('commands:userinfo.createdAt'), `${moment(member.user.createdTimestamp).format('LLL')}\n(${moment(member.user.createdTimestamp).fromNow()})`, true)
.addField(t('commands:userinfo.joinedAt'), `${moment(member.joinedTimestamp).format('LLL')}\n(${moment(member.joinedTimestamp).fromNow()})`, true)
const isUserPartial = !member.joinedTimestamp
const createdAt = isUserPartial ? member.createdAt : member.user.createdTimestamp
const embed = new SwitchbladeEmbed()
.setTitle(isUserPartial ? member.username : member.displayName)
.setThumbnail((isUserPartial ? member : member.user).displayAvatarURL({ format: 'png' }))
.addField(t('commands:userinfo.tag'), isUserPartial ? member.tag : member.user.tag, true)
.addField(t('commands:userinfo.id'), member.id, true)
// .addField(t('commands:userinfo.status'), t(`commands:userinfo.${member.presence.status}`, { status: this.getEmoji(member.presence.status) }), true)
.addField(t('commands:userinfo.createdAt'), `${moment(createdAt).format('LLL')}\n(${moment(createdAt).fromNow()})`, true)

if (!isUserPartial) {
embed.addField(t('commands:userinfo.joinedAt'), `${moment(member.joinedTimestamp).format('LLL')}\n(${moment(member.joinedTimestamp).fromNow()})`, true)
.setFooter(`${author.user.tag} - ${t('commands:userinfo.memberNumber', { count: MiscUtils.formatNumber(guild.members.cache.sort((a, b) => a.joinedTimestamp - b.joinedTimestamp).array().indexOf(member) + 1, language) })}`)
)
}

channel.send(embed)
}
}
10 changes: 6 additions & 4 deletions src/http/api/contributors.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ module.exports = class Contributors extends Route {

register (app) {
const router = Router()

// what the fuck is happening here
// TODO: everything, it sucks
router.get('/', async (req, res) => {
const guild = this.client.guilds.cache.get(process.env.BOT_GUILD)
const roles = guild.roles
const roles = guild.roles.cache
console.log(roles)
almeidx marked this conversation as resolved.
Show resolved Hide resolved
const members = guild.members

const ignoreUsers = process.env.IGNORE_USERS ? process.env.IGNORE_USERS.split(',') : []
Expand All @@ -28,8 +30,8 @@ module.exports = class Contributors extends Route {
members: members.map(member => {
if (member.roles.has(role.id) && !member.user.bot && !alreadyFound.includes(member.id) && !ignoreUsers.includes(member.id)) {
alreadyFound.push(member.id)
const { id, user: { username, discriminator, avatar, presence: { status } } } = member
return { username, discriminator, id, avatar, status }
const { id, user: { username, discriminator, avatar } } = member
return { username, discriminator, id, avatar }
}
}).filter(u => u)
}
Expand Down
22 changes: 13 additions & 9 deletions src/listeners/MainListener.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ module.exports = class MainListener extends EventListener {
this.user.setActivity(`@${this.user.username} help`, { type: 'PLAYING' })

async function updatePresence (client) {
const shardGuildCounts = await client.shard.fetchClientValues('guilds.cache.size')
const totalGuildCount = shardGuildCounts.reduce((total, current) => total + current)
const shardUserCounts = await client.shard.fetchClientValues('users.cache.size')
const totalUserCount = shardUserCounts.reduce((total, current) => total + current)
const [totalGuildCount, totalUserCount] = await Promise.all([
client.shard.fetchClientValues('guilds.cache.size'),
client.shard.broadcastEval('this.guilds.cache.reduce((a, g) => a + g.memberCount, 0)')
])

const presences = [
{
Expand Down Expand Up @@ -64,13 +64,17 @@ module.exports = class MainListener extends EventListener {
}

// TODO: Make stat posters modular
function postStats (client) {
async function postStats (client) {
const [totalGuilds, totalUsers] = await Promise.all([
client.shard.fetchClientValues('guilds.cache.size'),
client.shard.broadcastEval('this.guilds.cache.reduce((a, g) => a + g.memberCount, 0)')
])
// bots.discord.pw
if (process.env.DISCORDBOTSPW_TOKEN) {
fetch(`https://bots.discord.pw/api/bots/${client.user.id}/stats`, {
method: 'POST',
headers: { Authorization: process.env.DISCORDBOTSPW_TOKEN },
body: { server_count: client.guilds.size }
body: { server_count: totalGuilds }
})
.then(() => client.log('Posted statistics successfully', { color: 'green', tags: ['bots.discord.pw'] }))
.catch(() => client.log('Failed to post statistics', { color: 'red', tags: ['bots.discord.pw'] }))
Expand All @@ -81,7 +85,7 @@ module.exports = class MainListener extends EventListener {
fetch(`https://top.gg/api/bots/${client.user.id}/stats`, {
method: 'POST',
headers: { Authorization: process.env.DBL_TOKEN },
body: { server_count: client.guilds.size }
body: { server_count: totalGuilds }
})
.then(() => client.log('Posted statistics successfully', { color: 'green', tags: ['discordbots.org'] }))
.catch(() => client.log('Failed to post statistics', { color: 'red', tags: ['discordbots.org'] }))
Expand All @@ -92,7 +96,7 @@ module.exports = class MainListener extends EventListener {
fetch(`https://botsfordiscord.com/api/bots/${client.user.id}`, {
method: 'POST',
headers: { Authorization: process.env.BOTSFORDISCORD_TOKEN },
body: { server_count: client.guilds.size }
body: { server_count: totalGuilds }
})
.then(() => client.log('Posted statistics successfully', { color: 'green', tags: ['botsfordiscord.com'] }))
.catch(() => client.log('Failed to post statistics', { color: 'red', tags: ['botsfordiscord.com'] }))
Expand All @@ -102,7 +106,7 @@ module.exports = class MainListener extends EventListener {
fetch(`https://discordbotlist.com/api/bots/${client.user.id}/stats`, {
method: 'POST',
headers: { Authorization: process.env.DBL2_TOKEN },
body: { guilds: client.guilds.size, users: client.users.size }
body: { guilds: totalGuilds, users: totalUsers }
})
.then(() => client.log('Posted statistics successfully', { color: 'green', tags: ['discordbotlist.com'] }))
.catch(() => client.log('Failed to post statistics', { color: 'red', tags: ['discordbotlist.com'] }))
Expand Down
1 change: 1 addition & 0 deletions src/locales/en-US/commands.json
Original file line number Diff line number Diff line change
Expand Up @@ -1894,6 +1894,7 @@
"updatedAt": "Updated at",
"tested": "people tested",
"deaths": "Deaths",
"vaccinated": "People vaccinated",
"casesPerOneMillion": "Cases per one million",
"source": "Data provided by [disease-sh](https://github.com/disease-sh). Check the [sources](https://github.com/disease-sh/API/blob/master/README.md#sources)",
"subcommands": {
Expand Down
1 change: 1 addition & 0 deletions src/locales/en-US/errors.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"invalidEmoji": "You have to give me a valid emoji.",
"invalidRole": "You have to give me a valid role.",
"userCantBeDeveloper": "User can't be a developer.",
"userPartial": "User isn't on this server and this command requires it to.",
"onlyOldAccounts": "Your account must be at least one month old in order to do that!",
"voiceChannelJoin": "I can't join this voice channel!",
"sameUser": "You have to give me a user that isn't you.",
Expand Down
1 change: 1 addition & 0 deletions src/music/sources/twitch/TwitchSong.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ module.exports = class TwitchSong extends Song {
const user = await tw.getUser(stream.user_id)
if (user) {
this.artwork = user.profile_image_url
console.log('ate aqui foi')
this.richInfo = {
viewerCount: stream.viewer_count,
viewCount: user.view_count,
Expand Down
8 changes: 5 additions & 3 deletions src/structures/command/parameters/types/MemberParameter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ module.exports = class MemberParameter extends UserParameter {
}
}

static parse (arg, context) {
static async parse (arg, context) {
if (!arg) return

const { guild } = context
const user = super.parse(arg, context)
return guild.members.cache.get(user.id)
const user = await super.parse(arg, context)

if (!user) return undefined
return !user.joinedTimestamp && user.id ? user : guild.members.cache.get(user.id)
}
}
16 changes: 13 additions & 3 deletions src/structures/command/parameters/types/UserParameter.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,36 @@ module.exports = class UserParameter extends Parameter {
acceptUser: defVal(options, 'acceptUser', true),
acceptDeveloper: defVal(options, 'acceptDeveloper', true),
acceptSelf: !!options.acceptSelf,
acceptPartial: !!options.acceptPartial,
errors: {
invalidUser: 'errors:invalidUser',
acceptSelf: 'errors:sameUser',
acceptBot: 'errors:invalidUserBot',
acceptUser: 'errors:invalidUserNotBot',
acceptDeveloper: 'errors:userCantBeDeveloper',
acceptPartial: 'errors:userPartial',
...(options.errors || {})
}
}
}

static parse (arg, { t, client, author, guild }) {
static async parse (arg, { t, client, author, guild }) {
if (!arg) return

const regexResult = MENTION_REGEX.exec(arg)
const id = regexResult && regexResult[1]
const findMember = guild.members.cache.get(id) || guild.members.cache.find(m => m.user.username.toLowerCase().includes(arg.toLowerCase()) || m.displayName.toLowerCase().includes(arg.toLowerCase()))
const partialUser = this.acceptPartial && await client.users.fetch(id).catch(() => null)
const user = (!!findMember && findMember.user) || client.users.cache.get(id)

if (!user) {
if (!this.acceptPartial) throw new CommandError(t(this.errors.acceptPartial))
if (partialUser) {
return partialUser
}
throw new CommandError(t(this.errors.invalidUser))
}

const user = client.users.cache.get(id) || (!!findMember && findMember.user)
if (!user) throw new CommandError(t(this.errors.invalidUser))
if (!this.acceptSelf && user.id === author.id) throw new CommandError(t(this.errors.acceptSelf))
if (!this.acceptBot && user.bot) throw new CommandError(t(this.errors.acceptBot))
if (!this.acceptUser && !user.bot) throw new CommandError(t(this.errors.acceptUser))
Expand Down