#Adding dynamic translation to a discord bot
14 messages · Page 1 of 1 (latest)
The command file ```
import { ChannelType, ChatInputCommandInteraction, SlashCommandBuilder } from 'discord.js';
import guildService from "../services/guild.service";
import channelService from "../services/channel.service";
const fs = require('fs');
async function getSelectedLanguage(guildId: string, channelId: string): Promise<string> {
const guild = await guildService.getGuildLanguage(guildId)
const channel = await channelService.getChannelLanguage(guildId, channelId)
if (channel)
return channel.language
if (guild)
return guild.language!
return "en"
}
export async function buildSlashCommandHandler(interaction: ChatInputCommandInteraction) {
const selectedLanguage = await getSelectedLanguage(interaction.guildId!, interaction.channelId);
const translations = JSON.parse(fs.readFileSync(../../translations/${selectedLanguage}.json));
const slashCommandBuilder = new SlashCommandBuilder()
.setName(translations.setName)
.setDescription(translations.setDescription)
.addStringOption(option =>
option.setName(translations.optionLanguageName)
.setRequired(true)
.setDescription(translations.optionLanguageDescription))
.addChannelOption(option =>
option.setName(translations.optionChannelName)
.addChannelTypes(ChannelType.GuildText)
.setDescription(translations.optionChannelDescription))
return slashCommandBuilder
}
module.exports = {
data: buildSlashCommandHandler,
async execute(interaction: ChatInputCommandInteraction) {
await interaction.reply('languagecommand!');
},
};
The interaction before all the commands:
import { ChatInputCommandInteraction, Events } from "discord.js";
import { buildSlashCommandHandler } from "../commands/language";
module.exports = {
name: Events.InteractionCreate,
once: true,
async execute(interaction: ChatInputCommandInteraction) {
if (!interaction.isCommand()) return;
await buildSlashCommandHandler(interaction).catch(console.error);
},
};
I honestly dont get your code at all
Just a mess tbh, cant you just use setNameLocalization?
SlashCommandBuilder#setNameLocalizations()
Sets the name localizations
And same thing with others
Then just access interaction.locale and change the reply depending on the language
ChatInputCommandInteraction#locale
The locale of the user who invoked this interaction
Slash Commands: Localized responses
In addition to the ability to provide localized command definitions, you can also localize your responses. To do this, get the locale of the user with ChatInputCommandInteraction#locale and respond accordingly:
read more
toJSON() not json()
That should work, dont know how i missed that :/
Yeah ist correct i just spelled it incorrectly here, mybad
Then paste your actual error, not paraphrase it please