discordgoi18n

package module
v0.0.0-...-a6b2062 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

discordgo-i18n

GoDoc Golangci-lint Test codecov

discordgo-i18n is a simple and lightweight Go package that helps you translate Go programs into languages supported by Discord.

  • Built to ease usage of bwmarrin/discordgo
  • Less verbose than go-i18n
  • Supports multiple strings per key to make your bot "more alive"
  • Supports strings and arrays with named variables
  • Supports message files of JSON format

Getting started

Installing

This assumes you already have a working Go environment, if not please see this page first.

go get will always pull the latest tagged release from the main branch.

go get github.com/kaysoro/discordgo-i18n

NOTICE: this package has been built to ease usage of bwmarrin/discordgo, it can be used for other projects but will be less practical.

Usage

Import the package into your project.

import i18n "github.com/kstoums/discordgo-i18n"

Initialize the logger adapter with a logger that implements the logger.Logger interface

loggerAdapter := NewDiscordGoI18nLoggerAdapter(DiscordGoI18nLoggerAdapterDeps{Logger: your_logger_implementing_the_logger.Logger_interface})

Initialize the i18n translator with your logger adapter

i18n := i18n.NewTranslator(loggerAdapter)

Load bundles for locales to support with a local filepath.

err := i18n.LoadBundle(discordgo.French, "path/to/your/file.json")

Or through fs.FS.

//go:embed langs/*
var langFS embed.FS
err := i18n.LoadBundleFS(discordgo.Czech, langFS, "langs/fr-FR.json")

If you want to handle yourself i18n filesystem, provide the content directly.

err := i18n.LoadBundleContent(discordgo.Danish, map[string]any{"my": "content"})

The bundle format must respect the schema below; note text/template syntax is used to inject variables.
For a given key, value can be string, string array or even deep structures to group translations as wanted. In case any other type is provided, it is mapped to string automatically.

{
    "hello_world": "Hello world!",
    "hello_anyone": "Hello {{ .anyone }}!",
    "image": "https://media2.giphy.com/media/Ju7l5y9osyymQ/giphy.gif",
    "bye": ["See you", "Bye!"],
    "command": {
        "scream": {
            "name": "scream",
            "description": "Screams something",
            "dog": "Waf waf! 🐶",
            "cat": "Miaw! 🐱"
        }
    }
}

By default, the locale fallback used when a key does not have any translations is discordgo.EnglishUS. To change it, use the following method.

i18n.SetDefault(discordgo.ChineseCN)

To get translations use the below thread-safe method; if any translation cannot be found or an error occurred even with the fallback, key is returned.

helloWorld := i18n.Get(discordgo.EnglishUS, "hello_world")
fmt.Println(helloWorld)
// Prints "Hello world!"

helloAnyone := i18n.Get(discordgo.EnglishUS, "hello_anyone")
fmt.Println(helloAnyone)
// Prints "Hello {{ .anyone }}!"

helloAnyone = i18n.Get(discordgo.EnglishUS, "hello_anyone", i18n.Vars{"anyone": "Nick"})
fmt.Println(helloAnyone)
// Prints "Hello Nick!"

bye := i18n.Get(discordgo.EnglishUS, "bye")
fmt.Println(bye)
// Prints randomly "See you" or "Bye!"

keyDoesNotExist := i18n.Get(discordgo.EnglishUS, "key_does_not_exist")
fmt.Println(keyDoesNotExist)
// Prints "key_does_not_exist"

dog := i18n.Get(discordgo.EnglishUS, "command.scream.dog")
fmt.Println(dog)
// Prints "Waf waf! 🐶"

To get localizations for a command name, description, options or other fields, use the below thread-safe method. It retrieves a *map[discordgo.Locale]string based on the loaded bundles.

screamCommand := discordgo.ApplicationCommand{
    Name:                     "scream",
    Description:              "Here a default description for my command",
    NameLocalizations:        i18n.GetLocalizations("command.scream.name"),
    DescriptionLocalizations: i18n.GetLocalizations("command.scream.description"),
}

Here an example of how it can work with interactions.

func HelloWorld(s *discordgo.Session, i *discordgo.InteractionCreate) {

    err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
		Type: discordgo.InteractionResponseChannelMessageWithSource,
		Data: &discordgo.InteractionResponseData{
			Embeds: []*discordgo.MessageEmbed{
                {
                    Title:       i18n.Get(i.Locale, "hello_world"),
                    Description: i18n.Get(i.Locale, "hello_anyone", i18n.Vars{"anyone": i.Member.Nick}),
                    Image:       &discordgo.MessageEmbedImage{URL: i18n.Get(i.Locale, "image")},
                },
            },
		},
	})

    // ...
}

Contributing

Contributions are very welcomed, however please follow the below guidelines.

  • First open an issue describing the bug or enhancement so it can be discussed.
  • Try to match current naming conventions as closely as possible.
  • Create a Pull Request with your changes against the main branch.

Licence

discordgo-i18n is available under the MIT license. See the LICENSE file for more info.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MockDeps

type MockDeps struct {
	Logger logger.Logger
}

type Translator

type Translator interface {
	SetDefault(locale discordgo.Locale) // Defined in constructor
	LoadBundle(locale discordgo.Locale, path string) error
	LoadBundleFS(locale discordgo.Locale, fs fs.FS, path string) error
	LoadBundleContent(locale discordgo.Locale, content map[string]any) error
	Get(locale discordgo.Locale, key string, values Vars) string
	GetArray(locale discordgo.Locale, key string, values Vars) []string
	GetDefault(key string, values Vars) string
	GetDefaultArray(key string, values Vars) []string
	GetLocalizations(key string, variables Vars) *map[discordgo.Locale]string
}

func NewTranslator

func NewTranslator(logger logger.Logger) Translator

type Vars

type Vars map[string]any

Vars is the collection used to inject variables during translation. This type only exists to be less verbose.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL