telebot
telebot copied to clipboard
Any documentation about how to use layout package?
Hello. First of all, thanks for amazing library :)
I'm wondering if there are some how-tos about layout package? As far as I understand this package helps to handle multiple locales I'm building multilangual bot that replies depending on language that user sets at the start/settings.
Anyway, figured it out myself.
- You need to create your layout YAML file (can take template from example.yml)
- Put your localized texts YAML file into locales dir (by default its
./locales
). File name (without extension) must match the locale you return inLocaleFunc
(see below). Example of texts file:
en.yml
greeting: Hello
good_bye: Bye
- Implement your own LocaleFunc. In short: this function must return string value of a locale name, for example
"en"
or"ru"
and also your texts file must be nameden.yml
orru.yml
- Put it all together:
import (
tele "gopkg.in/telebot.v3"
"gopkg.in/telebot.v3/layout"
)
var tgbot *tele.Bot
var lt *layout.Layout
func InitBot(settings tele.Settings) {
var err error
tgbot, err = tele.NewBot(settings)
if err != nil {
panic(err)
}
lt, err = layout.New("layout.yml")
if err != nil {
panic(err)
}
// Middlewares first argument is 'fallback' locale
tgbot.Use(lt.Middleware("en", getUserLocale))
}
func getUserLocale(r tele.Recipient) string {
// your get locale logic
return "en"
}
- And in your handlers:
func handler(c tele.Context) error {
tgbot.Send(c.Sender(), lt.Text(c, "greeting"))
return err
}
You can find other methods in layout/layout.go