tbot

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2019 License: Apache-2.0 Imports: 12 Imported by: 19

README

tbot - Telegram Bot Server Build Status Go Report Card codecov

GoDoc

tbot is a Telegram bot server.

It feels just like net/http. You define routes and handlers and it works. Middleware support included.

logo

Installation

go get -u github.com/yanzay/tbot

Support

For a brief introduction, take a look the blog post on medium.

Join telegram group to get support or just to say thank you.

Usage

It feels like net/http Server, so it's easy to use:

package main

import (
	"log"
	"os"
	"time"

	"github.com/yanzay/tbot"
)

func main() {
	token := os.Getenv("TELEGRAM_TOKEN")
	// Create new telegram bot server using token
	bot, err := tbot.NewServer(token)
	if err != nil {
		log.Fatal(err)
	}

	// Use whitelist for Auth middleware, allow to interact only with user1 and user2
	whitelist := []string{"yanzay", "user2"}
	bot.AddMiddleware(tbot.NewAuth(whitelist))

	// Yo handler works without slash, simple text response
	bot.Handle("yo", "YO!")

	// Handle with HiHandler function
	bot.HandleFunc("/hi", HiHandler)
	// Handler can accept varialbes
	bot.HandleFunc("/say {text}", SayHandler)
	// Bot can send stickers, photos, music
	bot.HandleFunc("/sticker", StickerHandler)
	bot.HandleFunc("/photo", PhotoHandler)
	bot.HandleFunc("/keyboard", KeyboardHandler)

	// Use file handler to handle user uploads
	bot.HandleFile(FileHandler)

	// Set default handler if you want to process unmatched input
	bot.HandleDefault(EchoHandler)

	// Start listening for messages
	err = bot.ListenAndServe()
	log.Fatal(err)
}

func HiHandler(message *tbot.Message) {
	// Handler can reply with several messages
	message.Replyf("Hello, %s!", message.From)
	time.Sleep(1 * time.Second)
	message.Reply("What's up?")
}

func SayHandler(message *tbot.Message) {
	// Message contain it's varialbes from curly brackets
	message.Reply(message.Vars["text"])
}

func EchoHandler(message *tbot.Message) {
	message.Reply(message.Text())
}

func StickerHandler(message *tbot.Message) {
	message.ReplySticker("sticker.png")
}

func PhotoHandler(message *tbot.Message) {
	message.ReplyPhoto("photo.jpg", "it's me")
}

func KeyboardHandler(message *tbot.Message) {
	buttons := [][]string{
		{"Some", "Test", "Buttons"},
		{"Another", "Row"},
	}
	message.ReplyKeyboard("Buttons example", buttons)
}

func FileHandler(message *tbot.Message) {
	err := message.Download("./uploads")
	if err != nil {
		message.Replyf("Error handling file: %q", err)
		return
	}
	message.Reply("Thanks for uploading!")
}

See full documentation on godoc.

Documentation

Index

Constants

View Source
const (
	RouteBack    = "<..>"
	RouteRoot    = ""
	RouteRefresh = "<.>"
)

Variables

View Source
var DisablePreview = func(msg *model.Message) {
	msg.DisablePreview = true
}

DisablePreview option disables web page preview when sending links.

View Source
var OneTimeKeyboard = func(msg *model.Message) {
	msg.OneTimeKeyboard = true
}

OneTimeKeyboard option sends keyboard that hides after the user use it once.

View Source
var WithDataInlineButtons = func(msg *model.Message) {
	msg.WithDataInlineButtons = true
}

WithDataInlineButtons option send inline keyboard buttons with data for catch a callback.

View Source
var WithMarkdown = func(msg *model.Message) {
	msg.Markdown = true
}

WithMarkdown option enables Markdown style formatting for text messages.

View Source
var WithURLInlineButtons = func(msg *model.Message) {
	msg.WithURLInlineButtons = true
}

WithURLInlineButtons option send inline keyboard buttons as url.

Functions

This section is empty.

Types

type DefaultMux

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

DefaultMux is a default multiplexer, supports parametrized commands. Parameters should be enclosed with curly brackets, like in "/say {hi}" - "hi" is a parameter.

func (*DefaultMux) DefaultHandler

func (dm *DefaultMux) DefaultHandler() *Handler

DefaultHandler returns default handler, nil if it's not set

func (*DefaultMux) FileHandler

func (dm *DefaultMux) FileHandler() *Handler

FileHandler returns file handler, nil if there is no file handler

func (*DefaultMux) HandleDefault

func (dm *DefaultMux) HandleDefault(handler HandlerFunction, description ...string)

HandleDefault adds new default handler, when nothing matches with message, "description" is for "/help" handler.

func (*DefaultMux) HandleFile

func (dm *DefaultMux) HandleFile(handler HandlerFunction, description ...string)

HandleFile adds file handler. When the user uploads Document, Download method will be available for *Message.

func (*DefaultMux) HandleFunc

func (dm *DefaultMux) HandleFunc(path string, handler HandlerFunction, description ...string)

HandleFunc adds new handler function to mux, "description" is for "/help" handler.

func (*DefaultMux) Handlers

func (dm *DefaultMux) Handlers() Handlers

Handlers returns list of handlers currently presented in mux

func (*DefaultMux) Mux

func (dm *DefaultMux) Mux(msg *Message) (*Handler, MessageVars)

Mux takes message content and returns corresponding handler and parsed vars from message

func (*DefaultMux) Reset added in v0.4.1

func (db *DefaultMux) Reset(int64)

func (*DefaultMux) SetAlias added in v0.4.1

func (dm *DefaultMux) SetAlias(route string, aliases ...string)

type Handler

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

Handler is a struct that represents any message handler with handler function, description, pattern and parsed variables

func NewHandler

func NewHandler(f func(*Message), path string, description ...string) *Handler

NewHandler creates new handler and returns it

type HandlerFunction

type HandlerFunction func(*Message)

HandlerFunction is a function that can process incoming messages

type Handlers

type Handlers map[string]*Handler

Handlers is a lookup table of handlers, key - string pattern value - Handler

type InMemoryStorage added in v0.4.1

type InMemoryStorage struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*InMemoryStorage) Get added in v0.4.1

func (ims *InMemoryStorage) Get(id int64) string

func (*InMemoryStorage) Reset added in v0.4.1

func (ims *InMemoryStorage) Reset(id int64)

func (*InMemoryStorage) Set added in v0.4.1

func (ims *InMemoryStorage) Set(id int64, path string)

type InlineKeyboardButtonsOption added in v0.4.1

type InlineKeyboardButtonsOption func(*model.Message)

InlineKeyboardButtonsOption is a functional option for inline keyboard buttons

type KeyboardOption

type KeyboardOption func(*model.Message)

KeyboardOption is a functional option for custom keyboards

type Message

type Message struct {
	*model.Message
	Vars MessageVars
	// contains filtered or unexported fields
}

Message is a received message from chat, with parsed variables

func (*Message) Download

func (m *Message) Download(dir string) error

Download file from FileHandler

func (*Message) Reply

func (m *Message) Reply(reply string, options ...MessageOption)

Reply to the user with plain text

func (*Message) ReplyAudio

func (m *Message) ReplyAudio(filepath string)

ReplyAudio sends audio file to chat

func (*Message) ReplyDocument

func (m *Message) ReplyDocument(filepath string)

ReplyDocument sends generic file (not audio, voice, image) to the chat

func (*Message) ReplyInlineKeyboard added in v0.4.1

func (m *Message) ReplyInlineKeyboard(text string, inlineButtons []map[string]string, options ...InlineKeyboardButtonsOption)

ReplyInlineKeyboard sends custom inline reply keyboard waiting for data callback to the user.

func (*Message) ReplyKeyboard

func (m *Message) ReplyKeyboard(text string, buttons [][]string, options ...KeyboardOption)

ReplyKeyboard sends custom reply keyboard to the user.

func (*Message) ReplyLocation added in v0.4.1

func (m *Message) ReplyLocation(longitude, latitude float64)

ReplyLocation sends location reply to the user.

func (*Message) ReplyPhoto

func (m *Message) ReplyPhoto(filepath string, caption ...string)

ReplyPhoto sends photo to the chat. Has optional caption.

func (*Message) ReplySticker

func (m *Message) ReplySticker(filepath string)

ReplySticker sends sticker to the chat.

func (*Message) ReplyVideo added in v0.4.1

func (m *Message) ReplyVideo(filepath string, caption ...string)

ReplyVideo sends video to the chat. Has optional caption.

func (*Message) Replyf

func (m *Message) Replyf(reply string, values ...interface{})

Replyf is a formatted reply to the user with plain text, with parameters like in fmt.Printf

func (*Message) RequestContactButton added in v0.4.1

func (m *Message) RequestContactButton(text string, button string, options ...KeyboardOption)

RequestContactButton sends custom reply contact button to the user.

func (*Message) RequestLocationButton added in v0.4.1

func (m *Message) RequestLocationButton(text string, button string, options ...KeyboardOption)

RequestLocationButton sends custom reply location keyboard to the user.

func (*Message) SetReplyChannel added in v0.4.1

func (m *Message) SetReplyChannel(ch chan *model.Message)

SetReplyChannel sets channel for custom reply handling, e. g. for tests

func (*Message) Text

func (m *Message) Text() string

Text returns message text

type MessageOption added in v0.4.1

type MessageOption func(*model.Message)

MessageOption is a functional option for text messages

type MessageVars

type MessageVars map[string]string

MessageVars is a parsed message variables lookup table

type Middleware

type Middleware func(HandlerFunction) HandlerFunction

Middleware function takes HandlerFunction and returns HandlerFunction. Should call it's argument function inside, if needed.

func NewAuth

func NewAuth(whitelist interface{}) Middleware

NewAuth creates Middleware for white-list based authentication according to username, userid or chatid list. purpose: to prevent the access to bots from another users or groups

type Mux

type Mux interface {
	Mux(*Message) (*Handler, MessageVars)
	HandleFunc(string, HandlerFunction, ...string)
	HandleFile(HandlerFunction, ...string)
	HandleDefault(HandlerFunction, ...string)
	SetAlias(string, ...string)
	Reset(int64)

	Handlers() Handlers
	DefaultHandler() *Handler
	FileHandler() *Handler
}

Mux interface represents message multiplexer

func NewDefaultMux

func NewDefaultMux() Mux

NewDefaultMux creates new DefaultMux

func NewRouterMux added in v0.4.1

func NewRouterMux(storage SessionStorage) Mux

NewRouterMux creates new RouterMux Takes SessionStorage to store users' sessions state

type Node added in v0.4.1

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

func NewNode added in v0.4.1

func NewNode(parent *Node, route string, handler *Handler) *Node

type RouterMux added in v0.4.1

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

RouterMux is a tree-route multiplexer

func (*RouterMux) DefaultHandler added in v0.4.1

func (rm *RouterMux) DefaultHandler() *Handler

DefaultHandler returns default handler, nil if it's not set

func (*RouterMux) FileHandler added in v0.4.1

func (rm *RouterMux) FileHandler() *Handler

func (*RouterMux) HandleDefault added in v0.4.1

func (rm *RouterMux) HandleDefault(handler HandlerFunction, description ...string)

HandleDefault adds new default handler, when nothing matches with message,

func (*RouterMux) HandleFile added in v0.4.1

func (rm *RouterMux) HandleFile(handler HandlerFunction, description ...string)

func (*RouterMux) HandleFunc added in v0.4.1

func (rm *RouterMux) HandleFunc(path string, handler HandlerFunction, description ...string)

HandleFunc adds new handler function to mux.

func (*RouterMux) Handlers added in v0.4.1

func (rm *RouterMux) Handlers() Handlers

Handlers returns list of handlers currently presented in mux

func (*RouterMux) Mux added in v0.4.1

func (rm *RouterMux) Mux(msg *Message) (*Handler, MessageVars)

Mux takes message content and returns corresponding handler

func (*RouterMux) Reset added in v0.4.1

func (rm *RouterMux) Reset(chatID int64)

func (*RouterMux) SetAlias added in v0.4.1

func (rm *RouterMux) SetAlias(route string, aliases ...string)

SetAlias sets aliases for specified route.

type Server

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

Server is a telegram bot server. Looks and feels like net/http.

func NewServer

func NewServer(token string, options ...ServerOption) (*Server, error)

NewServer creates new Server with Telegram API Token and default /help handler using go default http client

func (*Server) AddMiddleware

func (s *Server) AddMiddleware(mid Middleware)

AddMiddleware adds new Middleware for server

func (*Server) Handle

func (s *Server) Handle(path string, reply string, description ...string)

Handle is a shortcut for HandleFunc to reply just with static text, "description" is for "/help" handler.

func (*Server) HandleDefault

func (s *Server) HandleDefault(handler HandlerFunction, description ...string)

HandleDefault delegates HandleDefault to the current Mux

func (*Server) HandleFile

func (s *Server) HandleFile(handler HandlerFunction, description ...string)

HandleFile adds file handler for user uploads.

func (*Server) HandleFunc

func (s *Server) HandleFunc(path string, handler HandlerFunction, description ...string)

HandleFunc delegates HandleFunc to the current Mux

func (*Server) HelpHandler

func (s *Server) HelpHandler(m *Message)

HelpHandler is a default handler for /help, shows available commands and their description

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts Server, returns error on failure

func (*Server) Reset added in v0.4.1

func (s *Server) Reset(chatID int64)

func (*Server) Send added in v0.4.1

func (s *Server) Send(chatID int64, text string) error

func (*Server) SendMessage added in v0.4.1

func (s *Server) SendMessage(m *model.Message) error

SendMessage method sends a Message object to the user. MessageType and ChatID are required for sending a proper message to a chat.

func (*Server) SendRaw added in v0.4.1

func (s *Server) SendRaw(endpoint string, params map[string]string) error

SendRaw sends direct request to telegram api

func (*Server) SetAlias added in v0.4.1

func (s *Server) SetAlias(route string, aliases ...string)

type ServerOption

type ServerOption func(*Server)

ServerOption is a functional option for Server

func WithHttpClient added in v0.4.1

func WithHttpClient(client *http.Client) ServerOption

WithHttpClient sets custom http client for server.

func WithMux

func WithMux(m Mux) ServerOption

WithMux sets custom mux for server. Should satisfy Mux interface.

func WithWebhook

func WithWebhook(url string, addr string) ServerOption

WithWebhook returns ServerOption for given Webhook URL and Server address to listen. e.g. WithWebook("https://bot.example.com/super/url", "0.0.0.0:8080")

type SessionStorage added in v0.4.1

type SessionStorage interface {
	Set(int64, string)
	Get(int64) string
	Reset(int64)
}

func NewSessionStorage added in v0.4.1

func NewSessionStorage() SessionStorage

Directories

Path Synopsis
examples
internal

Jump to

Keyboard shortcuts

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