Categorygithub.com/bot-api/telegram
modulepackage
0.0.0-20170115211335-b7abf87c449e
Repository: https://github.com/bot-api/telegram.git
Documentation: pkg.go.dev

# README

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

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

CloneMessage convert message to Messenger type to send it to another chat.
GetUpdates runs loop and requests updates from telegram.
IsAPIError checks if error is ApiError.
IsForbiddenError checks if error is forbidden.
IsRequiredError checks if error is RequiredError.
IsUnauthorizedError checks if error is unauthorized.
IsValidationError checks if error is ValidationError.
IsValidToken returns true if token is a valid telegram bot token Token format is like: 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq.
New returns API instance with default http client.
NewAnswerCallback creates a new callback message.
NewAnswerCallbackWithAlert creates a new callback message that alerts the user.
NewBytesFile takes byte slice and returns InputFile.
NewChatAction sets a chat action.
NewEditMessageCaption allows you to edit the caption of a message.
NewEditMessageReplyMarkup allows you to edit the inline keyboard markup.
NewEditMessageText allows you to edit the text of a message.
NewForwardMessage creates a new Message.
NewHInlineKeyboard creates inline keyboard with horizontal buttons only.
NewHKeyboard creates keyboard with horizontal buttons only.
NewInlineQueryResultArticle creates a new inline query article.
NewInputFile takes Reader object and returns InputFile.
NewKeyboard creates keyboard by matrix i*j.
NewLocation shares your location.
NewMessage creates a new Message.
NewMessagef creates a new Message with formatting.
NewPhotoShare creates a new photo uploader.
NewPhotoUpload creates a new photo uploader.
NewRequiredError creates RequireError.
NewUpdate gets updates since the last Offset with Timeout 30 seconds offset is the last Update ID to include.
NewUserProfilePhotos gets user profile photos.
NewValidationError creates ValidationError.
NewVInlineKeyboard creates inline keyboard with vertical buttons only [ first ] [ second ] [ third ].
NewVKeyboard creates keyboard with vertical buttons only [ first ] [ second ] [ third ].
NewWebhook creates a new webhook.
NewWebhookWithCert creates a new webhook with a certificate.
NewWithClient returns API instance with custom http client.

# Constants

Type of action to broadcast.
Type of action to broadcast.
Type of action to broadcast.
Type of action to broadcast.
Type of action to broadcast.
Type of action to broadcast.
Type of action to broadcast.
Type of action to broadcast.
ChatMember possible statuses.
APIEndpoint is the endpoint for all API methods, with formatting for Sprintf.
bold text.
EntityType constants helps to set type of entity in MessageEntity object.
Type of chat.
monowidth string.
ChatMember possible statuses.
EntityType constants helps to set type of entity in MessageEntity object.
FileEndpoint is the endpoint for downloading a file from Telegram.
Type of chat.
EntityType constants helps to set type of entity in MessageEntity object.
Constant values for ParseMode in MessageCfg.
italic text.
ChatMember possible statuses.
ChatMember possible statuses.
Constant values for ParseMode in MessageCfg.
ChatMember possible statuses.
@username.
monowidth block.
Type of chat.
Type of chat.
for clickable text URLs.
for users without usernames.
EntityType constants helps to set type of entity in MessageEntity object.

# Variables

DefaultDebugFunc prints debug message to default logger.

# Structs

AnswerCallbackCfg contains information on making a anserCallbackQuery response.
AnswerInlineQueryCfg contains information on making an InlineQuery response.
API implements Telegram bot API described on https://core.telegram.org/bots/api.
APIError contains error information from response.
APIResponse is a response from the Telegram API with the result stored raw.
Audio object represents an audio file to be treated as music by the Telegram clients.
AudioCfg contains information about a SendAudio request.
BaseChat describes chat settings.
BaseEdit is base type of all chat edits.
BaseFile describes file settings.
BaseInlineQueryResult is a base class for InlineQueryResult.
BaseMessage is a base type for all message config types.
CallbackQuery represents an incoming callback query from a callback button in an inline keyboard.
Chat object represents a Telegram user, bot or group chat.
ChatActionCfg contains information about a SendChatAction request.
ChatMember object contains information about one member of the chat.
ChosenInlineResult represents a result of an inline query that was chosen by the user and sent to their chat partner.
Contact object represents a phone contact of Telegram user.
ContactCfg contains information about a SendContact request.
Document object represents a general file (as opposed to Photo or Audio).
DocumentCfg contains information about a SendDocument request.
EditMessageCaptionCfg allows you to modify the caption of a message.
EditMessageReplyMarkupCfg allows you to modify the reply markup of a message.
EditMessageTextCfg allows you to modify the text in a message.
EditResult is an option type, because telegram may return bool or Message.
File object represents any sort of file.
FileCfg has information about a file hosted on Telegram.
ForceReply allows the Bot to have users directly reply to it without additional interaction.
ForwardMessageCfg contains information about a ForwardMessage request.
GetChatAdministratorsCfg contains information about a getChat request.
GetChatCfg contains information about a getChat request.
GetChatMemberCfg contains information about a getChatMember request.
GetChatMembersCountCfg contains information about a getChatMemberCount request.
InlineKeyboardButton object represents one button of an inline keyboard.
InlineKeyboardMarkup object represents an inline keyboard that appears right next to the message it belongs to.
InlineQuery is an incoming inline query.
InlineQueryResultArticle is an inline query response article.
InlineQueryResultAudio is an inline query response audio.
InlineQueryResultContact represents a contact with a phone number.
InlineQueryResultDocument is an inline query response document.
InlineQueryResultGIF is an inline query response GIF.
InlineQueryResultLocation is an inline query response location.
InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF.
InlineQueryResultPhoto is an inline query response photo.
InlineQueryResultVenue represents a venue.
InlineQueryResultVideo is an inline query response video.
InlineQueryResultVoice is an inline query response voice.
InlineThumb struct helps to describe thumbnail.
InputContactMessageContent contains a contact for displaying as an inline query result.
InputLocationMessageContent contains a location for displaying as an inline query result.
InputTextMessageContent represents the content of a text message to be sent as the result of an inline query.
InputVenueMessageContent contains a venue for displaying as an inline query result.
KeyboardButton object represents one button of the reply keyboard.
KickChatMemberCfg contains information about a kickChatMember request.
LeaveChatCfg contains information about a leaveChat request.
Location object represents geographic position.
LocationCfg contains information about a SendLocation request.
A MarkInlineQueryResult implements InlineQueryResult interface.
A MarkInputMessageContent implements InputMessageContent interface.
A MarkReplyMarkup implements ReplyMarkup interface.
MeCfg contains information about a getMe request.
Message object represents a message.
MessageCfg contains information about a SendMessage request.
MessageEntity object represents one special entity in a text message.
MetaFile represents meta information about file.
PhotoCfg contains information about a SendPhoto request.
PhotoSize object represents one size of a photo or a file / sticker thumbnail.
ReplyKeyboardHide tells Telegram clients to hide the current custom keyboard and display the default letter-keyboard.
ReplyKeyboardMarkup represents a custom keyboard with reply options.
RequiredError tells if fields are required but were not filled.
Size object represent size information.
Sticker object represents a WebP image, so-called sticker.
StickerCfg contains information about a SendSticker request.
UnbanChatMemberCfg contains information about a unbanChatMember request.
Update object represents an incoming update.
UpdateCfg contains information about a getUpdates request.
User object represents a Telegram user or bot.
UserProfilePhotos contains a set of user profile pictures.
UserProfilePhotosCfg contains information about a GetUserProfilePhotos request.
ValidationError tells if field has wrong value.
Venue object represents a venue.
VenueCfg contains information about a SendVenue request.
Video object represents an MP4-encoded video.
VideoCfg contains information about a SendVideo request.
Voice object represents a voice note.
VoiceCfg contains information about a SendVoice request.
WebhookCfg contains information about a SetWebhook request.

# Interfaces

Filer is any config type that can be sent that includes a file.
HTTPDoer interface helps to test api.
InlineQueryResult interface represents one result of an inline query.
InputFile describes interface for input files.
InputMessageContent interface represents the content of a message to be sent as a result of an inline query.
Messenger is a virtual interface to distinct methods that return Message from others.BaseMessage.
Method describes interface for Telegram API request Every method is https://api.telegram.org/bot<token>/METHOD_NAME Values are passed as application/x-www-form-urlencoded for usual request and multipart/form-data when files are uploaded.
ReplyMarkup describes interface for reply_markup keyboards.

# Type aliases

DebugFunc describes function for debugging.