Adam was built with the option of localization in mind. This means everything the user sees in the end is somehow localizable. Before you can use localization, however, you need to set a few things up.
Choosing a Localization Library
Adam does not provide direct support for localization. Instead, it abstracts it using a i18n.Func.
Although abstracted, not all types of i18n libraries are supported. Your localization library must support key-based placeholders, and pluralization through the use of an interface{} that is either a number type or a string containing a number. If you are unsure about which library to use, we recommend Nick Snyder's go-i18n.
Enabling Localization
To enable localization, you need to first use a SettingsProvider that returns a *i18n.Localizer. Localizers are responsible for generating translations. Below is an example using go-i18n.
There are better ways of structuring this outside of package main. Regard this as an MWE.
cmd/mybot/settings_provider.go
package main
import (
"github.com/diamondburned/ariakwa/v2/discord"
"github.com/mavolin/adam/pkg/i18n"
"github.com/mavolin/disstate/v3/pkg/state"
i18nimpl "github.com/nicksnyder/go-i18n/v2/i18n"
)
type settingsRepository interface {
GuildSettings(discord.GuildID) (prefixes []string, lang string, err error)
}
func newSettingsProvider(
repo settingsRepository, bundle *i18nimpl.Bundle,
) bot.SettingsProvider {
return func (_ *state.Base, m *discord.Message) (
[]string, *i18n.Localizer, bool,
) {
prefixes, lang, err := repo.GuildSettings(m.GuildID)
if err != nil {
log.Println(err)
// allow execution regardless, and just use fallbacks
return nil, nil, true
}
return prefixes, i18n.NewLocalizer(lang, newI18nFunc(bundle, lang)), true
}
}
func newI18nFunc(b *i18nimpl.Bundle, lang string) i18n.Func {
l := i18nimpl.NewLocalizer(b, lang)
return func(
term i18n.Term, placeholders map[string]interface{}, plural interface{},
) (string, error) {
return l.Localize(&i18nimpl.LocalizeConfig{
MessageID: string(term),
TemplateData: placeholders,
PluralCount: plural,
})
}
}