margelet

package module
v0.0.0-...-5c7768c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2016 License: MIT Imports: 6 Imported by: 0

README

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.

Note: margelet is in early beta now. Any advices and suggestions are welcome

Installation

go get https://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)
    }

    bot.Run()
}

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:

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

// Response send message back to author
func (handler EchoHandler) HandleMessage(bot margelet.MargeletAPI, message tgbotapi.Message) error {
	_, err := bot.Send(tgbotapi.NewMessage(message.Chat.ID, 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:

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

// Handle sends default help message
func (handler HelpHandler) HandleCommand(bot MargeletAPI, message tgbotapi.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 := bot.Send(tgbotapi.NewMessage(message.Chat.ID, 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:

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

// HandleResponse - Handlers user response
func (session SumSession) HandleResponse(bot MargeletAPI, message tgbotapi.Message, responses []tgbotapi.Message) (bool, error) {
	var msg tgbotapi.MessageConfig
	switch len(responses) {
	case 0:
		msg = tgbotapi.MessageConfig{Text: "Hello, please, write one number per message, after some iterations write 'end'."}
		msg.ReplyMarkup = tgbotapi.ForceReply{true, true}
	default:
		if message.Text == "end" {
			var sum int
			for _, m := range responses {
				n, _ := strconv.Atoi(m.Text)
				sum += n
			}
			msg = tgbotapi.MessageConfig{Text: fmt.Sprintf("Your sum: %d", sum)}
			session.response(bot, message, msg)
			msg.ReplyMarkup = tgbotapi.ForceReply{false, true}
			return true, nil
		}

		_, err := strconv.Atoi(message.Text)
		if err != nil {
			msg = tgbotapi.MessageConfig{Text: "Sorry, not a number"}
			session.response(bot, message, msg)
			msg.ReplyMarkup = tgbotapi.ForceReply{true, true}
			return false, err
		}
	}

	session.response(bot, message, msg)
	return false, nil
}

// CancelResponse - Chance to clean up everything
func (session SumSession) CancelSession(bot MargeletAPI, message tgbotapi.Message, responses []tgbotapi.Message){
  //Clean up all variables only used in the session

}

func (session SumSession) response(bot MargeletAPI, message tgbotapi.Message, msg tgbotapi.MessageConfig) {
	msg.ChatID = message.Chat.ID
	msg.ReplyToMessageID = message.MessageID
	bot.Send(msg)
}

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

Command 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.v2"
)

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()
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.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthorizationPolicy

type AuthorizationPolicy interface {
	Allow(message tgbotapi.Message) error
}

AuthorizationPolicy - interface, that describes authorization policy for command or session

type ChatConfigRepository

type ChatConfigRepository struct {
	// contains filtered or unexported fields
}

ChatConfigRepository - repository for chat configs

func (*ChatConfigRepository) Get

func (chatConfig *ChatConfigRepository) Get(chatID int) string

Get - returns config for chatID

func (*ChatConfigRepository) GetWithStruct

func (chatConfig *ChatConfigRepository) GetWithStruct(chatID int, obj interface{})

GetWithStruct - returns config for chatID using a struct

func (*ChatConfigRepository) Remove

func (chatConfig *ChatConfigRepository) Remove(chatID int)

Remove - removes config for chatID

func (*ChatConfigRepository) Set

func (chatConfig *ChatConfigRepository) Set(chatID int, JSON string)

Set - stores any config for chatID

func (*ChatConfigRepository) SetWithStruct

func (chatConfig *ChatConfigRepository) SetWithStruct(chatID int, obj interface{})

SetWithStruct - stores any config for chatID using a struct

type CommandHandler

type CommandHandler interface {
	HandleCommand(bot MargeletAPI, message tgbotapi.Message) error
	HelpMessage() string
}

CommandHandler - interface for command handlers

type HelpHandler

type HelpHandler struct {
	Margelet *Margelet
}

HelpHandler Default handler for /help command. Margelet will add this automatically

func (HelpHandler) HandleCommand

func (handler HelpHandler) HandleCommand(bot MargeletAPI, message tgbotapi.Message) error

HandleCommand sends default help message

func (HelpHandler) HelpMessage

func (handler HelpHandler) HelpMessage() string

HelpMessage return help string for HelpHandler

type InlineHandler

type InlineHandler interface {
	HandleInline(bot MargeletAPI, query tgbotapi.InlineQuery) error
}

InlineHandler - interface for message handlers

type Margelet

type Margelet struct {
	MessageHandlers []MessageHandler
	CommandHandlers map[string]authorizedCommandHandler
	SessionHandlers map[string]authorizedSessionHandler
	InlineHandler   InlineHandler

	Redis                *redis.Client
	ChatRepository       *chatRepository
	SessionRepository    SessionRepository
	ChatConfigRepository *ChatConfigRepository
	// contains filtered or unexported fields
}

Margelet - main struct in package, handles all interactions

Example
package main

import (
	"../margelet"

	"gopkg.in/telegram-bot-api.v2"
)

type BotMock struct {
	Updates chan tgbotapi.Update
}

func (bot BotMock) Send(c tgbotapi.Chattable) (tgbotapi.Message, error) {
	return tgbotapi.Message{}, nil
}

func (bot BotMock) AnswerInlineQuery(config tgbotapi.InlineConfig) (tgbotapi.APIResponse, error) {
	return tgbotapi.APIResponse{}, nil
}

func (bot BotMock) GetFileDirectURL(fileID string) (string, error) {
	return "https://example.com/test.txt", nil
}

func (bot BotMock) IsMessageToMe(message tgbotapi.Message) bool {
	return false
}

func (bot BotMock) GetUpdatesChan(config tgbotapi.UpdateConfig) (<-chan tgbotapi.Update, error) {
	return bot.Updates, nil
}

var (
	botMock = BotMock{}
)

func getMargelet() *margelet.Margelet {
	botMock.Updates = make(chan tgbotapi.Update, 10)
	m, _ := margelet.NewMargeletFromBot("test", "127.0.0.1:6379", "", 10, &botMock)

	m.Redis.FlushDb()
	return m
}

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

	if err != nil {
		panic(err)
	}

	bot.Run()
}
Output:

func NewMargelet

func NewMargelet(botName string, redisAddr string, redisPassword string, redisDB int64, token string, verbose bool) (*Margelet, error)

NewMargelet creates new Margelet instance

func NewMargeletFromBot

func NewMargeletFromBot(botName string, redisAddr string, redisPassword string, redisDB int64, bot TGBotAPI) (*Margelet, error)

NewMargeletFromBot creates new Margelet instance from existing TGBotAPI(tgbotapi.BotAPI)

func (*Margelet) AddCommandHandler

func (margelet *Margelet) AddCommandHandler(command string, handler CommandHandler, auth ...AuthorizationPolicy)

AddCommandHandler - adds new CommandHandler to Margelet

func (*Margelet) AddMessageHandler

func (margelet *Margelet) AddMessageHandler(handler MessageHandler)

AddMessageHandler - adds new MessageHandler to Margelet

func (*Margelet) AddSessionHandler

func (margelet *Margelet) AddSessionHandler(command string, handler SessionHandler, auth ...AuthorizationPolicy)

AddSessionHandler - adds new SessionHandler to Margelet

func (*Margelet) AnswerInlineQuery

func (margelet *Margelet) AnswerInlineQuery(config tgbotapi.InlineConfig) (tgbotapi.APIResponse, error)

AnswerInlineQuery - send answer to InlineQuery

func (*Margelet) GetConfigRepository

func (margelet *Margelet) GetConfigRepository() *ChatConfigRepository

GetConfigRepository - returns chat config repository

func (*Margelet) GetFileDirectURL

func (margelet *Margelet) GetFileDirectURL(fileID string) (string, error)

GetFileDirectURL - converts fileID to direct URL

func (*Margelet) GetRedis

func (margelet *Margelet) GetRedis() *redis.Client

GetRedis - returns margelet's redis client

func (*Margelet) GetSessionRepository

func (margelet *Margelet) GetSessionRepository() SessionRepository

GetSessionRepository - returns session repository

func (*Margelet) HandleSession

func (margelet *Margelet) HandleSession(message tgbotapi.Message, command string)

HandleSession - handles any message as session message with handler

func (*Margelet) IsMessageToMe

func (margelet *Margelet) IsMessageToMe(message tgbotapi.Message) bool

IsMessageToMe - return true if message sent to this bot

func (*Margelet) QuickReply

func (margelet *Margelet) QuickReply(chatID, messageID int, message string) (tgbotapi.Message, error)

QuickReply - quick send text reply to message

func (*Margelet) QuickSend

func (margelet *Margelet) QuickSend(chatID int, message string) (tgbotapi.Message, error)

QuickSend - quick send text message to chatID

func (*Margelet) Run

func (margelet *Margelet) Run() error

Run - starts message processing loop

func (*Margelet) Send

func (margelet *Margelet) Send(c tgbotapi.Chattable) (tgbotapi.Message, error)

Send - send message to Telegram

func (*Margelet) Stop

func (margelet *Margelet) Stop()

Stop - stops message processing loop

type MargeletAPI

type MargeletAPI interface {
	Send(c tgbotapi.Chattable) (tgbotapi.Message, error)
	AnswerInlineQuery(config tgbotapi.InlineConfig) (tgbotapi.APIResponse, error)
	QuickSend(chatID int, message string) (tgbotapi.Message, error)
	QuickReply(chatID, messageID int, message string) (tgbotapi.Message, error)
	GetFileDirectURL(fileID string) (string, error)
	IsMessageToMe(message tgbotapi.Message) bool
	GetConfigRepository() *ChatConfigRepository
	GetSessionRepository() SessionRepository
	GetRedis() *redis.Client
	HandleSession(message tgbotapi.Message, command string)
}

MargeletAPI - interface, that describes margelet API

type MessageHandler

type MessageHandler interface {
	HandleMessage(bot MargeletAPI, message tgbotapi.Message) error
}

MessageHandler - interface for message handlers

type SessionHandler

type SessionHandler interface {
	HandleSession(bot MargeletAPI, message tgbotapi.Message, responses []tgbotapi.Message) (bool, error)
	CancelSession(bot MargeletAPI, message tgbotapi.Message, responses []tgbotapi.Message)
	HelpMessage() string
}

SessionHandler - interface for session handlers

type SessionRepository

type SessionRepository interface {
	Create(chatID int, userID int, command string)
	Add(chatID int, userID int, message tgbotapi.Message)
	Remove(chatID int, userID int)
	Command(chatID int, userID int) string
	Dialog(chatID int, userID int) (messages []tgbotapi.Message)
}

SessionRepository - public interface for session repository

type TGBotAPI

type TGBotAPI interface {
	Send(c tgbotapi.Chattable) (tgbotapi.Message, error)
	AnswerInlineQuery(config tgbotapi.InlineConfig) (tgbotapi.APIResponse, error)
	GetFileDirectURL(fileID string) (string, error)
	IsMessageToMe(message tgbotapi.Message) bool
	GetUpdatesChan(config tgbotapi.UpdateConfig) (<-chan tgbotapi.Update, error)
}

TGBotAPI - interface, that describe telegram-bot-api API

type UsernameAuthorizationPolicy

type UsernameAuthorizationPolicy struct {
	Usernames []string
}

UsernameAuthorizationPolicy - simple authorization policy, that checks sender's username

func (UsernameAuthorizationPolicy) Allow

func (p UsernameAuthorizationPolicy) Allow(message tgbotapi.Message) error

Allow check message author's username and returns nil if it in Usernames otherwise, returns an authorization error message

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL