feat: descrete wargaming response

This commit is contained in:
TresAbhi committed 2023-04-27 00:21:39 +00:00
1 parent fd1dc40918
commit d4f676091d
14 files changed
+211 -297

No files matched your search

+10 -7
View File
@@ -1,6 +1,7 @@
import { Client, EmbedBuilder, TextChannel } from 'discord.js';
import discord from '../../discord.json' assert { type: 'json' };
import { NEGATIVE_COLOR } from '../constants/colors.js';
import isDev from '../utilities/isDev.js';
export const PROCESS_ERROR_EVENTS = ['uncaughtException'];
export const CLIENT_ERROR_EVENTS = ['error'];
@@ -18,19 +19,21 @@ function handleError(error: Error, client: Client) {
.setTitle('Skilled Bot ran into a catastrophic error')
.setColor(NEGATIVE_COLOR)
.setDescription(
`Total shutdown was avoided! Error:\n\n\`\`\`${error.name}\n${error.message}\n${error.stack}\n${error.cause}\`\`\``,
`\`\`\`${error.name}\n${error.message}\n${error.stack}\n${error.cause}\`\`\``,
),
],
});
}
export function registerErrorHandlers(client: Client) {
PROCESS_ERROR_EVENTS.forEach((name) =>
process.on(name, (error) => handleError(error, client)),
);
CLIENT_ERROR_EVENTS.forEach((name) =>
client.on(name, (error) => handleError(error, client)),
);
if (!isDev()) {
PROCESS_ERROR_EVENTS.forEach((name) =>
process.on(name, (error) => handleError(error, client)),
);
CLIENT_ERROR_EVENTS.forEach((name) =>
client.on(name, (error) => handleError(error, client)),
);
}
return client;
}
+1 -1
View File
@@ -20,7 +20,7 @@ export const CLANS = {
export default {
inProduction: true,
inDevelopment: false,
inDevelopment: true,
inPublic: false,
command: new SlashCommandBuilder()
+54 -48
View File
@@ -1,11 +1,11 @@
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import fetch from 'node-fetch';
import { CommandRegistry } from '../behaviors/interactionCreate.js';
import { NEGATIVE_COLOR, POSITIVE_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { ClanDetails } from '../types/clanDetails.js';
import { ClanInfo } from '../types/clanInfo.js';
import { PlayerPersonalData } from '../types/playerPersonalData.js';
import getClan from '../utilities/getClan.js';
import getWargamingResponse from '../utilities/getWargamingResponse.js';
const DEFAULT_THRESHOLD = 7;
@@ -51,56 +51,62 @@ export default {
const threshold =
interaction.options.getNumber('threshold')! ?? DEFAULT_THRESHOLD;
const time = new Date().getTime() / 1000;
const clanData = (await (
await fetch(
`https://api.wotblitz.com/wotb/clans/info/?application_id=${process.env.WARGAMING_APPLICATION_ID}&clan_id=${clan.clan_id}`,
)
).json()) as ClanDetails;
const memberIds = clanData.data[clan.clan_id].members_ids;
const playerPersonalData = (await (
await fetch(
`https://api.wotblitz.com/wotb/account/info/?application_id=${
process.env.WARGAMING_APPLICATION_ID
}&account_id=${memberIds.join(',')}`,
)
).json()) as PlayerPersonalData;
const inactiveInfo = memberIds
.map((memberId) => {
const member = playerPersonalData.data[memberId];
const inactiveDays = (time - member.last_battle_time) / 60 / 60 / 24;
getWargamingResponse<ClanInfo>(
`https://api.wotblitz.com/wotb/clans/info/?application_id=${process.env.WARGAMING_APPLICATION_ID}&clan_id=${clan.clan_id}`,
interaction,
async (clanInfo) => {
const memberIds = clanInfo[clan.clan_id].members_ids;
return [member.nickname, inactiveDays] as const;
})
.filter(([, inactiveDays]) => inactiveDays >= threshold)
.sort((a, b) => b[1] - a[1])
.map(([nickname, inactiveDays]) => {
const days = Math.floor(inactiveDays);
return `**${nickname}**: ${days} day${days === 1 ? '' : 's'}`;
});
const hasInactiveMembers = inactiveInfo.length > 0;
getWargamingResponse<PlayerPersonalData>(
`https://api.wotblitz.com/wotb/account/info/?application_id=${
process.env.WARGAMING_APPLICATION_ID
}&account_id=${memberIds.join(',')}`,
interaction,
async (playerPersonalData) => {
const inactiveInfo = memberIds
.map((memberId) => {
const member = playerPersonalData[memberId];
const inactiveDays =
(time - member.last_battle_time) / 60 / 60 / 24;
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(hasInactiveMembers ? NEGATIVE_COLOR : POSITIVE_COLOR)
.setTitle(
hasInactiveMembers
? `${clan.name}'s inactive members`
: `No inactive members in ${clan.name}`,
)
.setDescription(
hasInactiveMembers
? `Players that exceed the threshold of ${threshold} days:\n\n${inactiveInfo.join(
'\n',
)}`
: `No players exceed the threshold of ${threshold} days.`,
),
],
});
return [member.nickname, inactiveDays] as const;
})
.filter(([, inactiveDays]) => inactiveDays >= threshold)
.sort((a, b) => b[1] - a[1])
.map(([nickname, inactiveDays]) => {
const days = Math.floor(inactiveDays);
return `**${nickname}**: ${days} day${days === 1 ? '' : 's'}`;
});
const hasInactiveMembers = inactiveInfo.length > 0;
console.log(
`Displaying inactive members in ${clan.name} for ${threshold} days`,
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(
hasInactiveMembers ? NEGATIVE_COLOR : POSITIVE_COLOR,
)
.setTitle(
hasInactiveMembers
? `${clan.name}'s inactive members`
: `No inactive members in ${clan.name}`,
)
.setDescription(
hasInactiveMembers
? `Players that exceed the threshold of ${threshold} days:\n\n${inactiveInfo.join(
'\n',
)}`
: `No players exceed the threshold of ${threshold} days.`,
),
],
});
console.log(
`Displaying inactive members in ${clan.name} for ${threshold} days`,
);
},
);
},
);
});
},
+35 -35
View File
@@ -1,10 +1,10 @@
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import fetch from 'node-fetch';
import { CommandRegistry } from '../behaviors/interactionCreate.js';
import { SKILLED_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { TanksStats } from '../types/tanksStats.js';
import getBlitzAccount from '../utilities/getBlitzAccount.js';
import getWargamingResponse from '../utilities/getWargamingResponse.js';
import { tankTypeEmojis, tankopedia } from '../utilities/tankopedia.js';
export default {
@@ -47,42 +47,42 @@ export default {
const tier = Math.round(interaction.options.getNumber('tier')!);
getBlitzAccount(interaction, name, server, async (account) => {
const tankStats = (await (
await fetch(
`https://api.wotblitz.${server}/wotb/tanks/stats/?application_id=${process.env.WARGAMING_APPLICATION_ID}&account_id=${account.account_id}`,
)
).json()) as TanksStats;
getWargamingResponse<TanksStats>(
`https://api.wotblitz.${server}/wotb/tanks/stats/?application_id=${process.env.WARGAMING_APPLICATION_ID}&account_id=${account.account_id}`,
interaction,
async (tankStats) => {
const tanks = tankStats[account.account_id]!.map(
(tankData) => tankopedia.data[tankData.tank_id],
).filter((tank) => tank.tier === tier);
const tanks = tankStats.data[account.account_id]!.map(
(tankData) => tankopedia.data[tankData.tank_id],
).filter((tank) => tank.tier === tier);
await interaction.reply({
embeds: [
new EmbedBuilder()
.setTitle(
`${account.nickname}'s owned ${
tier === null ? '' : `tier ${tier} `
}tanks`,
)
.setDescription(
tanks.length === 0
? `No tanks found for player in tier ${tier}`
: tanks
.map(
(tank) =>
`${tankTypeEmojis[tank.type]} ${tank.name} ${
tank.is_premium ? '⭐' : ''
}`,
)
.join('\n'),
)
.setColor(SKILLED_COLOR),
],
});
await interaction.reply({
embeds: [
new EmbedBuilder()
.setTitle(
`${account.nickname}'s owned ${
tier === null ? '' : `tier ${tier} `
}tanks`,
)
.setDescription(
tanks.length === 0
? `No tanks found for player in tier ${tier}`
: tanks
.map(
(tank) =>
`${tankTypeEmojis[tank.type]} ${tank.name} ${
tank.is_premium ? '⭐' : ''
}`,
)
.join('\n'),
)
.setColor(SKILLED_COLOR),
],
});
console.log(
`Displaying ${account.nickname}'s owned tanks in tier ${tier}`,
console.log(
`Displaying ${account.nickname}'s owned tanks in tier ${tier}`,
);
},
);
});
},
+49 -47
View File
@@ -1,11 +1,11 @@
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import fetch from 'node-fetch';
import discord from '../../discord.json' assert { type: 'json' };
import { CommandRegistry } from '../behaviors/interactionCreate.js';
import { NEGATIVE_COLOR, POSITIVE_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { PlayerClanData } from '../types/playerClanData.js';
import getBlitzAccount from '../utilities/getBlitzAccount.js';
import getWargamingResponse from '../utilities/getWargamingResponse.js';
import { PlayerClanData } from '../types/playerClanData.js';
export default {
inProduction: true,
@@ -38,55 +38,57 @@ export default {
const server = interaction.options.getString('server') as BlitzServer;
getBlitzAccount(interaction, name, server, async (account) => {
// good match
const clanData = (await fetch(
getWargamingResponse<PlayerClanData>(
`https://api.wotblitz.${server}/wotb/clans/accountinfo/?application_id=${process.env.WARGAMING_APPLICATION_ID}&account_id=${account.account_id}&extra=clan`,
).then((response) => response.json())) as PlayerClanData;
const clan = clanData.data[account.account_id].clan;
const clanTag = clan === null ? '' : ` [${clan!.tag}]`;
interaction,
async (clanData) => {
const clan = clanData[account.account_id].clan;
const clanTag = clan === null ? '' : ` [${clan!.tag}]`;
if (interaction.member && interaction.guild) {
const member = interaction.guild?.members.cache.get(
interaction.member?.user.id,
);
member
?.setNickname(`${name}${clanTag}`)
.then(async () => {
await member.roles.remove(discord.verify_role);
await member.roles.add(discord.peasant_role);
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(POSITIVE_COLOR)
.setTitle(`${interaction.user.username} is verified`)
.setDescription(
`The user is now verified as ${name}${clanTag}`,
),
],
});
console.log(
`${interaction.user.username} verified as ${name}${clanTag}`,
if (interaction.member && interaction.guild) {
const member = interaction.guild?.members.cache.get(
interaction.member?.user.id,
);
})
.catch(async () => {
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(NEGATIVE_COLOR)
.setTitle(`${interaction.user.username} failed to verify`)
.setDescription(
'I may not have the permission to change your nickname.',
),
],
});
console.warn(
`${interaction.user.username} failed to verify as ${name}${clanTag}`,
);
});
}
member
?.setNickname(`${name}${clanTag}`)
.then(async () => {
await member.roles.remove(discord.verify_role);
await member.roles.add(discord.peasant_role);
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(POSITIVE_COLOR)
.setTitle(`${interaction.user.username} is verified`)
.setDescription(
`The user is now verified as ${name}${clanTag}`,
),
],
});
console.log(
`${interaction.user.username} verified as ${name}${clanTag}`,
);
})
.catch(async () => {
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(NEGATIVE_COLOR)
.setTitle(`${interaction.user.username} failed to verify`)
.setDescription(
'I may not have the permission to change your nickname.',
),
],
});
console.warn(
`${interaction.user.username} failed to verify as ${name}${clanTag}`,
);
});
}
},
);
});
},
} satisfies CommandRegistry;
@@ -1,7 +1,5 @@
import { WargamingResponse } from './wargamingResponse.js';
export interface ClanDetailsData {
recruiting_options: {
export interface ClanInfo {
[clanId:number]:{recruiting_options: {
vehicles_level: number;
wins_ratio: number;
average_battles_per_day: number;
@@ -26,9 +24,5 @@ export interface ClanDetailsData {
renamed_at: number;
old_tag: null;
leader_id: number;
description: string;
description: string;}
}
export type ClanDetails = WargamingResponse<{
[accountId: number]: ClanDetailsData;
}>;
+1 -3
View File
@@ -1,5 +1,3 @@
import { WargamingResponse } from './wargamingResponse.js';
export interface Clan {
members_count: number;
created_at: number;
@@ -8,4 +6,4 @@ export interface Clan {
name: string;
}
export type ClanList = WargamingResponse<Clan[]>;
export type ClanList = Clan[];
+2 -4
View File
@@ -1,6 +1,4 @@
import { WargamingResponse } from './wargamingResponse.js';
export type PlayerClanData = WargamingResponse<{
export type PlayerClanData = {
[accountId: number]: {
account_id: number;
joined_at: number;
@@ -17,4 +15,4 @@ export type PlayerClanData = WargamingResponse<{
emblem_set_id: number;
};
};
}>;
};
+2 -4
View File
@@ -1,6 +1,4 @@
import { WargamingResponse } from './wargamingResponse.js';
export type PlayerPersonalData = WargamingResponse<{
export type PlayerPersonalData = {
[accountId: number]: {
statistics: {
clan: {
@@ -54,4 +52,4 @@ export type PlayerPersonalData = WargamingResponse<{
last_battle_time: number;
nickname: string;
};
}>;
};
+2 -4
View File
@@ -1,6 +1,4 @@
import { WargamingResponse } from './wargamingResponse.js';
export type TanksStats = WargamingResponse<{
export type TanksStats = {
[accountId: number]: {
all: {
spotted: number;
@@ -32,4 +30,4 @@ export type TanksStats = WargamingResponse<{
in_garage: number | null;
tank_id: number;
}[];
}>;
};
+31 -34
View File
@@ -3,10 +3,10 @@ import {
ChatInputCommandInteraction,
EmbedBuilder,
} from 'discord.js';
import fetch from 'node-fetch';
import { NEGATIVE_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { Clan, ClanList } from '../types/clanList.js';
import getWargamingResponse from './getWargamingResponse.js';
export default async function getClan(
interaction: ChatInputCommandInteraction<CacheType>,
@@ -16,39 +16,36 @@ export default async function getClan(
) {
const serverName = BLITZ_SERVERS[server];
const clans = (await fetch(
getWargamingResponse<ClanList>(
`https://api.wotblitz.${server}/wotb/clans/list/?application_id=${process.env.WARGAMING_APPLICATION_ID}&search=${name}`,
).then((response) => response.json())) as ClanList;
interaction,
async (clans) => {
if (
clans.length > 0 &&
(clans[0].name === name || clans[0].tag === name.toUpperCase())
) {
callback(clans[0]);
} else {
// no exact match
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(NEGATIVE_COLOR)
.setTitle(`Clan not found`)
.setDescription(
`I couldn't find "${name}" in the ${serverName} server. I found ${
clans ? (clans.length < 100 ? clans.length : 'over 100') : 0
} similarly spelled clan${clans?.length !== 1 ? 's' : ''}. ${
clans && clans.length > 0
? `Did you mean "${clans[0].name}" or "${clans[0].tag}"? `
: ''
}Re-run the command, don't make typos, and capitalize correctly.`,
),
],
});
if (
clans.status === 'ok' &&
clans.data.length > 0 &&
(clans.data[0].name === name || clans.data[0].tag === name.toUpperCase())
) {
callback(clans.data[0]);
} else {
// no exact match
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(NEGATIVE_COLOR)
.setTitle(`Clan not found`)
.setDescription(
`I couldn't find "${name}" in the ${serverName} server. I found ${
clans?.data
? clans.data.length < 100
? clans.data.length
: 'over 100'
: 0
} similarly spelled clan${clans?.data?.length !== 1 ? 's' : ''}. ${
clans?.data && clans.data.length > 0
? `Did you mean "${clans.data[0].name}" or "${clans.data[0].tag}"? `
: ''
}Re-run the command, don't make typos, and capitalize correctly.`,
),
],
});
console.log(`Clan not found for ${name} in ${serverName} server.`);
}
console.log(`Clan not found for ${name} in ${serverName} server.`);
}
},
);
}
+20
View File
@@ -0,0 +1,20 @@
import { CacheType, ChatInputCommandInteraction } from 'discord.js';
import { WargamingResponse } from '../types/wargamingResponse.js';
import wargamingError from './wargamingError.js';
export default function getWargamingResponse<Data extends object>(
url: string,
interaction: ChatInputCommandInteraction<CacheType>,
callback: (data: Data) => void,
) {
fetch(url)
.then((response) => response.json())
.then((response: WargamingResponse<Data>) => {
if (response.status === 'ok') {
callback(response.data);
} else {
wargamingError(interaction);
}
})
.catch(() => wargamingError(interaction));
}