Golang bindings for the Telegram Bot API

Related tags

golang telegram
Overview

Golang bindings for the Telegram Bot API

GoDoc Travis

All methods are fairly self explanatory, and reading the godoc page should explain everything. If something isn't clear, open an issue or submit a pull request.

The scope of this project is just to provide a wrapper around the API without any additional features. There are other projects for creating something with plugins and command handlers without having to design all that yourself.

Join the development group if you want to ask questions or discuss development.

Example

First, ensure the library is installed and up to date by running go get -u github.com/go-telegram-bot-api/telegram-bot-api.

This is a very simple bot that just displays any gotten updates, then replies it to that chat.

package main

import (
	"log"

	"github.com/go-telegram-bot-api/telegram-bot-api"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message == nil { // ignore any non-Message Updates
			continue
		}

		log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

		msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
		msg.ReplyToMessageID = update.Message.MessageID

		bot.Send(msg)
	}
}

There are more examples on the wiki with detailed information on how to do many different kinds of things. It's a great place to get started on using keyboards, commands, or other kinds of reply markup.

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

package main

import (
	"log"
	"net/http"

	"github.com/go-telegram-bot-api/telegram-bot-api"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
	if err != nil {
		log.Fatal(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
	if err != nil {
		log.Fatal(err)
	}
	info, err := bot.GetWebhookInfo()
	if err != nil {
		log.Fatal(err)
	}
	if info.LastErrorDate != 0 {
		log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
	}
	updates := bot.ListenForWebhook("/" + bot.Token)
	go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

	for update := range updates {
		log.Printf("%+v\n", update)
	}
}

If you need, you may generate a self signed certficate, as this requires HTTPS / TLS. The above example tells Telegram that this is your certificate and that it should be trusted, even though it is not properly signed.

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes

Now that Let's Encrypt is available, you may wish to generate your free TLS certificate there.

Issues
  • Multi-thread safe?

    Multi-thread safe?

    Just wondering if I need to protect the bot object with a mutex when calling bot.Send() from multiple go routines. I don't think I do, but just want to be sure.

    opened by utdrmac 12
  • Panic when sending Photo by URL

    Panic when sending Photo by URL

    Trying to send a Photo by URL results in nil pointer dereference

    This is the panic:

    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x476208]
    
    goroutine 52 [running]:
    panic(0x6224a0, 0xc42000c0d0)
            /usr/lib/go/src/runtime/panic.go:500 +0x1a1
    io.(*multiReader).Read(0xc42023c1a0, 0xc4204572e7, 0x44, 0xd19, 0x1cc, 0x0, 0x0)
            /usr/lib/go/src/io/multi.go:20 +0x98
    io/ioutil.(*nopCloser).Read(0xc42022a270, 0xc4204572e7, 0x44, 0xd19, 0x1cc, 0x0, 0x0)
            <autogenerated>:4 +0x6b
    io.(*LimitedReader).Read(0xc420376640, 0xc4204572e7, 0xd19, 0xd19, 0x1cc, 0x0, 0x0)
            /usr/lib/go/src/io/io.go:436 +0x6c
    bufio.(*Writer).ReadFrom(0xc420322f80, 0x75f9e0, 0xc420376640, 0xc4200fcbb8, 0x1, 0x18)
            /usr/lib/go/src/bufio/bufio.go:693 +0xcc
    io.copyBuffer(0x75f660, 0xc420322f80, 0x75f9e0, 0xc420376640, 0x0, 0x0, 0x0, 0x631bc0, 0x1, 0xc420376640)
            /usr/lib/go/src/io/io.go:384 +0x323
    io.Copy(0x75f660, 0xc420322f80, 0x75f9e0, 0xc420376640, 0xf, 0xc420379100, 0x581d02)
            /usr/lib/go/src/io/io.go:360 +0x68
    net/http.(*transferWriter).WriteBody(0xc4202fa7e0, 0x75f660, 0xc420322f80, 0x2, 0x2)
            /usr/lib/go/src/net/http/transfer.go:227 +0x677
    net/http.(*Request).write(0xc4200c01e0, 0x75f660, 0xc420322f80, 0x0, 0xc420365890, 0x0, 0x0, 0x0)
            /usr/lib/go/src/net/http/request.go:565 +0x778
    net/http.(*persistConn).writeLoop(0xc420474300)
            /usr/lib/go/src/net/http/transport.go:1649 +0x1ac
    created by net/http.(*Transport).dialConn
            /usr/lib/go/src/net/http/transport.go:1063 +0x50e
    exit status 2
    

    This is my code:

    package main
    
    import (
            "log"
            "github.com/go-telegram-bot-api/telegram-bot-api"
            "net/url"
    )
    
    func main() {
            bot, err := tgbotapi.NewBotAPI("pls enter some token here")
            if err != nil {
                    log.Panic(err)
            }
            bot.Debug = true
            log.Printf("Authorized on account %s", bot.Self.UserName)
    
            u := tgbotapi.NewUpdate(0)
            u.Timeout = 60
            updates, err := bot.GetUpdatesChan(u)
    
            url_ptr, _ := url.Parse("https://assets-cdn.github.com/images/modules/site/home-ill-platform.png")
            url := *url_ptr
    
            for update := range updates {
                    if update.Message == nil {
                            continue
                    }
                    log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
                    msg := tgbotapi.NewPhotoUpload(update.Message.Chat.ID, url)
                    bot.Send(msg);
            }
    }
    

    The panic is caused by this line: https://github.com/go-telegram-bot-api/telegram-bot-api/blob/99170e2de436c1be90d2ef23dcf533b55a973e56/bot.go#L171

    The panic only happens when sending a Photo via URL, if NewPhotoUpload is called with file path, no panic happens and the Photo is sent correctly.

    question 
    opened by teamalpha5441 10
  • BUTTON_TYPE_INVALID

    BUTTON_TYPE_INVALID

    Bad Request: BUTTON_TYPE_INVALID if I try remove InlineKeyboard in message by this code:

    edit := tgbotapi.NewEditMessageReplyMarkup(
        callback.Message.Chat.ID,
        callback.Message.MessageID,
        tgbotapi.InlineKeyboardMarkup{},
    )
    bot.Send(edit)
    

    P.S.: Also, as and with this variant:

    var markup tgbotapi.InlineKeyboardMarkup
    edit := tgbotapi.NewEditMessageText(
        callback.Message.Chat.ID,
        callback.Message.MessageID,
        "sample text",
    )
    edit.ReplyMarkup = &markup
    bot.Send(edit)
    
    opened by toby3d 10
  • EditMessageMedia - Added Edit using Upload

    EditMessageMedia - Added Edit using Upload

    Edit Message Media Added

    opened by aliforever 9
  • Hi, there not really PR, but new vision of tgbotapi with new API

    Hi, there not really PR, but new vision of tgbotapi with new API

    Many refactorings and DRYing, all Send* functions replaces with one Send(), Some other small changes. Tests added, 85% coverage. Everything works. Travis added.

    Please, check my code. I know, that public API is changed, but it's really useful. It will be great if it possible to merge my code to upstream, but i can rename project and develop it as my own.

    Package Syfaro/telegram-bot-api in my fork changed to zhulik/telegram-bot-api. I will change it back if you will merge my code.

    Thanks!

    ps: I want to develop some Bot framework based on it, with commands support, sessions, middlewares and so on

    opened by zhulik 8
  • err:invalid character '<' looking for beginning of value

    err:invalid character '<' looking for beginning of value

    Sometimes i see this error in logs. Is it 400/500 error from telegram server?

    enhancement question 
    opened by recoilme 8
  • Provide users with more customization when creating a new bot.

    Provide users with more customization when creating a new bot.

    User are now able to create a bot with debug enabled by default.

    The debug part is use full when NewBotAPI() is failing with the message

    [email protected]    | 2018/11/12 12:15:38 created msg
    [email protected]    | 2018/11/12 12:15:38 getting bot
    [email protected]    | 2018/11/12 12:15:38 error is about to happen
    [email protected]    | 2018/11/12 12:15:38 Not Found (this one 🤷🏾‍♂️)
    

    By being able to enale debug when creating the bot user are able to debug the following code:

    		b, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_BOT_TOKEN"))
    
    		if err != nil {
    			log.Print("error is about to happen")
    			log.Fatal(err)
    		}
    
    opened by OGKevin 8
  • cannot access some methods when using with go.mod

    cannot access some methods when using with go.mod

    It works fine when not using go.mod

    my go.mod

    module github.com/phanirithvij/stickerbot
    
    go 1.13
    
    require (
    	github.com/cavaliercoder/grab v2.0.0+incompatible
    	github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible
    	github.com/spf13/viper v1.6.3
    	github.com/technoweenie/multipartstreamer v1.0.1 // indirect
    )
    

    my go.sum file

    //...
    github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU=
    github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM=
    

    Code:

    //...
    config := tgbotapi.GetStickerSetConfig{Name: stickerSet}
    data, err := bot.GetStickerSet(config)
    //...
    

    Error:

    # command-line-arguments
    .\bot.go:76:14: undefined: tgbotapi.GetStickerSetConfig
    .\bot.go:77:20: bot.GetStickerSet undefined (type *tgbotapi.BotAPI has no field or method GetStickerSet)
    
    opened by phanirithvij 8
  • More flexible logging options

    More flexible logging options

    At the moment this library does not allow a developer to replace the golang default log package to capture logs to redirect to say syslog as is common with services.

    This is mainly apparent in the UpdatesChan goroutine when an error occurs during the poll.

    opened by nvx 7
  • implement a feature that allows stopping the update loop of the bot

    implement a feature that allows stopping the update loop of the bot

    This is a PR following the improvement proposal I've posted in issue #84

    The code in the PR implements an option to stop the update loop that is generated on a call to GetUpdatesChan

    opened by sandler31 7
  • Update params.go

    Update params.go

    opened by snxx-lppxx 0
  • running multiple bots

    running multiple bots

    Discussed in https://github.com/go-telegram-bot-api/telegram-bot-api/discussions/462

    Originally posted by sSimuSs July 6, 2021 Hello, is it possible to run multiple bots? Thank you) (with the same domain and port)

    opened by sSimuSs 0
  • Updates for Bot API 5.3

    Updates for Bot API 5.3

    • Adds scope and language_code to setMyCommands and getMyCommands
    • Adds deleteMyCommands
    • Adds input_field_placeholder to ReplyKeyboardMarkup and ForceReply

    Things still needing consideration:

    • ChatMember was split into multiple classes, how should this be reflected in the library?
    • kickChatMember and getChatMembersCount were renamed to banChatMember and getChatMemberCount without plans for deprecation. Should this be changed (maybe create an alias)?
    opened by Syfaro 0
  • I'm trying to run it on my Android phone, this has error:

    I'm trying to run it on my Android phone, this has error: "read: connection refused"

    Equipment: Xiaomi Application: termux

    I tried compiling to run on Android phone with ARM64 and got the error in the picture. It seems that UDP cannot be used in Terminal, but I wrote a local UDP connection demo by myself, and the connection is accurate. The same code I compiled to Mac and Windows without this error

    run-153121 code-153050

    opened by QDxQKOAA 2
  • Allow providing Context and other fixes

    Allow providing Context and other fixes

    • Allow providing context.Context to basic request methods
      • Unsure how to deal with more specific methods, duplicating everything seems excessive
    • Use single Config struct for passing config information, allows setting more options before initialization
    • Rework logging to avoid global logger and use Logger set for each BotAPI instance
    • Only use accessible errors, and wrap errors where needed
    • Various other lint fixes
    opened by Syfaro 0
  • bot.StopReceivingUpdates() - repeated action

    bot.StopReceivingUpdates() - repeated action

    After entering the bot.StopReceivingUpdates() Bot processes one next update. and after starting it, it processes it, as a result, a double is obtained (for example, two clicks on the button).

    Can a bot pause receiving updates and then launch them? Now the program just closes.

    opened by sifaaa 0
  • NewBotAPIWithClient apiEndpoint string. how to use?

    NewBotAPIWithClient apiEndpoint string. how to use?

    Good day. How to use the "apiEndpoint" string in the "NewBotAPIWithClient" function, what is it for? Please add an example. Please correct the documentation. There is no such parameter in the documentation. https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#NewBotAPIWithClient thank you in advance

    opened by ozmy 3
  • add new structs and methods for Bot API 5.1

    add new structs and methods for Bot API 5.1

    • ChatMemberUpdated
    • VoiceChatStarted
    • VoiceChatEnded
    • VoiceChatParticipantsInvited
    • MessageAutoDeleteTimerChanged
    • ChatInviteLink

    new permissions

    • CanManageVoiceChats
    • CanManageChat

    new methods

    • CreateChatInviteLink
    • EditChatInviteLink
    • RevokeChatInviteLink
    opened by snaffi 5
  • Getting nil or panics when trying to call Contact struct

    Getting nil or panics when trying to call Contact struct

    	for update := range updates {
    		if update.Message == nil {
    			continue
    		}
    
    		fmt.Println("INCOMING FROM:", update.Message.Contact.PhoneNumber)
    
    	}
    

    There returns a panic from invalid memory adress, if we Changed to:

    fmt.Println("INCOMING FROM:", update.Message.Contact)
    

    We get:

    <nil>
    

    Comments about that?

    opened by TheGolurk 3
Releases(v4.6)
  • v4.6(Nov 25, 2016)

    This release adds the new features and changes from the Telegram Bot API 2.3.

    Please note that Telegram is deprecating the hide_keyboard field in favor of remove_keyboard.

    Source code(tar.gz)
    Source code(zip)
  • v4.5.1(Aug 1, 2016)

    chat_id and message_id should be sent only if there is no inline_message_id (and vice versa), according to documentation. Without this change it is impossible to edit a message by InlineMessageID, because chat_id and message_id are always presented in a query and the Telegram server tries to use them instead of InlineMessageID

    https://github.com/go-telegram-bot-api/telegram-bot-api/pull/55

    Source code(tar.gz)
    Source code(zip)
  • v4.5.0(Jul 26, 2016)

    This release adds the following new helper methods.

    • NewInlineQueryResultArticleMarkdown(id, title, messageText string)
    • NewInlineQueryResultArticleHTML(id, title, messageText string)
    • NewInlineQueryResultPhotoWithThumb(id, url, thumb string)

    It also fixes a bug where update offsets could not be negative, which is a valid value.

    Source code(tar.gz)
    Source code(zip)
  • v4.4.0(May 22, 2016)

  • v4.3.0(May 20, 2016)

  • v4.2.1(May 2, 2016)

  • v4.2.0(Apr 23, 2016)

  • v4.1.0(Apr 15, 2016)

  • v4.0.0(Apr 14, 2016)

  • v3.0.0(Mar 24, 2016)

  • v2.2.1(Feb 28, 2016)

  • v2.1.0(Jan 18, 2016)

  • v2.0.0(Jan 4, 2016)

    This version removes previously deprecated functions and values, prefixes all error constants with Err, removes a string error and replaces it with a constant, makes Message.Command return just the command without slash or bot name if specified, and removes the http.Handler returned by ListenForWebhook.

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jan 3, 2016)

    All documention is now less than 80 characters wide. Old methods now show deprecated warnings. The Values/Params/Method functions are now private. Types and configs have required and optional comments on them. Simplified some function logic.

    Source code(tar.gz)
    Source code(zip)
Owner
Golang library for the Telegram Bot API
null
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

Andrew Dunai 12 Jul 20, 2021
easy-peasy wg tg bot

wireguard-telegram-bot Simple-Dimple Telegram Bot for Wireguard VPN config generation Functionality /menu — list available commands /newkeys — create

Sergey Skaredov 12 Jun 7, 2021
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

Gleb Sinyavskiy 62 Jul 15, 2021
Slack Bot Framework

slacker Built on top of the Slack API github.com/slack-go/slack with the idea to simplify the Real-Time Messaging feature to easily create Slack Bots,

Raed Shomali 536 Jul 23, 2021
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

null 3k Jul 23, 2021
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

Ian P Badtrousers 2k Jul 22, 2021
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,

Skycoin 3 May 13, 2021
Chatto is a minimal chatbot framework in Go.

chatto Simple chatbot framework written in Go, with configurations in YAML. The aim of this project is to create very simple text-based chatbots using

Jaime Tenorio 88 Jul 12, 2021
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

Xelaj technologies 643 Jul 19, 2021
A lightweight, universal cloud drive upload tool for all platforms

简体中文 LightUploader MoeClub wrote a very good version, but unfortunately it's not open source and hasn't been updated in a while. This project is a sim

高玩梁 178 Jul 13, 2021
A golang implementation of a console-based trading bot for cryptocurrency exchanges

Golang Crypto Trading Bot A golang implementation of a console-based trading bot for cryptocurrency exchanges. Usage Download a release or directly bu

Alessandro Sanino 574 Jul 22, 2021
Kelp is a free and open-source trading bot for the Stellar DEX and 100+ centralized exchanges

Kelp Kelp is a free and open-source trading bot for the Stellar universal marketplace and for centralized exchanges such as Binance, Kraken, CoinbaseP

Stellar 714 Jul 25, 2021
The modern cryptocurrency trading bot written in Go.

bbgo A trading bot framework written in Go. The name bbgo comes from the BB8 bot in the Star Wars movie. aka Buy BitCoin Go! Current Status Features E

Yo-An Lin 329 Jul 15, 2021
A telegram bot that fetches multiple RSS cryptocurrency news feeds for sentiment analysis

Crypto News Telegram Bot A simple telegram bot that will help you stay updated on your latest crypto news This bot will help you keep track of the lat

Cha 4 May 11, 2021