项目作者: nskondratev

项目描述 :
Middlewares chain for telegram-bot-api: https://github.com/go-telegram-bot-api/telegram-bot-api
高级语言: Go
项目地址: git://github.com/nskondratev/telegram-bot-api-chain.git
创建时间: 2020-02-01T09:07:05Z
项目社区:https://github.com/nskondratev/telegram-bot-api-chain

开源协议:MIT License

下载


telegram-bot-api-chain

Middlewares chain for telegram-bot-api package: https://github.com/go-telegram-bot-api/telegram-bot-api

Motivation

I like the concept of handler in standard Go http package.
Also I like the middleware chaining, provided by alice package.

This package introduces Handler and HandlerFunc types for telegram-bot-api package and utility functions for chaining middleware for updates handler.

Example

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "os"
  6. "time"
  7. "github.com/go-telegram-bot-api/telegram-bot-api"
  8. chain "github.com/nskondratev/telegram-bot-api-chain"
  9. )
  10. func LogTimeExecution(next chain.Handler) chain.Handler {
  11. return bot.HandlerFunc(func(ctx context.Context, update tgbotapi.Update) {
  12. ts := time.Now()
  13. next.Handle(ctx, update)
  14. te := time.Now().Sub(ts)
  15. log.Printf("Execution time of handler: %s", te.String())
  16. })
  17. }
  18. func UpdateHandler(ctx context.Context, update tgbotapi.Update) {
  19. if update.Message != nil && update.Message.From != nil {
  20. log.Printf("Received update from: %s\n", update.Message.From)
  21. }
  22. }
  23. func main() {
  24. h := chain.
  25. NewChain(
  26. LogTimeExecution,
  27. ).
  28. ThenFunc(chain.HandlerFunc(UpdateHandler))
  29. tg, _ := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_API_TOKEN"))
  30. updateConfig := tgbotapi.NewUpdate(0)
  31. updateConfig.Timeout = 60
  32. updates, _ := tg.GetUpdatesChan(updateConfig)
  33. for u := range updates {
  34. h.Handle(context.Background(), u)
  35. }
  36. }