• Stars
    star
    117
  • Rank 301,828 (Top 6 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang telegram bot API wrapper, session-based router and middleware

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. easyjson is plugged. So, it's 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 are the only two additional features over go-swagger, a possibility to setup token by default(It solved as an interface checking) and API throttling for 30 calls per second(see more info).

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 context
	ctx, cancel = context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	_, err := api.Users.GetMe(
		users.NewGetMeParams().
			WithContext(ctx),
	)

	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.
Also, have a look at Swagger UI for telegram API(master branch).

Router

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

package main

import (
	"context"
	"flag"
	"log"
	"os"

	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(ctx, *token)

	// setup global middleware
	r.Use(tgbot.Recover)
	r.Use(tgbot.Logger(os.Stdout))

	// modify path to be able to match user's commands via router
	r.Use(func(c *tgbot.Context) error {
		c.Path = c.Path + c.Text
		return nil
	})

	// bind handler
	r.Bind(`^/message/(?:.*)/text/start(?:\s(.*))?$`, func(c *tgbot.Context) error {
		log.Println(c.Capture)             // - ^ from path
		log.Println(c.Update.Message.Text) // or c.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.AllowedUpdateMessage); err != nil {
		log.Fatal(err)
	}
}

Default string representation of any kind of an update could be found here - router.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.

More examples can be found at godoc.


See the documentation for more details.

LICENSE

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

More Repositories

1

go-starter-kit

[abandoned] Golang isomorphic react/hot reloadable/redux/css-modules/SSR starter kit
Go
2,826
star
2

when

A natural language date/time parser with pluggable rules
Go
1,328
star
3

go-duktape

[abandoned] Duktape JavaScript engine bindings for Go
Go
777
star
4

emitter

Emits events in Go way, with wildcard, predicates, cancellation possibilities and many other good wins
Go
483
star
5

config

JSON or YAML configuration wrapper with convenient access methods.
Go
266
star
6

cdn

[abandoned] Content Delivery Network on the top of MongoDb GridFs with on-the-fly image crop/resize
Go
132
star
7

srlt

Simple tool for save and restore states of all existing repositories on the given path
Go
53
star
8

staticbin

Gin middleware/handler for serving static files from binary data
Go
43
star
9

hook-to-trello

Github & Bitbucket web hooks handler for Trello
LiveScript
28
star
10

gojax

A set of extensions for goja javascript engine
Go
27
star
11

swarm

A CRDT-backed reactive real-time data with no merge conflicts, with offline mode. For business-critical data-driven apps on intermittently connected devices.
JavaScript
27
star
12

go-gamp

Google Analytics Measurement Protocol in Golang
Go
16
star
13

gin-cache

Tiny and simple cache middleware for gin framework
Go
15
star
14

rest

REST interface over MongoDB, as middlware for martini framework.
Go
14
star
15

go-duktape-fetch

Server side fetch polyfill for go-duktape
Go
12
star
16

on

CLI for fsnotify
Go
8
star
17

chat

SwarmDB Example Chat Application
JavaScript
4
star
18

node-mystem

Node.js wrapper for `MyStem` morphology text analyzer by Yandex.ru
LiveScript
4
star
19

todo

SwarmDB Example TodoMVC Application. Demo 👉
JavaScript
3
star
20

pinentry-mac-keychain

A pinentry program for macOs that stores entered PINs in the macOS KeyChain. Convenient when use with smart cards, like Yubikey
Go
2
star
21

var

tool to fill in json/yaml stdin stream from the environment variables
Go
2
star
22

t2s

Text-To-Speech tool for Russian language, written in Golang
Go
1
star
23

pickle.js

JavaScript implementation of the Python pickle format. Fork.
JavaScript
1
star
24

dotfiles

$HOME sweet home
Vim Script
1
star
25

mice

SwarmDB Example Mice Application
JavaScript
1
star
26

go-googl

A Golang library for https://goo.gl URL shortener API
Go
1
star