🤖 Telegram Bot API on Go

Telegraphist

GoDoc Telegraphist CI status Go Report Card GitHub tag (latest SemVer) GitHub

Telegram Bot API on Go. API v4.4 (29 July 2019) is supported. All methods and types represent their alter ego from Telegram Bot API so you would expect what you see in the official documentation. And you don't need to study the new API to use this library.

Documentation

Installation

go get -u github.com/xamut/telegraphist

Usage

package main

import (
	"encoding/json"
	"fmt"
	"os"

	Telegraphist "github.com/xamut/telegraphist"
	Telegram "github.com/xamut/telegraphist/telegram"
)

func printResp(resp interface{}, err error) {
	if err != nil {
		fmt.Println(err)
	}
	respAsJSON, _ := json.MarshalIndent(resp, "", "\t")
	fmt.Println(string(respAsJSON))
}

func main() {
	telegraphist, err := Telegraphist.NewClient(&Telegraphist.ClientConfig{
		BotToken: "YOUR_BOT_TOKEN",
	})

	if err != nil {
		fmt.Println(err)
	}

	printResp(telegraphist.GetMe()) // Simple method to obtain basic bot info
					// https://core.telegram.org/bots/api#getme
					// Returns an User struct

	chatID := int64(<YOUR_CHAT_ID>)
	printResp(telegraphist.SendMessage(&Telegram.SendMessageParams{ // Send a text message to a chat
		ChatID: chatID,  				        // https://core.telegram.org/bots/api#sendmessage
		Text:   "Hello there!", 				// Returns a Message struct
	}))

	photo, _ := os.Open("<PATH_TO_PHOTO>")
	printResp(telegraphist.SendPhoto(&Telegram.SendPhotoParams{ // Send a photo to a chat
		ChatID:  chatID,              			    // https://core.telegram.org/bots/api#sendphoto
		Photo:   photo,					    // Returns a Message struct
		Caption: "Just a nice photo",
	}))
}

Getting updates

Webhook

  • Find your IP
curl ifconfig.co
  • Use nip.io to pretend you have a domain, for example, "app.X.X.X.X.nip.io"

  • Generate a certificate, replace X.X.X.X with your IP:

openssl req -newkey rsa:2048 \
  -new -nodes -x509 \
  -days 3650 \
  -out cert.pem \
  -keyout key.pem \
  -subj "/O=Organization/CN=app.X.X.X.X.nip.io"
  • Run server
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/url"
	"os"
	"path"

	Telegraphist "github.com/xamut/telegraphist"
	Telegram "github.com/xamut/telegraphist/telegram"
)

func combineURL(host string, parts ...string) string {
	baseURL, err := url.Parse(host)
	if err != nil {
		log.Fatal(err)
	}
	parts = append([]string{baseURL.Path}, parts...)
	baseURL.Path = path.Join(parts...)

	return baseURL.String()
}

func main() {
	telegraphist, err := Telegraphist.NewClient(&Telegraphist.ClientConfig{
		BotToken: "<YOUR_BOT_TOKEN>",
	})

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

	host := "https://app.X.X.X.X.nip.io" // For example: "https://example.com"
	webhookPath := "<YOUR_WEBHOOK_PATH>" // For example: "/telegram_webhook"

	cert, _ := os.Open("./cert.pem")
	ok, err := telegraphist.SetWebhook(&Telegram.SetWebhookParams{
		URL:         combineURL(host, webhookPath),
		Certificate: cert,
	})

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

	if !ok {
		log.Println("Something went wrong and the webhook wasn't set up")
	}

	handlers := map[string]func(update Telegram.Update) error{
		// "message":              func(update Telegram.Update) error {},
		// "edited_message":       func(update Telegram.Update) error {},
		// "channel_post":         func(update Telegram.Update) error {},
		// "edited_channel_post":  func(update Telegram.Update) error {},
		// "inline_query":         func(update Telegram.Update) error {},
		// "chosen_inline_result": func(update Telegram.Update) error {},
		// "callback_query":       func(update Telegram.Update) error {},
		// "shipping_query":       func(update Telegram.Update) error {},
		// "pre_checkout_query":   func(update Telegram.Update) error {},
		// "poll":                 func(update Telegram.Update) error {},
		"always": func(update Telegram.Update) error {
			js, _ := json.MarshalIndent(update, "", "\t")
			fmt.Println(string(js))
			return nil
		},
	}

	err = Telegraphist.NewServer(&Telegraphist.ServerConfig{
		EnableHTTPS: true,
		Webhook:     webhookPath,
	}, &handlers)

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

NOTE: Use this example only for testing purposes, for production use something like nginx or traefik to serve HTTPS (and/or to (re)generate Let's Encrypt certificate).

License

Telegraphist is released under the MIT License.

Owner
Ilya Manin
Software Engineer
Ilya Manin
Similar Resources

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

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

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

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

Golang Based Account Generator Telegram Bot

Account Generator Bot Account Generator Bot, written in GoLang via gotgbot library. Variables Env Vars - BOT_TOKEN - Get it from @BotFather CHANNEL_ID

Nov 21, 2022
Comments
  • " when using telegraphist.SendPhoto">

    "\\u003cb..." (unicode) instead of "<>" when using telegraphist.SendPhoto

    Hello,

    when I use this...

    		printResp(telegraphist.SendPhoto(&Telegram.SendPhotoParams{
    			ChatID:    chatID,
    			Photo:     p,
    			ParseMode: "HTML",
    			Caption:   "<b>test</b>",
    		}))
    

    ...I get this output:

    {
    	"message_id": xxx,
    	"from": {
    		"id": xxx,
    		"is_bot": true,
    		"first_name": "xxxr",
    		"username": "xxx"
    	},
    	"date": xxx,
    	"chat": {
    		"id": xxx,
    		"type": "private",
    		"username": "xxx",
    		"first_name": "xxx"
    	},
    	"photo": [
    		{
    			"file_id": "xxx",
    			"width": 320,
    			"height": 320,
    			"file_size": 18490
    		},
    		{
    			"file_id": "xxx",
    			"width": 461,
    			"height": 461,
    			"file_size": 32722
    		}
    	],
    	**"caption": "\\u003cb\\u003etest\\u003c/b\\u003e"**
    }
    reply sent
    

    Note the "caption": "\u003cb\u003etest\u003c/b\u003e"; "<" and ">" is somehow converted into unicode (while "äöü" are submitted correctly).

    This issue doesn't occur when using...

    printResp(telegraphist.SendMessage(&Telegram.SendMessageParams{
    			ChatID:    chatID,
    			ParseMode: "HTML",
    			Text:      "<b>test</b>",
    		}))
    

    ...here the output is...

    {
    	"message_id": xxx,
    	"from": {
    		"id": xxx,
    		"is_bot": true,
    		"first_name": "xxx",
    		"username": "xxx"
    	},
    	"date": xxx,
    	"chat": {
    		"id": xxx,
    		"type": "xxx",
    		"username": "xxx",
    		"first_name": "xxx"
    	},
    	**"text": "test",**
    	"entities": [
    		{
    			"type": "bold",
    			"offset": 0,
    			"length": 4
    		}
    	]
    }
    

    ...it's perfectly fine and bold as it should be.

    I'd be very happy if you could help! Thank you.

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
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
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