Concurrent library for Telegram Bots written in pure go.

echotron


logo

Language PkgGoDev Go Report Card License Build Status Coverage Status Mentioned in Awesome Go Telegram

Echotron is a concurrent library for telegram bots written in pure Go.

Fetch with

go get github.com/NicoNex/echotron/v3

Design

Echotron is heavily based on concurrency: for example, every call to the Update method of each bot is executed on a different goroutine. This makes sure that, even if one instance of the bot is deadlocked, the other ones keep running just fine, making the bot work for other users without any issues and/or slowdowns.

Echotron is designed to be as similar to the official Telegram API as possible, but there are some things to take into account before starting to work with this library.

  • The methods have the exact same name, but with a capital first letter, since in Go methods have to start with a capital letter to be exported. Example: sendMessage becomes SendMessage
  • The order of the parameters in some methods is different than in the official Telegram API, so refer to the docs for the correct one.
  • The only chat_id (or, in this case, chatID) type supported is int64, instead of the "Integer or String" requirement of the official API. That's because numeric IDs can't change in any way, which isn't the case with text-based usernames.
  • In some methods, you might find a InputFile type parameter. InputFile is a struct with unexported fields, since only three combination of fields are valid, which can be obtained through the methods NewInputFileID, NewInputFilePath and NewInputFileBytes.
  • In some methods, you might find a MessageIDOptions type parameter. MessageIDOptions is another struct with unexported fields, since only two combination of field are valid, which can be obtained through the methods NewMessageID and NewInlineMessageID.
  • Optional parameters can be added by passing the correct struct to each method that might request optional parameters. If you don't want to pass any optional parameter, nil is more than enough. Refer to the docs to check for each method's optional parameters struct: it's the type of the opts parameter.
  • Some parameters are hardcoded to avoid putting random stuff which isn't recognized by the Telegram API. Some notable examples are ParseMode, ChatAction and InlineQueryType. For a full list of custom hardcoded parameters, refer to the docs for each custom type: by clicking on the type's name, you'll get the source which contains the possible values for that type.

Usage

Long Polling

A very simple implementation:

package main

import (
    "log"

    "github.com/NicoNex/echotron/v3"
)

type bot struct {
    chatID int64
    echotron.API
}

const token = "YOUR TELEGRAM TOKEN"

func newBot(chatID int64) echotron.Bot {
    return &bot{
        chatID,
        echotron.NewAPI(token),
    }
}

func (b *bot) Update(update *echotron.Update) {
    if update.Message.Text == "/start" {
        b.SendMessage("Hello world", b.chatID, nil)
    }
}

func main() {
    dsp := echotron.NewDispatcher(token, newBot)
    log.Println(dsp.Poll())
}

Proof of concept with self destruction for low RAM usage:

package main

import (
    "log"
    "time"

    "github.com/NicoNex/echotron/v3"
)

type bot struct {
    chatID int64
    echotron.API
}

const token = "YOUR TELEGRAM TOKEN"

var dsp echotron.Dispatcher

func newBot(chatID int64) echotron.Bot {
    var bot = &bot{
        chatID,
        echotron.NewAPI(token),
    }
    go bot.selfDestruct(time.After(time.Hour))
    return bot
}

func (b *bot) selfDestruct(timech <- chan time.Time) {
    select {
    case <-timech:
        b.SendMessage("goodbye", b.chatID, nil)
        dsp.DelSession(b.chatID)
    }
}

func (b *bot) Update(update *echotron.Update) {
    if update.Message.Text == "/start" {
        b.SendMessage("Hello world", b.chatId, nil)
    }
}

func main() {
    dsp := echotron.NewDispatcher(token, newBot)
    log.Println(dsp.Poll())
}

Webhook

package main

import "github.com/NicoNex/echotron/v3"

type bot struct {
	chatID int64
	echotron.API
}

const token = "YOUR TELEGRAM TOKEN"

func newBot(chatID int64) echotron.Bot {
	return &bot{
		chatID,
		echotron.NewAPI(token),
	}
}

func (b *bot) Update(update *echotron.Update) {
	if update.Message.Text == "/start" {
		b.SendMessage("Hello world", b.chatID, nil)
	}
}

func main() {
	dsp := echotron.NewDispatcher(token, newBot)
	dsp.ListenWebhook("https://example.com:443/my_bot_token")
}

Webhook with a custom http.Server

This is an example for a custom http.Server which handles your own specified routes and also the webhook route which is specified by ListenWebhook.

package main

import (
	"github.com/NicoNex/echotron/v3"
	
	"context"
	"log"
	"net/http"
)

type bot struct {
	chatID int64
	echotron.API
}

const token = "YOUR TELEGRAM TOKEN"

func newBot(chatID int64) echotron.Bot {
	return &bot{
		chatID,
		echotron.NewAPI(token),
	}
}

func (b *bot) Update(update *echotron.Update) {
	if update.Message.Text == "/start" {
		b.SendMessage("Hello world", b.chatID, nil)
	}
}

func main() {
	termChan := make(chan os.Signal, 1) // Channel for terminating the app via os.Interrupt signal
	signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)

	mux := http.NewServeMux()
	mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		// Handle user login
	})
	mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		// Handle user logout
	})
	mux.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
		// Tell something about your awesome telegram bot
	})

	// Set custom http.Server
	server := &http.Server{Addr: ":8080", Handler: mux}

	go func() {
		<-termChan
		// Perform some cleanup..
		if err := server.Shutdown(context.Background()); err != nil {
			log.Print(err)
		}
	}()

	// Capture the interrupt signal for app termination handling
	dsp := echotron.NewDispatcher(token, newBot)
	dsp.SetHTTPServer(server)
	// Start your custom http.Server with a registered /my_bot_token handler.
	log.Println(dsp.ListenWebhook("https://example.com/my_bot_token"))
}
Owner
Nicolò Santamaria
PhD in printf debugging.
Nicolò Santamaria
Comments
  • Feature/set custom httpserver

    Feature/set custom httpserver

    Hi @NicoNex,

    I was wondering if it will be better to pass a pointer to an http.Server instead of the http.Handler because then, the user of the your library has more control and can for example, initiate a gracefully server shutdown by himself. I know that this will bring braking changes, and I'm sad that I don't came up earlier with this idea, but maybe you can consider the change for the next major version. Thanks in advance.

  • Add GetWebhookHandler method

    Add GetWebhookHandler method

    Hi Nicolò, thanks for your awesome echotron package. I extracted your handle function for the webhook into a separate function, so that I can handle it within my own http server. Maybe it's useful for others as well.

  • move mutex unlock before bot update goroutine

    move mutex unlock before bot update goroutine

    Hello! I am new to Go and currently learning it by reading the source code. I love coding async bots on Python and now want to do almost the same with goroutines. I spot that mutex unlock call is after goroutine, isn't it bad? If it isn't, can you explain me why? Thanks for the library!

  • Error to json marshal MessageEntity

    Error to json marshal MessageEntity

    Looks like misprint, all json fields are in lower case https://core.telegram.org/bots/api#messageentity. Type 'MessageEntity' has error in Length field types.go:278: Length int `json:"Length"`

  • Update Telegram Bot API 5.4

    Update Telegram Bot API 5.4

    You might want to change ChatInviteLinkOption since member_limit and creates_join_request cannot be specified together https://core.telegram.org/bots/api#createchatinvitelink

  • Refactor: proper handling of media

    Refactor: proper handling of media

    Properly handle thumbnails in the various send* methods that require a Thumb (type InputFile) object and in the new method SendMediaGroup. Also, properly handle media in the EditMessageMedia method.

  • Fixed listen() method and Added new API methods

    Fixed listen() method and Added new API methods

    Fixed an important bug in listen() method which made unable to handle Callback Queries Added SendPhotoWithKeyboard method Added EditMessageReplyMarkup method Added EditMessageText method Added AnswerCallbackQuery method Added Data field to CallbackQuery type

  • Webhook implementation

    Webhook implementation

    Here is a webhook implementation. It is not totally completed at the moment, because it lacks of a way to use an SSL/TLS certficate directly.

    README.md now includes an example using webhooks.

  • Webhook implementation

    Webhook implementation

    Here is a Webhook mode implementation. It is not fully complete at the moment, because it lacks of a way to send an SSL/TLS certificate directly.

    README.md now includes a new Webhook example.

  • Webhook implementation

    Webhook implementation

    This is my webhook implementation. It's not totally complete at the moment, since it lacks of the way to supply SSL/TLS certificate directly.

    I updated the README with a new Webhook example.

  • Avoid running this in another goroutine.

    Avoid running this in another goroutine.

    https://github.com/NicoNex/echotron/blob/309c5b5659c6028d584b5d513217f40a46610596/timer.go#L83

    Avoid running the callback in a different goroutine because the call is already at the end of the parent goroutine.

A Telegram Repo For Bots Under Maintenance Which Gives Faster Response To Users
A Telegram Repo For Bots Under Maintenance Which Gives Faster Response To Users

Maintenance Bot A Telegram Repo For Bots Under Maintenance Which Gives Faster Response To Users Requests » Report a Bug | Request Feature Table of Con

Mar 21, 2022
A set of mastodon (fediverse) bots written in Go

Mastodon Bot Bots Hagh Hagh reblogs certain toots to itself creating a Hagh page. Users from local instance are able to make a toot hagh. Setup Have g

Sep 17, 2021
A fast responsive, machine learning, conversational dialog engine for creating chat bots, written in Go.

chatbot English | 简体中文 项目说明 chatbot 是一个通过已知对话数据集快速生成回答的 Go 问答引擎。比 ChatterBot 快非常多,我们在1.2亿对话上的对比结果是:ChatterBot 回答需要21秒,chatbot 只需要18毫秒。 bot 问答引擎 cli tr

Jan 6, 2023
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
Dlercloud-telegram-bot - A Telegram bot for managing your Dler Cloud account

Dler Cloud Telegram Bot A Telegram bot for managing your Dler Cloud account. Usa

Dec 30, 2021
Pro-bot - A telegram bot to play around with the community telegram channels

pro-bot ?? Pro Bot A Telegram Bot to Play Around With The Community Telegram Cha

Jan 24, 2022
Golang Framework for writing Slack bots

hanu - Go for Slack Bots! The Go framework hanu is your best friend to create Slack bots! hanu uses allot for easy command and request parsing (e.g. w

Oct 24, 2022
its the same idea as bruh-bot, but with golang, and add more bots
its the same idea as bruh-bot, but with golang, and add more bots

bruh-bot but more powerful! requirements python go you can used on mac and linux the idea its really simple, can make a lot of bots with the same task

Jul 7, 2021
HellPot is a portal to endless suffering meant to punish unruly HTTP bots.
HellPot is a portal to endless suffering meant to punish unruly HTTP bots.

HellPot Summary HellPot is an endless honeypot based on Heffalump that sends unruly HTTP bots to hell. Notably it implements a toml configuration file

Jan 2, 2023
Automated Trader (at). Framework for building trading bots.
Automated Trader (at). Framework for building trading bots.

Automated Trader (at) Purpose: Framework for building automated trading strategies in three steps: Build your own strategy. Verify it with the backtes

Dec 14, 2022
Make discord bots to drain discriminators

allthebotses make discord bots to drain discriminators a stupid idea You can only make ~5 bots before getting ratelimited, and it gets tougher every t

Dec 12, 2021
Telegram bot written in Golang using gotgbot library

go_tgbot Telegram bot written in Golang using gotgbot library. How to run go get -u github.com/itsLuuke/go_tgbot rename sample.env to .env and fill in

Nov 4, 2022
Library for working with golang telegram client + bot based on tdlib. This library was taken from the user Arman92 and changed for the current version of tdlib.

go-tdlib Golang Telegram TdLib JSON bindings Install To install, you need to run inside a docker container (it is given below) go get -u github.com/ka

Dec 2, 2022
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
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
Fancy, fully-featured, easy to use Telegram CAPTCHA bot written in Go
Fancy, fully-featured, easy to use Telegram CAPTCHA bot written in Go

Go Telegram Captcha Bot Fancy, fully-featured, easy to use, scalable Telegram CAPTCHA bot written in Go based on tucnak's telebot this robot only has

Jul 18, 2022
YouTube downloader bot for Telegram written in the Go programming language

ytdGoBot YouTube downloader bot for Telegram written in the Go programming language. For now it only downloads audio content from a provided YouTube l

Apr 15, 2022
RaspChecker - A Telegram bot that allows you to monitor your Raspberry Pi's temperature and shut it down. Written in Golang.

RaspChecker Remotely monitor your Raspberry Pi's temperature and shut it down if you want. All through Telegram. How to set up In order to run the bot

Jan 2, 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