tgbotapi-mux

command module
v0.0.0-...-124e46a Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2023 License: MIT Imports: 8 Imported by: 0

README

Simple Telegram Updates Routing

This example contains bunch of helpers and abstractions compatible with any telegram bot libs

See example with tgbotapi v5 in example.go and feel free to copy and reuse this utils.
package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"

	"github.com/dailydismay/tgbotapi-mux/mux/dispatcher"
	"github.com/dailydismay/tgbotapi-mux/mux/filter"
	"github.com/dailydismay/tgbotapi-mux/mux/handler"
	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

type V5Filter = filter.Filter[*tgbotapi.Update]

func IsCommand(command string) V5Filter {
	return func(u *tgbotapi.Update) bool {
		return u.Message != nil && u.Message.IsCommand() && u.Message.Command() == command
	}
}

func main() {
	globalNoopMwStack := handler.CombineMiddleware([]handler.Middleware[*tgbotapi.Update]{
		func(next handler.HandleFn[*tgbotapi.Update]) handler.HandleFn[*tgbotapi.Update] {
			return func(u *tgbotapi.Update) error {
				fmt.Println("noop one")
				return next(u)
			}
		},
		func(next handler.HandleFn[*tgbotapi.Update]) handler.HandleFn[*tgbotapi.Update] {
			return func(u *tgbotapi.Update) error {
				fmt.Println("noop two")
				return next(u)
			}
		},
	})

	v5dispatcher := dispatcher.NewDefault[*tgbotapi.Update]()
	v5dispatcher.Register(IsCommand("start"), handler.WithMiddleware(
		func(u *tgbotapi.Update) error {
			// implement routed logic
			return nil
		},
		globalNoopMwStack,
	))

	ctx, cancel := signal.NotifyContext(context.Background(), os.Kill, os.Interrupt)
	defer cancel()

	bot, _ := tgbotapi.NewBotAPI("")
	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60
	updates := bot.GetUpdatesChan(u)

	// !!! warning !!!
	// this is only an example
	// this code is not production-ready
	// but shows how to use dispatcher instance
	for {
		select {
		case <-ctx.Done():
			return
		case update, ok := <-updates:
			if !ok {
				return
			}
			// global error handler
			_ = v5dispatcher.Dispatch(&update)
		}
	}
}

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
mux

Jump to

Keyboard shortcuts

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