Implementation for the telegram bot API
Switch branches/tags
Nothing to show
Clone or download
Permalink
Failed to load latest commit information.
cmd/tbot Change update offset type from uint64 to int64 Jun 30, 2016
examples Add inline query support May 16, 2016
scripts Add new methods May 22, 2016
telebot Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
testdata Initial commit, bot api, bot cli May 6, 2016
testutils Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
.coveralls.yml Add coverall support May 9, 2016
.gitignore Add coverall support May 9, 2016
.travis.yml Add go 1.6 support May 10, 2016
LICENSE Initial commit Apr 9, 2016
Makefile Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
README.md Add remaining Bot API 2.1 changes May 22, 2016
all_test.go Add useful helpers for testing api May 16, 2016
api.go Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
api_17.go Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
api_integration_test.go Add new methods May 22, 2016
api_internal_test.go Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
api_pre_17.go Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
api_test.go Fix go 1.7 tests, Add session middleware and DownloadFile method for api Jul 20, 2016
configs.go Add helper to set ChatID Jul 27, 2016
configs_edit.go Add inline query support May 16, 2016
configs_message.go Add Reset and GetFileID methods to Filer interface Jul 23, 2016
configs_message_test.go Add inline query support May 16, 2016
configs_test.go Add new methods May 22, 2016
constants.go Add remaining Bot API 2.1 changes May 22, 2016
errors.go Initial commit, bot api, bot cli May 6, 2016
errors_internal_test.go Update tests, add travis May 9, 2016
helpers.go Add Reset and GetFileID methods to Filer interface Jul 23, 2016
interfaces.go Remove Reset method from Filer interface Jan 15, 2017
types.go Fix bugs with offset and empty api result Jun 30, 2016
types_inline.go Add inline query support May 16, 2016
utils.go Update tests, add travis May 9, 2016
utils_test.go Update tests, add travis May 9, 2016

README.md

Telegram Bot Api GoDoc Build Status Coverage Status Go Report Card

Supported go version: 1.5, 1.6, tip

Implementation of the telegram bot API, inspired by github.com/go-telegram-bot-api/telegram-bot-api.

The main difference between telegram-bot-api and this version is supporting net/context. Also, this library handles errors more correctly at this time (telegram-bot-api v4).

Package contains:

  1. Client for telegram bot api.
  2. Bot with:
    1. Middleware support
      1. Command middleware to handle commands.
      2. Recover middleware to recover on panics.
    2. Webhook support

Get started

Get last telegram api:

go get github.com/bot-api/telegram

If you want to use telegram bot api directly:

go run ./examples/api/main.go -debug -token BOT_TOKEN

package main

import (
	"log"
	"flag"

	"github.com/bot-api/telegram"
	"golang.org/x/net/context"
)


func main() {
	token := flag.String("token", "", "telegram bot token")
	debug := flag.Bool("debug", false, "show debug information")
	flag.Parse()

	if *token == "" {
		log.Fatal("token flag required")
	}

	api := telegram.New(*token)
	api.Debug(*debug)

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

	if user, err := api.GetMe(ctx); err != nil {
		log.Panic(err)
	} else {
		log.Printf("bot info: %#v", user)
	}

	updatesCh := make(chan telegram.Update)

	go telegram.GetUpdates(ctx, api, telegram.UpdateCfg{
		Timeout: 10, 	// Timeout in seconds for long polling.
		Offset: 0, 	// Start with the oldest update
	}, updatesCh)

	for update := range updatesCh {
		log.Printf("got update from %s", update.Message.From.Username)
		if update.Message == nil {
			continue
		}
		msg := telegram.CloneMessage(update.Message, nil)
		// echo with the same message
		if _, err := api.Send(ctx, msg); err != nil {
			log.Printf("send error: %v", err)
		}
	}
}

If you want to use bot

go run ./examples/echo/main.go -debug -token BOT_TOKEN

package main
// Simple echo bot, that responses with the same message

import (
	"flag"
	"log"

	"github.com/bot-api/telegram"
	"github.com/bot-api/telegram/telebot"
	"golang.org/x/net/context"
)

func main() {
	token := flag.String("token", "", "telegram bot token")
	debug := flag.Bool("debug", false, "show debug information")
	flag.Parse()

	if *token == "" {
		log.Fatal("token flag is required")
	}

	api := telegram.New(*token)
	api.Debug(*debug)
	bot := telebot.NewWithAPI(api)
	bot.Use(telebot.Recover()) // recover if handler panic

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

	bot.HandleFunc(func(ctx context.Context) error {
		update := telebot.GetUpdate(ctx) // take update from context
		if update.Message == nil {
			return nil
		}
		api := telebot.GetAPI(ctx) // take api from context
		msg := telegram.CloneMessage(update.Message, nil)
		_, err := api.Send(ctx, msg)
		return err

	})

	// Use command middleware, that helps to work with commands
	bot.Use(telebot.Commands(map[string]telebot.Commander{
		"start": telebot.CommandFunc(
			func(ctx context.Context, arg string) error {

				api := telebot.GetAPI(ctx)
				update := telebot.GetUpdate(ctx)
				_, err := api.SendMessage(ctx,
					telegram.NewMessagef(update.Chat().ID,
						"received start with arg %s", arg,
					))
				return err
			}),
	}))


	err := bot.Serve(netCtx)
	if err != nil {
		log.Fatal(err)
	}
}

Use callback query and edit bot's message

go run ./examples/callback/main.go -debug -token BOT_TOKEN

bot.HandleFunc(func(ctx context.Context) error {
    update := telebot.GetUpdate(ctx) // take update from context
    api := telebot.GetAPI(ctx) // take api from context

    if update.CallbackQuery != nil {
        data := update.CallbackQuery.Data
        if strings.HasPrefix(data, "sex:") {
            cfg := telegram.NewEditMessageText(
                update.Chat().ID,
                update.CallbackQuery.Message.MessageID,
                fmt.Sprintf("You sex: %s", data[4:]),
            )
            api.AnswerCallbackQuery(
                ctx,
                telegram.NewAnswerCallback(
                    update.CallbackQuery.ID,
                    "Your configs changed",
                ),
            )
            _, err := api.EditMessageText(ctx, cfg)
            return err
        }
    }

    msg := telegram.NewMessage(update.Chat().ID,
        "Your sex:")
    msg.ReplyMarkup = telegram.InlineKeyboardMarkup{
        InlineKeyboard: telegram.NewVInlineKeyboard(
            "sex:",
            []string{"Female", "Male",},
            []string{"female", "male",},
        ),
    }
    _, err := api.SendMessage(ctx, msg)
    return err

})

Take a look at ./examples/ to know more how to use bot and telegram api.

TODO:

  • Handlers

  • Middleware

  • Command middleware

  • Session middleware

  • Log middleware

  • Menu middleware

  • Examples

    • Command
    • CallbackAnswer
    • Inline
    • Proxy
    • Menu
  • Add travis-ci integration

  • Add coverage badge

  • Add integration tests

  • Add gopkg version

  • Improve documentation

  • Benchmark ffjson and easyjson.

  • Add GAE example.

Supported API methods:

  • getMe
  • sendMessage
  • forwardMessage
  • sendPhoto
  • sendAudio
  • sendDocument
  • sendSticker
  • sendVideo
  • sendVoice
  • sendLocation
  • sendChatAction
  • getUserProfilePhotos
  • getUpdates
  • setWebhook
  • getFile
  • answerInlineQuery inline bots

Supported API v2 methods:

  • sendVenue
  • sendContact
  • editMessageText
  • editMessageCaption
  • editMessageReplyMarkup
  • kickChatMember
  • unbanChatMember
  • answerCallbackQuery
  • getChat
  • getChatMember
  • getChatMembersCount
  • getChatAdministrators
  • leaveChat

Supported Inline modes

  • InlineQueryResultArticle
  • InlineQueryResultAudio
  • InlineQueryResultContact
  • InlineQueryResultDocument
  • InlineQueryResultGif
  • InlineQueryResultLocation
  • InlineQueryResultMpeg4Gif
  • InlineQueryResultPhoto
  • InlineQueryResultVenue
  • InlineQueryResultVideo
  • InlineQueryResultVoice
  • InlineQueryResultCachedAudio
  • InlineQueryResultCachedDocument
  • InlineQueryResultCachedGif
  • InlineQueryResultCachedMpeg4Gif
  • InlineQueryResultCachedPhoto
  • InlineQueryResultCachedSticker
  • InlineQueryResultCachedVideo
  • InlineQueryResultCachedVoice
  • InputTextMessageContent
  • InputLocationMessageContent

Other bots: I like this handler system https://bitbucket.org/master_groosha/telegram-proxy-bot/src/07a6b57372603acae7bdb78f771be132d063b899/proxy_bot.py?fileviewer=file-view-default