telebot icon indicating copy to clipboard operation
telebot copied to clipboard

Any documentation about how to use layout package?

Open Googlom opened this issue 2 years ago • 2 comments

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.

Googlom avatar Aug 12 '22 06:08 Googlom

Anyway, figured it out myself.

  1. You need to create your layout YAML file (can take template from example.yml)
  2. Put your localized texts YAML file into locales dir (by default its ./locales). File name (without extension) must match the locale you return in LocaleFunc (see below). Example of texts file:

en.yml

greeting: Hello
good_bye: Bye
  1. 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 named en.yml or ru.yml
  2. 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"
}
  1. 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

Googlom avatar Aug 15 '22 10:08 Googlom

  • You can find the basic documentation here
  • And many examples built on the newest telebot here
  • Also you can use this template for your future bots

demget avatar Aug 16 '22 09:08 demget