tgbot

package module
v3.3.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2017 License: Apache-2.0 Imports: 13 Imported by: 0

README

go-tgbot godoc

Pure Golang telegram bot API wrapper generated from swagger definition, session-based routing and middlewares.

Usage benefits
  1. No need to learn any other library API. You will use methods with payload exactly like it presented on telegram bot API description page. With only couple trade-offs, b/c of telegram bot API is generics a bit.
  2. All models and methods are being supported. The models and methods were generated from swagger.yaml description file. So, new entities/methods could be added by describing in the YAML swagger file. This approach allows validating the description, avoid typos and develop fast.
  3. ffjson is plugged. So, it's pretty fast.
  4. context.Context based HTTP client
  5. Session-based routing, not only message text based.
Client

Client package could be used as regular go-swagger client library without using Router. There is the only single additional feature over go-swagger - a possibility to setup token by default. It solved as a custom HTTP transport. Example:

package main

import (
	"context"
	"flag"
	"log"
	"time"

	tgbot "github.com/olebedev/go-tgbot"
	"github.com/olebedev/go-tgbot/client/users"
)

var token *string

func main() {
	token = flag.String("token", "", "telegram bot token")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	api := tgbot.NewClient(ctx, *token)

	log.Println(api.Users.GetMe(nil))

	// Also, every calls could be done with given token and/or context
	ctx, cancel = context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	t := "<overwrite default token>"
	_, err := api.Users.GetMe(
		users.NewGetMeParams().
			WithContext(ctx).
			WithToken(&t),
	)

	if err != nil {
		// users.NewGetMeBadRequest()
		if e, ok := err.(*users.GetMeBadRequest); ok {
			log.Println(e.Payload.ErrorCode, e.Payload.Description)
		}
	}
}

Since swagger covers many other platforms/technologies the same libraries could be generated for them too. See the source here - swagger.yaml.

Router

The Router allows binding between kinds of updates and handlers, which are being checked via regexp. router include client API library as embedded struct. Example:

package main

import (
	"context"
	"flag"
	"log"

	tgbot "github.com/olebedev/go-tgbot"
	"github.com/olebedev/go-tgbot/client/messages"
	"github.com/olebedev/go-tgbot/models"
)

var token *string

func main() {
	token = flag.String("token", "", "telegram bot token")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r := tgbot.New(&tgbot.Options{
		Context: ctx,
		Token:   *token,
	})

	// setup global middleware
	r.Use(tgbot.Recover)

	// Bind handler
	r.Message("^/start\\sstart$", func(c *tgbot.Context) error {
		log.Println(c.Update.Message.Text)
		// send greeting message back
		message := "hi there what's up"
		resp, err := r.Messages.SendMessage(
			messages.NewSendMessageParams().WithBody(&models.SendMessageBody{
				Text:   &message,
				ChatID: c.Update.Message.Chat.ID,
			}),
		)
		if err != nil {
			return err
		}
		if resp != nil {
			log.Println(resp.Payload.Result.MessageID)
		}
		return nil
	})

	if err := r.Poll(ctx, []models.AllowedUpdate{models.AllowedUpdateMessage}); err != nil {
		log.Fatal(err)
	}
}

Default string representation of any kind of an update could be found here - session.go.

Router implements http.Handler interface to be able to serve HTTP as well. But, it's not recommended because webhooks are much much slower than polling.

Session-based routing

After many bots were developed, the one principal thing could be marked - routing need to be matched with session instead of received message text. So, we should be able to wrap the update into a string representation, to be matched with a handler. For this purpose, Router accepts a GetSession optional argument. It's a function which returns (fmt.Stringer, error), the fmt.Stringer instance will be placed as c.Session during handlers chain call. Example:

package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	tgbot "github.com/olebedev/go-tgbot"
	"github.com/olebedev/go-tgbot/models"

	"app" // you application
)

type Session struct {
	User    *app.User
	Billing *app.UserBillingInfo
	// ... etc
	Route string
}

func (s Session) String() string {
	return s.Route
}

func GetSessionFunc(u *models.Update) (fmt.Stringer, error) {
	sess, err := tgbot.GetSession(u)
	if err != nil {
		return nil, err
	}

	s := &Session{
		Route: "~" + sess.String(),
	}

	s.User, err = app.GetUserByTgID(u.Message.From.ID)
	if err != nil {
		return err
	}
	s.Billing, err = app.GetBillingByID(s.User.ID)
	if err != nil {
		return err
	}

	if !s.Billing.Active {
		s.Route = "/pay" + s.Route
	}

	return s, nil
}

func main() {
	token := flag.String("token", "", "telegram bot token")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r := tgbot.New(&tgbot.Options{
		Context:    ctx,
		Token:      *token,
		GetSession: GetSessionFunc,
	})

	// setup global middleware
	r.Use(tgbot.Recover)

	// Bind handlers
	r.Message("^/pay~.*", func(c *tgbot.Context) error {
		s := c.Session.(*Session)
		// TODO handle payment here before say hello
		return r.Route(c.Update)
	})

	r.Message("^~/start\\sstart$", func(c *tgbot.Context) error {
		log.Println(c.Update.Message.Text)
		// send greeting message back
		message := "hi there what's up"
		resp, err := r.Messages.SendMessage(
			messages.NewSendMessageParams().WithBody(&models.SendMessageBody{
				Text:   &message,
				ChatID: c.Update.Message.Chat.ID,
			}),
		)
		if err != nil {
			return err
		}
		if resp != nil {
			log.Println(resp.Payload.MessageID)
		}
		return nil
	})

	if err := r.Poll(ctx, []models.AllowedUpdate{models.AllowedUpdateMessage}); err != nil {
		log.Fatal(err)
	}
}

See the documentation for more details.

LICENSE

http://www.apache.org/licenses/LICENSE-2.0

Documentation

Index

Examples

Constants

View Source
const (
	// Kind is const to route different updates
	KindMessage rkind = 1 << iota
	KindEditedMessage
	KindChannelPost
	KindEditedChannelPost
	KindInlineQuery
	KindCallbackQuery
	KindChosenInlineResult
	KindShippingQuery
	KindPreCheckoutQuery
	KindAll rkind = (1 << iota) - 1

	DefaultPollTimeout int64 = 29
)

Variables

This section is empty.

Functions

func GetSession

func GetSession(u *models.Update) (fmt.Stringer, error)

GetSession is a default session repository. it's just extract a text from an update. Returns Stringer interface to be able to match the update.

func NewClient

func NewClient(ctx context.Context, token string) *client.TelegramBot
Example
package main

import (
	"context"
	"flag"
	"log"
	"time"

	tgbot "github.com/olebedev/go-tgbot"
	"github.com/olebedev/go-tgbot/client/users"
)

var token *string

func main() {
	token = flag.String("token", "", "telegram bot token")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	api := tgbot.NewClient(ctx, *token)

	log.Println(api.Users.GetMe(nil))

	// Also, every calls could be done with given token and/or context
	ctx, cancel = context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	t := "<overwrite default token>"
	_, err := api.Users.GetMe(
		users.NewGetMeParams().
			WithContext(ctx).
			WithToken(&t),
	)

	if err != nil {
		// users.NewGetMeBadRequest()
		if e, ok := err.(*users.GetMeBadRequest); ok {
			log.Println(e.Payload.ErrorCode, e.Payload.Description)
		}
	}
}
Output:

func Recover

func Recover(c *Context) (err error)

Types

type Context

type Context struct {
	Update  *models.Update
	Keys    map[string]interface{}
	Params  []string
	Session fmt.Stringer
	Kind    rkind
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

Abort stops chain calling.

func (*Context) FallThrough

func (c *Context) FallThrough() error

FallThrough shows that the next matched handlers should be applied.

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

Returns the value for the given key if it exists, otherwise it panics.

func (*Context) Next

func (c *Context) Next() error

Next executes the pending handlers in the chain inside the calling handler.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set is used to store a new key/value pair exclusivelly for this context. It also lazy initializes c.Keys if it was not used previously.

type Options

type Options struct {
	Context    context.Context
	Token      string
	GetSession func(*models.Update) (fmt.Stringer, error)
}

Options ... All field are optional.

type Router

type Router struct {
	*client.TelegramBot
	// contains filtered or unexported fields
}

Router ...

func New

func New(o *Options) *Router

New returns a router.

Example
package main

import (
	"context"
	"flag"
	"log"

	tgbot "github.com/olebedev/go-tgbot"
	"github.com/olebedev/go-tgbot/client/messages"
	"github.com/olebedev/go-tgbot/models"
)

var token *string

func main() {
	token = flag.String("token", "", "telegram bot token")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r := tgbot.New(&tgbot.Options{
		Context: ctx,
		Token:   *token,
	})

	// setup global middleware
	r.Use(tgbot.Recover)

	// Bind handler
	r.Message("^/start\\sstart$", func(c *tgbot.Context) error {
		log.Println(c.Update.Message.Text)
		// send greeting message back
		message := "hi there what's up"
		resp, err := r.Messages.SendMessage(
			messages.NewSendMessageParams().WithBody(&models.SendMessageBody{
				Text:   &message,
				ChatID: c.Update.Message.Chat.ID,
			}),
		)
		if err != nil {
			return err
		}
		if resp != nil {
			log.Println(resp.Payload.Result.MessageID)
		}
		return nil
	})

	if err := r.Poll(ctx, []models.AllowedUpdate{models.AllowedUpdateMessage}); err != nil {
		log.Fatal(err)
	}
}
Output:

Example (Session)
package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	tgbot "github.com/olebedev/go-tgbot"
	"github.com/olebedev/go-tgbot/client/messages"
	"github.com/olebedev/go-tgbot/models"

	"app" // you application
)

type Session struct {
	User    *app.User
	Billing *app.UserBillingInfo
	// ... etc
	Route string
}

func (s Session) String() string {
	return s.Route
}

func GetSessionFunc(u *models.Update) (fmt.Stringer, error) {
	sess, err := tgbot.GetSession(u)
	if err != nil {
		return nil, err
	}

	s := &Session{
		Route: "~" + sess.String(),
	}

	s.User, err = app.GetUserByTgID(u.Message.From.ID)
	if err != nil {
		return err
	}
	s.Billing, err = app.GetBillingByID(s.User.ID)
	if err != nil {
		return err
	}

	if !s.Billing.Active {
		s.Route = "/pay" + s.Route
	}

	return s, nil
}

func main() {
	token := flag.String("token", "", "telegram bot token")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r := tgbot.New(&tgbot.Options{
		Context:    ctx,
		Token:      *token,
		GetSession: GetSessionFunc,
	})

	// setup global middleware
	r.Use(tgbot.Recover)

	// Bind handlers
	r.Message("^/pay~.*", func(c *tgbot.Context) error {
		s := c.Session.(*Session)
		// TODO handle payment here before say hello
		return r.Route(c.Update)
	})

	r.Message("^~/start\\sstart$", func(c *tgbot.Context) error {
		log.Println(c.Update.Message.Text)
		// send greeting message back
		message := "hi there what's up"
		resp, err := r.Messages.SendMessage(
			messages.NewSendMessageParams().WithBody(&models.SendMessageBody{
				Text:   &message,
				ChatID: c.Update.Message.Chat.ID,
			}),
		)
		if err != nil {
			return err
		}
		if resp != nil {
			log.Println(resp.Payload.MessageID)
		}
		return nil
	})

	if err := r.Poll(ctx, []models.AllowedUpdate{models.AllowedUpdateMessage}); err != nil {
		log.Fatal(err)
	}
}
Output:

func (*Router) All

func (r *Router) All(route string, handlers ...func(*Context) error) error

All binds all kind of updates and the route through handler/handlers.

func (*Router) CallbackQuery

func (r *Router) CallbackQuery(route string, handlers ...func(*Context) error) error

CallbackQuery binds callback updates and the route through handler/handlers.

func (*Router) ChannelPost

func (r *Router) ChannelPost(route string, handlers ...func(*Context) error) error

ChannelPost binds message updates and the route through handler/handlers.

func (*Router) ChosenInlineResult

func (r *Router) ChosenInlineResult(route string, handlers ...func(*Context) error) error

ChosenInlineResult binds chosen inline result updates and the route through handler/handlers.

func (*Router) EditedChannelPost

func (r *Router) EditedChannelPost(route string, handlers ...func(*Context) error) error

EditedChannelPost binds message updates and the route through handler/handlers.

func (*Router) EditedMessage

func (r *Router) EditedMessage(route string, handlers ...func(*Context) error) error

EditedMessage binss message updates and the route through handler/handlers.

func (*Router) Handle

func (r *Router) Handle(kind rkind, routeRegExp string, handlers ...func(*Context) error) error

Handle binds specific kinds of an update to the handler/handlers.

func (*Router) InlineQuery

func (r *Router) InlineQuery(route string, handlers ...func(*Context) error) error

InlineQuery binds inline queries and the route through handler/handlers.

func (*Router) Message

func (r *Router) Message(route string, handlers ...func(*Context) error) error

Message binds message updates and the route through handler/handlers.

func (*Router) Poll

func (r *Router) Poll(ctx context.Context, allowed []models.AllowedUpdate) error

Poll does a polling of API endpoints and routes consumed updates. It returns an error if any of handlers return the error.

func (*Router) PreCheckout

func (r *Router) PreCheckout(route string, handlers ...func(*Context) error) error

PreCheckout binds pre-checkout result updates and the route through handler/handlers.

func (*Router) Route

func (r *Router) Route(u *models.Update) error

Route routes given updates into the bound handlers through defined middlewares.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.ServeHTTP interface.

func (*Router) ShippingQuery

func (r *Router) ShippingQuery(route string, handlers ...func(*Context) error) error

ShippingQuery binds shipping result updates and the route through handler/handlers.

func (*Router) Use

func (r *Router) Use(middlewares ...func(*Context) error)

Use appends given middlewares into call chain.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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