/tgo

Telegram Bot framework & utilities for Go, built on top of telegram-bot-api, can be used as drop-in-replacement. With @nekomeowww's flavor, born from varies of Telegram Bot projects.

Primary LanguageGoMIT LicenseMIT

tgo

Go Reference

Telegram Bot framework & utilities for Go, built on top of telegram-bot-api, can be used as drop-in-replacement. With @nekomeowww's flavor, born from varies of Telegram Bot projects.

Features

  • 🎺 Wrapper for commands, callback queries, inline queries
  • 🎆 Any-length callback query data, no more 64-bytes fighting
  • 🎯 Battle-tested dispatcher for each supported updates
  • 👮 Middleware support (guard, permission check, etc.)
  • 🌍 Opt-in i18n support
  • 🚀 Easy to use, easy to extend
  • 🍱 Useful helpers for permission check, message handling, error handling
  • 📦 Dependency injection friendly
  • 📚 More examples and documentation
  • 🛜 Out of the box support for webhooks & polling

🤠 Spec & Documentation

GoDoc: https://godoc.org/github.com/nekomeowww/tgo

Usage

go get -u github.com/nekomeowww/tgo
package main

import (
	"context"
	"os"

	"github.com/nekomeowww/tgo"
)

func main() {
	bot, err := tgo.NewBot(
		tgo.WithToken(os.Getenv("TELEGRAM_BOT_TOKEN")),
	)
	if err != nil {
		panic(err)
	}

	bot.OnCommand("ping", nil, tgo.NewHandler(func(ctx *tgo.Context) (tgo.Response, error) {
		return ctx.NewMessage("pong"), nil
	}))

	bot.Bootstrap(context.TODO())
}

if you use uber/fx too, you can follow this example:

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/nekomeowww/fo"
	"github.com/nekomeowww/tgo"

	"go.uber.org/fx"
)

func NewBot() func() (*tgo.Bot, error) {
	return func() (*tgo.Bot, error) {
		bot, err := tgo.NewBot(tgo.WithToken(os.Getenv("TELEGRAM_BOT_TOKEN")))
		if err != nil {
			return nil, err
		}

		bot.OnCommand("ping", nil, tgo.NewHandler(func(ctx *tgo.Context) (tgo.Response, error) {
    		return ctx.NewMessage("pong"), nil
    	}))

		return bot, nil
	}
}

func Run() func(fx.Lifecycle, *tgo.Bot) {
	return func(lifecycle fx.Lifecycle, bot *tgo.Bot) {
		lifecycle.Append(fx.Hook{
			OnStart: func(ctx context.Context) error {
				go func() {
					_ = bot.Start(ctx)
				}()
				return nil
			},
			OnStop: func(ctx context.Context) error {
				return bot.Stop(ctx)
			},
		})
	}
}

func main() {
	app := fx.New(
		fx.Provide(NewBot()),
		fx.Invoke(Run()),
	)

	app.Run()

	stopCtx, stopCtxCancel := context.WithTimeout(context.Background(), time.Second*15)
	defer stopCtxCancel()

	if err := app.Stop(stopCtx); err != nil {
		log.Fatal(err)
	}
}

👪 Other family members of anyo

🎆 Other cool related Golang projects I made & maintained