Telegram Bot Framework for Go

Related tags

margelet
Overview

Build Status

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 with Telegram Bot API(downloading files, keyboards and so on) should be performed through telegram-bot-api.

Margelet is just a thin layer, that allows you to solve basic bot tasks quickly and easy.

Installation

go get github.com/zhulik/margelet

Simple usage

package main

import (
	"github.com/zhulik/margelet"
)

func main() {
	bot, err := margelet.NewMargelet("<your awesome bot name>", "<redis addr>", "<redis password>", 0, "your bot token", false)

	if err != nil {
		panic(err)
	}

	err = bot.Run()
	if err != nil {
		panic(err)
	}
}

Out of the box, margelet supports only /help command, it responds something like this

/help - Show bot help

Concept

Margelet is based on some concepts:

  • Message handlers
  • Command handlers
  • Session handlers
  • Chat configs
  • Inline handlers

Message handlers

Message handler is a struct that implements Handler interface. It receives all chat messages dependant on bot's Privacy mode. It doesn't receive commands.

Simple example:

package margelet_test

import (
	"../margelet"
)

// EchoHandler is simple handler example
type EchoHandler struct {
}

// Response send message back to author
func (handler EchoHandler) HandleMessage(m margelet.Message) error {
	_, err := m.QuickSend(m.Message().Text)
	return err
}

This handler will repeat any user's message back to chat.

Message helpers can be added to margelet with AddMessageHandler function:

bot, err := margelet.NewMargelet("<your awesome bot name>", "<redis addr>", "<redis password>", 0, "your bot token", false)
bot.AddMessageHandler(EchoHandler{})
bot.Run()

Command handlers

Command handler is struct that implements CommandHandler interface. CommandHandler can be subscribed on any command you need and will receive all message messages with this command, only if there is no active session with this user in this chat

Simple example:

package margelet

import (
	"fmt"
	"strings"
)

// HelpHandler Default handler for /help command. Margelet will add this automatically
type HelpHandler struct {
	Margelet *Margelet
}

// HandleCommand sends default help message
func (handler HelpHandler) HandleCommand(message Message) error {
	lines := []string{}
	for command, h := range handler.Margelet.CommandHandlers {
		lines = append(lines, fmt.Sprintf("/%s - %s", command, h.handler.HelpMessage()))
	}

	for command, h := range handler.Margelet.SessionHandlers {
		lines = append(lines, fmt.Sprintf("/%s - %s", command, h.handler.HelpMessage()))
	}

	_, err := message.QuickSend(strings.Join(lines, "\n"))
	return err
}

// HelpMessage return help string for HelpHandler
func (handler HelpHandler) HelpMessage() string {
	return "Show bot help"
}

Command handlers can be added to margelet with AddCommandHandler function:

bot, err := margelet.NewMargelet("<your awesome bot name>", "<redis addr>", "<redis password>", 0, "your bot token", false)
bot.AddCommandHandler("help", HelpHandler{bot})
bot.Run()

Session handlers

Session here is an interactive dialog with user, like @BotFather does. User runs session with a command and then response to bot's questions until bot collects all needed information. It can be used for bot configuration, for example.

Session handlers API is still developing

Session handler is struct that implements SessionHandler interface. Simple example:

package margelet_test

import (
	"fmt"
	"strconv"

	"../margelet"
	"gopkg.in/telegram-bot-api.v4"
)

// SumSession - simple example session, that can sum numbers
type SumSession struct {
}

// HandleResponse - Handlers user response
func (s SumSession) HandleSession(session margelet.Session) error {
	switch len(session.Responses()) {
	case 0:
		session.QuickReply("Hello, please, write one number per message, after some iterations write 'end'.")
	default:
		if session.Message().Text == "end" {
			var sum int
			for _, m := range session.Responses() {
				n, _ := strconv.Atoi(m.Text)
				sum += n
			}
			session.QuickReply(fmt.Sprintf("Your sum: %d", sum))
			session.Finish()
			return nil
		}

		_, err := strconv.Atoi(session.Message().Text)
		if err != nil {
			session.QuickReply("Sorry, not a number")
			return err
		}
	}

	return nil
}

// CancelResponse - Chance to clean up everything
func (s SumSession) CancelSession(session margelet.Session) {
	//Clean up all variables only used in the session

}

func (session SumSession) response(bot margelet.MargeletAPI, message *tgbotapi.Message, msg tgbotapi.MessageConfig) {
	msg.ChatID = message.Chat.ID
	msg.ReplyToMessageID = message.MessageID
	msg.ReplyMarkup = tgbotapi.ForceReply{ForceReply: true, Selective: true}
	bot.Send(msg)
}

// HelpMessage return help string for SumSession
func (session SumSession) HelpMessage() string {
	return "Sum your numbers and print result"
}

Session handlers can be added to margelet with AddSessionHandler function:

bot, err := margelet.NewMargelet("<your awesome bot name>", "<redis addr>", "<redis password>", 0, "your bot token", false)
bot.AddSessionHandler("help", SumSession{})
bot.Run()

On each user response it receives all previous user responses, so you can restore session state. HandleResponse return values it important:

  • first(bool), means that margelet should finish session, so return true if you receive all needed info from user, false otherwise
  • second(err), means that bot cannot handle user's message. This message will not be added to session dialog history. Return any error if you can handle user's message and return nil if message is accepted.

Inline handlers

Inline handler is struct that implements InlineHandler interface. InlineHandler can be subscribed on any inline queries.

Simple example:

package margelet_test

import (
	"github.com/zhulik/margelet"
	"gopkg.in/telegram-bot-api.v4"
)

type InlineImage struct {
}

func (handler InlineImage) HandleInline(bot margelet.MargeletAPI, query *tgbotapi.InlineQuery) error {
	testPhotoQuery := tgbotapi.NewInlineQueryResultPhoto(query.ID, "https://telegram.org/img/t_logo.png")
	testPhotoQuery.ThumbURL = "https://telegram.org/img/t_logo.png"

	config := tgbotapi.InlineConfig{
		InlineQueryID: query.ID,
		CacheTime:     2,
		IsPersonal:    false,
		Results:       []interface{}{testPhotoQuery},
		NextOffset:    "",
	}

	bot.AnswerInlineQuery(config)
	return nil
}

Inline handler can be added to margelet by InlineHandler assignment:

bot, err := margelet.NewMargelet("<your awesome bot name>", "<redis addr>", "<redis password>", 0, "your bot token", false)
m.InlineHandler = &InlineImage{}
bot.Run()

Callback handlers

Callback handler is struct that implements CallbackHandler interface. CallbackHandler can be subscribed on any callback queries.

Simple example:

package margelet_test

import (
	"../margelet"
	"gopkg.in/telegram-bot-api.v4"
)

type CallbackMessage struct {
}

func (handler CallbackMessage) HandleCallback(query margelet.CallbackQuery) error {
	config := tgbotapi.CallbackConfig{
		CallbackQueryID: query.Query().ID,
		Text:            "Done!",
		ShowAlert:       false,
	}

	query.Bot().AnswerCallbackQuery(config)
	return nil
}

Callback handler can be added to margelet by CallbackHandler assignment:

bot, err := margelet.NewMargelet("<your awesome bot name>", "<redis addr>", "<redis password>", 0, "your bot token", false)
m.CallbackHandler = &CallbackMessage{}
bot.Run()

Chat configs

Bots can store any config string(you can use serialized JSON) for any chat. It can be used for storing user's configurations and other user-related information. Simple example:

bot, err := margelet.NewMargelet("<your awesome bot name>", "<redis addr>", "<redis password>", 0, "your bot token", false)
...
bot.GetConfigRepository().Set(<chatID>, "<info>")
...
info := bot.GetConfigRepository().Get(<chatID>)

OR

type userInfo struct{
  FavColor string // First character has to be Capital otherwise it wont be saved
}
...
user := userInfo{FavColor: "Green"}
bot.GetConfigRepository().SetWithStruct(<chatID>, user)
...
var user userInfo
bot.GetConfigRepository().GetWithStruct(<chatID>, &user)

Chat config repository can be accessed from session handlers.

Example project

Simple and clean example project can be found here. It provides command handling and session configuration.

Issues
  • message.Command() Changed?

    message.Command() Changed?

    margelet.AddCommandHandler("/cat", CatHandler{})
    margelet.AddSessionHandler("/start", ConfigSessionHandler{})
    

    Should be changed to

    margelet.AddCommandHandler("cat", CatHandler{})
    margelet.AddSessionHandler("start", ConfigSessionHandler{})
    

    because message.Command() seems to return just the command without "/"

    opened by Mrcrypt 3
  • Fixed SessionHandler

    Fixed SessionHandler

    We want to use the command var because we want to get the sessionhandler from the active session and not the current command.

    opened by Mrcrypt 3
  • some README.md changes

    some README.md changes

    Few style changes in ReadMe.md file.

    opened by degiz 1
  • Update tgbotapi to v3.

    Update tgbotapi to v3.

    Telegram Chat IDs for supergroups may overflow an int, as they can reach values from -1e13 to 1e13 according to the Telegram documentation.

    This PR updates margelet to use tgbotapi v3 which uses int64 Chat IDs instead.

    opened by Syfaro 1
  • fix help_handler

    fix help_handler

    Исправляет поведение подсвечивая команды в диалоге справки.

    до-после.

    help-handler-update

    opened by xboston 1
  • May be use

    May be use ":" as redis namespace delimiter?

    Docs: http://redis.io/topics/data-types-intro#redis-keys

    Try to stick with a schema. For instance "object-type:id" is a good idea, as in "user:1000". Dots or dashes are often used for multi-word fields, as in "comment: 1234:reply.to" or "comment:1234:reply-to".

    https://github.com/resque/redis-namespace

    namespaced_redis.set('foo', 'bar') # redis_connection.set('ns:foo', 'bar')

    Example: 2016-04-21 01 07 50

    opened by xboston 1
  • Add callback query handler

    Add callback query handler

    Based on InlineHandler:

    type CallbackMessage struct {
    }
    
    func (handler CallbackMessage) HandleCallback(bot margelet.MargeletAPI, query *tgbotapi.CallbackQuery) error {
    
        config := tgbotapi.CallbackConfig{
            CallbackQueryID: query.ID,
            Text:            "Done!",
            ShowAlert:       false,
        }
    
        bot.AnswerCallbackQuery(config)
        return nil
    }
    
    opened by xboston 0
  • Fix readme

    Fix readme

    Replace space to tabs, update example

    opened by xboston 0
Owner
Gleb Sinyavskiy
Gleb Sinyavskiy
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
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 331 Jul 24, 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
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