margelet

package module
v0.0.0-...-7685d04 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2016 License: MIT Imports: 11 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.

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.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMessage

func NewMessage(bot MargeletAPI, msg *tgbotapi.Message) *message

NewMessage returns message, that wraps bot and message

Types

type AuthorizationPolicy

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

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

type CallbackHandler

type CallbackHandler interface {
	HandleCallback(query CallbackQuery) error
}

CallbackHandler - interface for message handlers

type CallbackQuery

type CallbackQuery interface {
	Message
	Query() *tgbotapi.CallbackQuery
	Data() string
}

type ChatConfigRepository

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

ChatConfigRepository - repository for chat configs

func (*ChatConfigRepository) Exists

func (chatConfig *ChatConfigRepository) Exists(chatID int64) bool

Exists - returns if key exists for chatID

func (*ChatConfigRepository) Get

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

Get - returns config for chatID

func (*ChatConfigRepository) GetWithStruct

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

GetWithStruct - returns config for chatID using a struct

func (*ChatConfigRepository) Remove

func (chatConfig *ChatConfigRepository) Remove(chatID int64)

Remove - removes config for chatID

func (*ChatConfigRepository) Set

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

Set - stores any config for chatID

func (*ChatConfigRepository) SetWithStruct

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

SetWithStruct - stores any config for chatID using a struct

type ChatRepository

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

ChatRepository - repository for started chats

func (*ChatRepository) Add

func (chat *ChatRepository) Add(id int64)

func (*ChatRepository) All

func (chat *ChatRepository) All() []int64

func (*ChatRepository) Exist

func (chat *ChatRepository) Exist(id int64) (res bool)

func (*ChatRepository) Remove

func (chat *ChatRepository) Remove(id int64)

type CommandHandler

type CommandHandler interface {
	HandleCommand(msg 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(message 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 {
	RecoverCallback       RecoverCallback
	ReceiveCallback       ReceiveCallback
	SendCallback          SendCallback
	MessageHandlers       []MessageHandler
	CommandHandlers       map[string]authorizedCommandHandler
	UnknownCommandHandler *authorizedCommandHandler
	SessionHandlers       map[string]authorizedSessionHandler
	InlineHandler         InlineHandler
	CallbackHandler       CallbackHandler

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

Margelet - main struct in package, handles all interactions

Example
package main

import (
	"net/url"

	"../margelet"

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

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) AnswerCallbackQuery(config tgbotapi.CallbackConfig) (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
}

func (bot BotMock) MakeRequest(endpoint string, params url.Values) (tgbotapi.APIResponse, error) {
	return tgbotapi.APIResponse{}, 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, false)

	m.Redis.FlushDb()
	return m
}

// Empty Function, because "go vet" wants Margelet() to exist because the ExampleMargelet function
func 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()
}
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, verbose bool) (*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) AnswerCallbackQuery

func (margelet *Margelet) AnswerCallbackQuery(config tgbotapi.CallbackConfig) (tgbotapi.APIResponse, error)

AnswerCallbackQuery - send answer to CallbackQuery

func (*Margelet) AnswerInlineQuery

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

AnswerInlineQuery - send answer to InlineQuery

func (*Margelet) GetChatRepository

func (margelet *Margelet) GetChatRepository() *ChatRepository

GetChatRepository - returns chats repository

func (*Margelet) GetConfigRepository

func (margelet *Margelet) GetConfigRepository() *ChatConfigRepository

GetConfigRepository - returns chat config repository

func (*Margelet) GetCurrentUserpic

func (margelet *Margelet) GetCurrentUserpic(userID int) (string, error)

GetCurrentUserpic - returns current userpic URL for userID or error

func (*Margelet) GetCurrentUserpicID

func (margelet *Margelet) GetCurrentUserpicID(userID int) (string, error)

GetCurrentUserpicID - returns current userpic FileID for userID or error

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

func (margelet *Margelet) GetStatsRepository() StatsRepository

GetStatsRepository - returns stats repository

func (*Margelet) GetUserProfilePhotos

func (margelet *Margelet) GetUserProfilePhotos(config tgbotapi.UserProfilePhotosConfig) (tgbotapi.UserProfilePhotos, error)

GetUserProfilePhotos - returns user profile photos by config

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

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

QuickForceReply - quick send text force reply to message

func (*Margelet) QuickReply

func (margelet *Margelet) QuickReply(chatID int64, messageID int, message string, replyMarkup interface{}) (tgbotapi.Message, error)

QuickReply - quick send text reply to message

func (*Margelet) QuickSend

func (margelet *Margelet) QuickSend(chatID int64, message string, replyMarkup interface{}) (tgbotapi.Message, error)

QuickSend - quick send text message to chatID

func (*Margelet) RawBot

func (margelet *Margelet) RawBot() *tgbotapi.BotAPI

RawBot - returns low-level tgbotapi.Bot

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

func (margelet *Margelet) SendDocument(chatID int64, reader tgbotapi.FileReader, replyMarkup interface{}) (tgbotapi.Message, error)

SendDocument - sends document to chat

func (*Margelet) SendDocumentByURL

func (margelet *Margelet) SendDocumentByURL(chatID int64, url string, replyMarkup interface{}) (tgbotapi.Message, error)

SendDocumentByURL - sends given by url document to chatID

func (*Margelet) SendFindLocationAction

func (margelet *Margelet) SendFindLocationAction(chatID int64) error

SendFindLocationAction - sends find_location chat action to chatID

func (*Margelet) SendHideKeyboard

func (margelet *Margelet) SendHideKeyboard(chatID int64, message string) error

SendHideKeyboard - hides keyboard in chatID

func (*Margelet) SendImage

func (margelet *Margelet) SendImage(chatID int64, reader tgbotapi.FileReader, caption string, replyMarkup interface{}) (tgbotapi.Message, error)

SendImage - sends image to chat

func (*Margelet) SendImageByID

func (margelet *Margelet) SendImageByID(chatID int64, fileID string, caption string, replyMarkup interface{}) (tgbotapi.Message, error)

SendImageByID - sends given by FileID image to chatID

func (*Margelet) SendImageByURL

func (margelet *Margelet) SendImageByURL(chatID int64, imgURL string, caption string, replyMarkup interface{}) (tgbotapi.Message, error)

SendImageByURL - sends given by url image to chatID

func (*Margelet) SendRecordAudioAction

func (margelet *Margelet) SendRecordAudioAction(chatID int64) error

SendRecordAudioAction - sends record_audio chat action to chatID

func (*Margelet) SendRecordVideoAction

func (margelet *Margelet) SendRecordVideoAction(chatID int64) error

SendRecordVideoAction - sends record_video chat action to chatID

func (*Margelet) SendTypingAction

func (margelet *Margelet) SendTypingAction(chatID int64) error

SendTypingAction - sends typing chat action to chatID

func (*Margelet) SendUploadAudioAction

func (margelet *Margelet) SendUploadAudioAction(chatID int64) error

SendUploadAudioAction - sends upload_audio chat action to chatID

func (*Margelet) SendUploadDocumentAction

func (margelet *Margelet) SendUploadDocumentAction(chatID int64) error

SendUploadDocumentAction - sends upload_document chat action to chatID

func (*Margelet) SendUploadPhotoAction

func (margelet *Margelet) SendUploadPhotoAction(chatID int64) error

SendUploadPhotoAction - sends upload_photo chat action to chatID

func (*Margelet) SendUploadVideoAction

func (margelet *Margelet) SendUploadVideoAction(chatID int64) error

SendUploadVideoAction - sends upload_video chat action to chatID

func (*Margelet) SetUnknownCommandHandler

func (margelet *Margelet) SetUnknownCommandHandler(handler CommandHandler, auth ...AuthorizationPolicy)

SetUnknownCommandHandler - sets unknown command handler

func (*Margelet) StartSession

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

StartSession - start new session with given command, adds message to dialog

func (*Margelet) Stop

func (margelet *Margelet) Stop()

Stop - stops message processing loop

type MargeletAPI

type MargeletAPI interface {
	Store
	Send(c tgbotapi.Chattable) (tgbotapi.Message, error)
	AnswerInlineQuery(config tgbotapi.InlineConfig) (tgbotapi.APIResponse, error)
	AnswerCallbackQuery(config tgbotapi.CallbackConfig) (tgbotapi.APIResponse, error)
	QuickSend(chatID int64, message string, replyMarkup interface{}) (tgbotapi.Message, error)
	QuickReply(chatID int64, messageID int, message string, replyMarkup interface{}) (tgbotapi.Message, error)
	QuickForceReply(chatID int64, messageID int, message string) (tgbotapi.Message, error)
	SendImage(chatID int64, reader tgbotapi.FileReader, caption string, replyMarkup interface{}) (tgbotapi.Message, error)

	GetFileDirectURL(fileID string) (string, error)
	IsMessageToMe(message tgbotapi.Message) bool
	HandleSession(message *tgbotapi.Message, command string)
	StartSession(message *tgbotapi.Message, command string)
	SendImageByURL(chatID int64, url string, caption string, replyMarkup interface{}) (tgbotapi.Message, error)
	SendImageByID(chatID int64, url string, caption string, replyMarkup interface{}) (tgbotapi.Message, error)

	SendDocument(chatID int64, reader tgbotapi.FileReader, replyMarkup interface{}) (tgbotapi.Message, error)
	SendDocumentByURL(chatID int64, url string, replyMarkup interface{}) (tgbotapi.Message, error)

	SendTypingAction(chatID int64) error
	SendUploadPhotoAction(chatID int64) error
	SendRecordVideoAction(chatID int64) error
	SendUploadVideoAction(chatID int64) error
	SendRecordAudioAction(chatID int64) error
	SendUploadAudioAction(chatID int64) error
	SendUploadDocumentAction(chatID int64) error
	SendFindLocationAction(chatID int64) error

	SendHideKeyboard(chatID int64, message string) error

	RawBot() *tgbotapi.BotAPI
	GetUserProfilePhotos(config tgbotapi.UserProfilePhotosConfig) (tgbotapi.UserProfilePhotos, error)
	GetCurrentUserpic(userID int) (string, error)
	GetCurrentUserpicID(userID int) (string, error)
}

MargeletAPI - interface, that describes margelet API

type Message

type Message interface {
	Store
	Message() *tgbotapi.Message
	GetFileDirectURL(fileID string) (string, error)
	QuickSend(text string, replyMarkup interface{}) (tgbotapi.Message, error)
	QuickReply(text string, replyMarkup interface{}) (tgbotapi.Message, error)
	QuickForceReply(text string) (tgbotapi.Message, error)
	SendImageByURL(url string, caption string, replyMarkup interface{}) (tgbotapi.Message, error)
	SendImage(reader tgbotapi.FileReader, caption string, replyMarkup interface{}) (tgbotapi.Message, error)
	SendDocument(reader tgbotapi.FileReader, replyMarkup interface{}) (tgbotapi.Message, error)
	SendDocumentByURL(url string, replyMarkup interface{}) (tgbotapi.Message, error)

	SendTypingAction() error
	SendUploadPhotoAction() error
	SendRecordVideoAction() error
	SendUploadVideoAction() error
	SendRecordAudioAction() error
	SendUploadAudioAction() error
	SendUploadDocumentAction() error
	SendFindLocationAction() error
	SendHideKeyboard(message string) error
	GetCurrentUserpic() (string, error)
	GetCurrentUserpicID() (string, error)
	Bot() MargeletAPI
	StartSession(command string)
}

Message - interface, that describes incapsulated info aboud user's message with some helper methods

type MessageHandler

type MessageHandler interface {
	HandleMessage(message Message) error
}

MessageHandler - interface for message handlers

type ReceiveCallback

type ReceiveCallback func(from int, text string)

type RecoverCallback

type RecoverCallback func(margelet *Margelet, userID int, r interface{})

RecoverCallback - callback wich will be called when margelet recovers from panic

type SendCallback

type SendCallback func(to int64, text string)

type Session

type Session interface {
	Message
	Responses() []tgbotapi.Message
	Finish()
}

Session - interface, that describes incapsulated info aboud user's session with bot

type SessionHandler

type SessionHandler interface {
	HandleSession(session Session) error
	CancelSession(session Session)
	HelpMessage() string
}

SessionHandler - interface for session handlers

type SessionRepository

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

SessionRepository - public interface for session repository

type StatsRepository

type StatsRepository interface {
	Incr(chatID int64, userID int, name string)
	Get(chatID int64, userID int, name string) int
}

StatsRepository - public interface for session repository

type Store

type Store interface {
	GetConfigRepository() *ChatConfigRepository
	GetSessionRepository() SessionRepository
	GetChatRepository() *ChatRepository
	GetStatsRepository() StatsRepository
	GetRedis() *redis.Client
}

type TGBotAPI

type TGBotAPI interface {
	Send(c tgbotapi.Chattable) (tgbotapi.Message, error)
	AnswerInlineQuery(config tgbotapi.InlineConfig) (tgbotapi.APIResponse, error)
	AnswerCallbackQuery(config tgbotapi.CallbackConfig) (tgbotapi.APIResponse, error)
	GetFileDirectURL(fileID string) (string, error)
	IsMessageToMe(message tgbotapi.Message) bool
	GetUpdatesChan(config tgbotapi.UpdateConfig) (<-chan tgbotapi.Update, error)
	MakeRequest(endpoint string, params url.Values) (tgbotapi.APIResponse, 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