Telegram - Implementation for the telegram bot API

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

Comments
  • Fix description of MessageCfg.ParseMode

    Fix description of MessageCfg.ParseMode

    It seems that Telegram changed their API a little bit and both old options currently return an error. New options are correct one. Details: https://core.telegram.org/bots/api

  • Api for deleting a post by bot

    Api for deleting a post by bot

    Hi. I'm going to build a telegram bot for my website. When I create a new post in my website, the bot will send the post to my telegram channel directly. There is some api for doing this.

    But I want this functionality, when I delete a post in my site, bot would be able to delete the post in the channel. I searched, but found nothing. Will be such a api for doing this?

  • Ability to split a message if it's too big to send in one piece

    Ability to split a message if it's too big to send in one piece

    If a message is larger than 4096 bytes telegram API doesn't accept it. I added an api call that split big messages like that to smaller pieces and them send them one by one. Every time we try to split the text by whitespace symbols if it's possible. Otherwise we simply cut a word as soon as it's size is greater than allowed size.

  • invalid character '<' looking for beginning of value

    invalid character '<' looking for beginning of value

    When I leave my bot (based on the boilerplate of the example echo bot) on e.g. overnight, it goes like this:

    2017/12/06 02:21:54 api.go:38: response map[data:<html>
    <head><title>502 Bad Gateway</title></head>
    <body bgcolor="white">
    <center><h1>502 Bad Gateway</h1></center>
    <hr><center>nginx/1.12.2</center>
    </body>
    </html>
    ]
    2017/12/06 02:21:54 langbot.go:74: invalid character '<' looking for beginning of value
    

    The main bot loop is:

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

    I guess my bot could ignore this error, and enter the loop again. But is it the way it's supposed to work? If it couldn't access Telegram, it would continue crashlooping forever.

    P.S. I mistakenly submitted this earlier to go-telegram-bot-api/telegram-bot-api#118.

  • send html message error

    send html message error

    html : <a>xxx</a> mycode:

    msg := telegram.NewMessagef(update.Chat().ID, newListStr, arg)
    msg.ParseMode = telegram.MarkdownMode
    _, err := api.SendMessage(ctx, msg)
    

    error

    response map[data:{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities in message text: Unexpected end of name token at byte offset 8"}]
    
  • Implement new game API in a bot

    Implement new game API in a bot

    https://core.telegram.org/bots/games

    https://core.telegram.org/bots/api

    New tools for building HTML5 games.
    New method sendGame, new object InlineQueryResultGame, new field game in Message.
    New parameter url in answerCallbackQuery. Create a game and accept the conditions using Botfather to send custom urls that open your games for the user.
    New field callback_game in InlineKeyboardButton, new fields game_short_name and chat_instance in CallbackQuery, new object CallbackGame.
    New methods setGameScore and getGameHighScores.
    Other changes
    
    Making life easier for webhook users. Added a detailed Guide to All Things Webhook that describes every pothole you can run into on the webhook road.
    New method getWebhookInfo to check current webhook status.
    
    Added the option to specify an HTTP URL for a file in all methods where InputFile or file_id can be used. Telegram will get the file from the specified URL and send it to the user. Files must be smaller than 5 MB for photos and smaller than 20 MB for all other types of content.
    
    Use the new url parameter in answerCallbackQuery to create buttons that open your bot with user-specific parameters.
    Added new field switch_inline_query_current_chat in InlineKeyboardButton.
    Added caption fields to sendAudio, sendVoice, InlineQueryResultAudio, InlineQueryResultVoice, InlineQueryResultCachedAudio, and InlineQueryResultCachedVoice.
    New field all_members_are_admins in the Chat object.
    Certain server responses may now contain the new parameters field with expanded info on errors that occurred while processing your requests.
    
Telego is Telegram Bot API library for Golang with full API implementation (one-to-one)
Telego is Telegram Bot API library for Golang with full API implementation (one-to-one)

Telego • Go Telegram Bot API Telego is Telegram Bot API library for Golang with full API implementation (one-to-one) The goal of this library was to c

Jan 5, 2023
A bot based on Telegram Bot API written in Golang allows users to download public Instagram photos, videos, and albums without receiving the user's credentials.

InstagramRobot InstagramRobot is a bot based on Telegram Bot API written in Golang that allows users to download public Instagram photos, videos, and

Dec 16, 2021
Bot - Telegram Music Bot in Go

Telegram Music Bot in Go An example bot using gotgcalls. Setup Install the serve

Jun 28, 2022
Bot-template - A simple bot template for creating a bot which includes a config, postgresql database

bot-template This is a simple bot template for creating a bot which includes a c

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

go-tgbot Pure Golang telegram bot API wrapper generated from swagger definition, session-based routing and middlewares. Usage benefits No need to lear

Nov 16, 2022
Client lib for Telegram bot api

Micha Client lib for Telegram bot api. Supports Bot API v2.3.1 (of 4th Dec 2016). Simple echo bot example: package main import ( "log" "git

Nov 10, 2022
Go library for Telegram Bot API
Go library for Telegram Bot API

tbot - Telegram Bot Server Features Full Telegram Bot API 4.7 support Zero dependency Type-safe API client with functional options Capture messages by

Nov 30, 2022
Golang bindings for the Telegram Bot API

Golang bindings for the Telegram Bot API All methods are fairly self explanatory, and reading the godoc page should explain everything. If something i

Jan 6, 2023
Bot that polls activity API for Github organisation and pushes updates to Telegram.

git-telegram-bot Telegram bot for notifying org events Requirements (for building) Go version 1.16.x Setup If you don't have a telegram bot token yet,

Apr 8, 2022
Flexible message router add-on for go-telegram-bot-api library.
Flexible message router add-on for go-telegram-bot-api library.

telemux Flexible message router add-on for go-telegram-bot-api library. Table of contents Motivation Features Minimal example Documentation Changelog

Oct 24, 2022
WIP Telegram Bot API server in Go

botapi The telegram-bot-api, but in go. WIP. Reference: https://core.telegram.org/bots/api Reference implementation: https://github.com/tdlib/telegram

Jan 2, 2023
Golang bindings for the Telegram Bot API

Golang bindings for the Telegram Bot API All methods are fairly self explanatory, and reading the godoc page should explain everything. If something i

Nov 18, 2021
UcodeQrTelebot ver2 - Easy way to get QR and U-code using Utopia API in telegram bot
UcodeQrTelebot ver2 - Easy way to get QR and U-code using Utopia API in telegram bot

UcodeQrTelebot Easy way to get QR and U-code using Utopia API in telegram bot Us

Dec 30, 2021
Quote-bot - Un bot utilisant l'API Twitter pour tweeter une citation par jour sur la programmation et les mathématiques.

Description Ceci est un simple bot programmé en Golang qui tweet une citation sur la programmation tout les jours. Ce bot est host sur le compte Twitt

Jan 1, 2022
The serverless OTP telegram service use telegram as OTP service, and send OTP through webhook

Setup OTP First thing, you need prepare API(webhook) with POST method, the payload format as below { "first_name": "Nolan", "last_name": "Nguyen",

Jul 24, 2022
Full-native go implementation of Telegram API
Full-native go implementation of Telegram API

MTProto Full-native implementation of MTProto protocol on Golang! english русский 简体中文 Features Full native implementation All code, from sending requ

Jan 1, 2023
IRC, Slack, Telegram and RocketChat bot written in go
IRC, Slack, Telegram and RocketChat bot written in go

go-bot IRC, Slack & Telegram bot written in Go using go-ircevent for IRC connectivity, nlopes/slack for Slack and Syfaro/telegram-bot-api for Telegram

Dec 20, 2022
Telegram Bot Framework for Go

Margelet Telegram Bot Framework for Go is based on telegram-bot-api It uses Redis to store it's states, configs and so on. Any low-level interactions

Dec 22, 2022
Telebot is a Telegram bot framework in Go.

Telebot "I never knew creating Telegram bots could be so sexy!" go get -u gopkg.in/tucnak/telebot.v2 Overview Getting Started Poller Commands Files Se

Dec 30, 2022