tbot

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2017 License: Apache-2.0 Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

tbot - Telegram Bot Server Build Status Go Report Card codecov

GoDoc

tbot is a Telegram bot server.

Installation

go get -u github.com/yanzay/tbot

Support

Join telegram group to get support.

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 here: https://godoc.org/github.com/yanzay/tbot

Test coverage: https://gocover.io/github.com/yanzay/tbot

Documentation

Index

Constants

This section is empty.

Variables

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

Functions

func AccessDenied

func AccessDenied(m *Message)

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

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)

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

type Handler

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

Handler is a struct that represents any message handler with handler function, descriptio, 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 KeyboardOption

type KeyboardOption func(*adapter.Message)

type Message

type Message struct {
	*adapter.Message
	Vars MessageVars
}

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

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

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

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

func (m *Message) Text() string

Text returns message text

type MessageVars

type MessageVars map[string]string

MessageVars is a parsed message variables lookup table

type Middleware

type Middleware func(HandlerFunction) HandlerFunction

func NewAuth

func NewAuth(whitelist []string) Middleware

type Mux

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

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

Mux interface represents message multiplexer

func NewDefaultMux

func NewDefaultMux() Mux

NewDefaultMux creates new DefaultMux

type Option

type Option func(*adapter.Message)

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

func (*Server) AddMiddleware

func (s *Server) AddMiddleware(mid Middleware)

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)

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

type ServerOption

type ServerOption func(*Server)

func WithMux

func WithMux(m Mux) ServerOption

func WithWebhook

func WithWebhook(url string, addr string) ServerOption

Directories

Path Synopsis
examples
simple command
internal

Jump to

Keyboard shortcuts

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