Skip to content

Commit

Permalink
Add default language configuration for slash command
Browse files Browse the repository at this point in the history
  • Loading branch information
appujet committed Jul 16, 2024
1 parent d80374e commit de0feac
Show file tree
Hide file tree
Showing 10 changed files with 146 additions and 80 deletions.
2 changes: 1 addition & 1 deletion languages
97 changes: 57 additions & 40 deletions src/commands/info/Help.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import { Command, type Context, type Lavamusic } from "../../structures/index.js";

/* "help": {
"description": "Shows the help menu.",
"options": {
"command": "The command you want to get info on"
},
"content": "Hey there! I'm {bot}, a music bot made with [Lavamusic](https://github.com/appujet/lavamusic) and Discord. You can use `{prefix}help <command>` to get more info on a command.",
"title": "Help Menu",
"help_cmd": "**Description:** {description.content}\n**Usage:** {usage}\n**Examples:** {examples}\n**Aliases:** {aliases}\n**Category:** {category}\n**Cooldown:** {cooldown} seconds\n**Permissions:** {premUser}\n**Bot Permissions:** {premBot}\n**Developer Only:** {dev}\n**Slash Command:** {slash}\n**Args:** {args}\n**Player:** {player}\n**DJ:** {dj}\n**DJ Permissions:** {djPerm}\n**Voice:** {voice}",
"footer": "Use {prefix}help <command> for more info on a command"
} */
export default class Help extends Command {
constructor(client: Lavamusic) {
super(client, {
name: "help",
description: {
content: "Shows the help menu",
content: "cmd.help.description",
examples: ["help"],
usage: "help",
},
Expand All @@ -28,7 +38,7 @@ export default class Help extends Command {
options: [
{
name: "command",
description: "The command you want to get info on",
description: "cmd.help.options.command",
type: 3,
required: false,
},
Expand All @@ -45,49 +55,56 @@ export default class Help extends Command {
const command = this.client.commands.get(args[0].toLowerCase());
if (!command) {
return await ctx.sendMessage({
embeds: [client.embed().setColor(client.color.red).setDescription(`Command \`${args[0]}\` not found`)],
embeds: [client.embed().setColor(client.color.red).setDescription(ctx.locale("cmd.help.not_found", { cmdName: args[0] }))],
});
}
const helpEmbed = embed
.setColor(this.client.color.main)
.setTitle(`Help Menu - ${command.name}`)
.setDescription(`**Description:** ${command.description.content}
**Usage:** ${guild.prefix}${command.description.usage}
**Examples:** ${command.description.examples.map((example) => `${guild.prefix}${example}`).join(", ")}
**Aliases:** ${command.aliases.map((alias) => `\`${alias}\``).join(", ")}
**Category:** ${command.category}
**Cooldown:** ${command.cooldown} seconds
**Permissions:** ${command.permissions.user.length > 0 ? command.permissions.user.map((perm) => `\`${perm}\``).join(", ") : "None"}
**Bot Permissions:** ${command.permissions.client.map((perm) => `\`${perm}\``).join(", ")}
**Developer Only:** ${command.permissions.dev ? "Yes" : "No"}
**Slash Command:** ${command.slashCommand ? "Yes" : "No"}
**Args:** ${command.args ? "Yes" : "No"}
**Player:** ${command.player.active ? "Yes" : "No"}
**DJ:** ${command.player.dj ? "Yes" : "No"}
**DJ Permissions:** ${command.player.djPerm ? command.player.djPerm : "None"}
**Voice:** ${command.player.voice ? "Yes" : "No"}`);
ctx.sendMessage({ embeds: [helpEmbed] });
} else {
const fields = categories.map((category) => ({
name: category,
value: commands
.filter((cmd) => cmd.category === category)
.map((cmd) => `\`${cmd.name}\``)
.join(", "),
inline: false,
}));
const helpEmbed = embed
.setColor(this.client.color.main)
.setTitle("Help Menu")
.setColor(client.color.main)
.setTitle(`${ctx.locale("cmd.help.title")} - ${command.name}`)
.setDescription(
`Hey there! I'm ${this.client.user.username}, a music bot made with [Lavamusic](https://github.com/appujet/lavamusic) and Discord. You can use \`${guild.prefix}help <command>\` to get more info on a command.`,
)
.setFooter({
text: `Use ${guild.prefix}help <command> for more info on a command`,
});
helpEmbed.addFields(...fields);
ctx.sendMessage({ embeds: [helpEmbed] });
ctx.locale("cmd.help.help_cmd", {
description: command.description.content,
usage: `${guild.prefix}${command.description.usage}`,
examples: command.description.examples.map((example) => `${guild.prefix}${example}`).join(", "),
aliases: command.aliases.map((alias) => `\`${alias}\``).join(", "),
category: command.category,
cooldown: command.cooldown,
premUser:
command.permissions.user.length > 0 ? command.permissions.user.map((perm) => `\`${perm}\``).join(", ") : "None",
premBot: command.permissions.client.map((perm) => `\`${perm}\``).join(", "),
dev: command.permissions.dev ? "Yes" : "No",
slash: command.slashCommand ? "Yes" : "No",
args: command.args ? "Yes" : "No",
player: command.player.active ? "Yes" : "No",
dj: command.player.dj ? "Yes" : "No",
djPerm: command.player.djPerm ? command.player.djPerm : "None",
voice: command.player.voice ? "Yes" : "No",
}),
);
return await ctx.sendMessage({ embeds: [helpEmbed] });
}
const fields = categories.map((category) => ({
name: category,
value: commands
.filter((cmd) => cmd.category === category)
.map((cmd) => `\`${cmd.name}\``)
.join(", "),
inline: false,
}));
const helpEmbed = embed
.setColor(client.color.main)
.setTitle(ctx.locale("cmd.help.title"))
.setDescription(
ctx.locale("cmd.help.content", {
bot: client.user.username,
prefix: guild.prefix,
}),
)
.setFooter({
text: ctx.locale("cmd.help.footer", { prefix: guild.prefix }),
});
helpEmbed.addFields(...fields);
return await ctx.sendMessage({ embeds: [helpEmbed] });
}
}

Expand Down
9 changes: 5 additions & 4 deletions src/commands/info/Invite.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from "discord.js";
import { Command, type Context, type Lavamusic } from "../../structures/index.js";


export default class Invite extends Command {
constructor(client: Lavamusic) {
super(client, {
name: "invite",
description: {
content: "Sends the bot's invite link",
content: "cmd.invite.description",
examples: ["invite"],
usage: "invite",
},
Expand Down Expand Up @@ -34,18 +35,18 @@ export default class Invite extends Command {
const embed = this.client.embed();
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder()
.setLabel("Invite")
.setLabel(ctx.locale("buttons.invite"))
.setStyle(ButtonStyle.Link)
.setURL(
`https://discord.com/api/oauth2/authorize?client_id=${client.config.clientId}&permissions=8&scope=bot%20applications.commands`,
),
new ButtonBuilder().setLabel("My Server").setStyle(ButtonStyle.Link).setURL("https://discord.gg/STXurwnZD5"),
new ButtonBuilder().setLabel(ctx.locale("buttons.support")).setStyle(ButtonStyle.Link).setURL("https://discord.gg/STXurwnZD5"),
);
return await ctx.sendMessage({
embeds: [
embed
.setColor(this.client.color.main)
.setDescription("You can invite me by clicking the button below. Any bugs or outages? Join the support server!"),
.setDescription(ctx.locale("cmd.invite.content"))
],
components: [row],
});
Expand Down
27 changes: 16 additions & 11 deletions src/commands/info/LavaLink.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Command, type Context, type Lavamusic } from "../../structures/index.js";


export default class LavaLink extends Command {
constructor(client: Lavamusic) {
super(client, {
name: "lavalink",
description: {
content: "Shows the current Lavalink stats",
content: "cmd.lavalink.description",
examples: ["lavalink"],
usage: "lavalink",
},
Expand All @@ -32,7 +33,7 @@ export default class LavaLink extends Command {
public async run(client: Lavamusic, ctx: Context): Promise<any> {
const embed = this.client
.embed()
.setTitle("Lavalink Stats")
.setTitle(ctx.locale("cmd.lavalink.title"))
.setColor(this.client.color.main)
.setThumbnail(this.client.user.avatarURL({}))
.setTimestamp();
Expand All @@ -46,16 +47,20 @@ export default class LavaLink extends Command {
memory: { used: 0, reservable: 0 },
};
const formattedStats = `\`\`\`yaml
Player: ${stats.players}
Playing Players: ${stats.playingPlayers}
Uptime: ${client.utils.formatTime(stats.uptime)}
Cores: ${stats.cpu.cores} Core(s)
Memory Usage: ${client.utils.formatBytes(stats.memory.used)} / ${client.utils.formatBytes(stats.memory.reservable)}
System Load: ${(stats.cpu.systemLoad * 100).toFixed(2)}%
Lavalink Load: ${(stats.cpu.lavalinkLoad * 100).toFixed(2)}%
\`\`\``;
${ctx.locale("cmd.lavalink.content", {
players: stats.players,
playingPlayers: stats.playingPlayers,
uptime: client.utils.formatTime(stats.uptime),
cores: stats.cpu.cores,
used: client.utils.formatBytes(stats.memory.used),
reservable: client.utils.formatBytes(stats.memory.reservable),
systemLoad: (stats.cpu.systemLoad * 100).toFixed(2),
lavalinkLoad: (stats.cpu.lavalinkLoad * 100).toFixed(2),
})}
\`\`\``;

embed.addFields({
name: `Name: ${node.name} (${statusEmoji})`,
name: `${node.name} (${statusEmoji})`,
value: formattedStats,
});
});
Expand Down
3 changes: 1 addition & 2 deletions src/commands/info/Ping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export default class Ping extends Command {
super(client, {
name: "ping",
description: {
content: "Shows the bot's ping",
content: "cmd.ping.description",
examples: ["ping"],
usage: "ping",
},
Expand All @@ -31,7 +31,6 @@ export default class Ping extends Command {

public async run(_client: Lavamusic, ctx: Context): Promise<any> {
const msg = await ctx.sendDeferMessage(ctx.locale("cmd.ping.content"));
console.log(ctx.guildLocale)
const embed = this.client
.embed()
.setAuthor({ name: "Pong", iconURL: this.client.user.displayAvatarURL() })
Expand Down
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import dotenv from "dotenv";
import { SearchEngine } from "./types.js";
import { SearchEngine, Language } from "./types.js";
dotenv.config();

const parseBoolean = (value?: string): boolean => value?.trim().toLowerCase() === "true";
Expand All @@ -14,7 +14,7 @@ export default {
yellow: 0xffff00,
main: 0x2f3136,
},
defaultLanguage: process.env.DEFAULT_LANGUAGE || "hi",
defaultLanguage: process.env.DEFAULT_LANGUAGE || Language.EnglishUS,
keepAlive: parseBoolean(process.env.KEEP_ALIVE),
autoNode: parseBoolean(process.env.AUTO_NODE),
searchEngine: process.env.SEARCH_ENGINE || SearchEngine.YouTube,
Expand Down
12 changes: 6 additions & 6 deletions src/structures/Command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ interface CommandPermissions {

interface CommandOptions {
name: string;
nameLocalizations?: Record<string, string>;
name_localizations?: Record<string, string>;
description?: Partial<CommandDescription>;
descriptionLocalizations?: Record<string, string>;
description_localizations?: Record<string, string>;
aliases?: string[];
cooldown?: number;
args?: boolean;
Expand All @@ -38,9 +38,9 @@ interface CommandOptions {
export default class Command {
public client: Lavamusic;
public name: string;
public nameLocalizations?: Record<string, string>;
public name_localizations?: Record<string, string>;
public description: CommandDescription;
public descriptionLocalizations?: Record<string, string>;
public description_localizations?: Record<string, string>;
public aliases: string[];
public cooldown: number;
public args: boolean;
Expand All @@ -53,13 +53,13 @@ export default class Command {
constructor(client: Lavamusic, options: CommandOptions) {
this.client = client;
this.name = options.name;
this.nameLocalizations = options.nameLocalizations ?? {};
this.name_localizations = options.name_localizations ?? {};
this.description = {
content: options.description?.content ?? "No description provided",
usage: options.description?.usage ?? "No usage provided",
examples: options.description?.examples ?? ["No examples provided"],
};
this.descriptionLocalizations = options.descriptionLocalizations ?? {};
this.description_localizations = options.description_localizations ?? {};
this.aliases = options.aliases ?? [];
this.cooldown = options.cooldown ?? 3;
this.args = options.args ?? false;
Expand Down
20 changes: 15 additions & 5 deletions src/structures/I18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ import i18n from "i18n";

import Logger from "./Logger.js";
import { Locale } from "discord.js";
import { Language } from "../types.js";

const logger = new Logger();


export function initI18n() {
i18n.configure({
locales: [
Locale.EnglishUS,
Locale.Hindi
],
defaultLocale: Locale.EnglishUS,
locales: Object.keys(Language),
defaultLocale: "EnglishUS",
directory: `${process.cwd()}/languages/locales`,
retryInDefaultLocale: true,
objectNotation: true,
Expand All @@ -36,4 +35,15 @@ export { i18n };
export function T(locale: string, text: string | i18n.TranslateOptions, ...params: any) {
i18n.setLocale(locale);
return i18n.__(text, ...params);
}

export function localization(lan: any, name: any, desc: any) {
return {
name: [Locale[lan], name],
description: [Locale[lan], T(lan, desc)]
};
}

export function descriptionLocalization(name: any, text: any) {
return i18n.getLocales().map((locale) => localization(Locale[locale] || locale, name, text));
}
Loading

0 comments on commit de0feac

Please sign in to comment.