telegram_bot_api_chain

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2020 License: MIT Imports: 2 Imported by: 0

README

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

package main

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

    "github.com/go-telegram-bot-api/telegram-bot-api"
    chain "github.com/nskondratev/telegram-bot-api-chain"
)

func LogTimeExecution(next chain.Handler) chain.Handler {
	return bot.HandlerFunc(func(ctx context.Context, update tgbotapi.Update) {
		ts := time.Now()
		next.Handle(ctx, update)
		te := time.Now().Sub(ts)
        log.Printf("Execution time of handler: %s", te.String())
	})
}

func UpdateHandler(ctx context.Context, update tgbotapi.Update) {
    if update.Message != nil && update.Message.From != nil {
    	log.Printf("Received update from: %s\n", update.Message.From)
    }
}

func main() {
    h := chain.
        NewChain(
            LogTimeExecution,
        ).
        ThenFunc(chain.HandlerFunc(UpdateHandler))

    tg, _ := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_API_TOKEN"))
    updateConfig := tgbotapi.NewUpdate(0)
    updateConfig.Timeout = 60
    
    updates, _ := tg.GetUpdatesChan(updateConfig)
    
    for u := range updates {
    	h.Handle(context.Background(), u)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Chain

type Chain struct {
	// contains filtered or unexported fields
}

func NewChain

func NewChain(middlewares ...Middleware) Chain

func (Chain) Append

func (c Chain) Append(middlewares ...Middleware) Chain

func (Chain) Extend

func (c Chain) Extend(nc Chain) Chain

func (Chain) Then

func (c Chain) Then(h Handler) Handler

func (Chain) ThenFunc

func (c Chain) ThenFunc(hf HandlerFunc) Handler

type Handler

type Handler interface {
	Handle(ctx context.Context, update tgbotapi.Update)
}

type HandlerFunc

type HandlerFunc func(ctx context.Context, update tgbotapi.Update)

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(ctx context.Context, update tgbotapi.Update)

type Middleware

type Middleware func(next Handler) Handler

Jump to

Keyboard shortcuts

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