Skip to content

Commit

Permalink
Basic route handling and serving based on #35 by @rodrigodiez.
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigodiez authored and Ian Byrd committed Nov 10, 2016
1 parent 5ce02a1 commit 9e485b0
Show file tree
Hide file tree
Showing 3 changed files with 133 additions and 87 deletions.
171 changes: 84 additions & 87 deletions README.md
@@ -1,134 +1,131 @@
# Telebot
>Telebot is a convenient wrapper to Telegram Bots API, written in Golang.
> Telebot is a convenient wrapper to Telegram Bots API, written in Golang.
[![GoDoc](https://godoc.org/github.com/tucnak/telebot?status.svg)](https://godoc.org/github.com/tucnak/telebot)
[![Travis](https://travis-ci.org/tucnak/telebot.svg?branch=master)](https://travis-ci.org/tucnak/telebot)
[![GoDoc](https://godoc.org/github.com/tucnak/telebot?status.svg)](https://godoc.org/github.com/tucnak/telebot) [![Travis](https://travis-ci.org/tucnak/telebot.svg?branch=master)](https://travis-ci.org/tucnak/telebot)

Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server.

Telebot offers a convenient wrapper to Bots API, so you shouldn't even
care about networking at all. You may install it with
bother about networking at all. You may install it with

go get github.com/tucnak/telebot

(after setting up your `GOPATH` properly).

Since you are probably
hosting your bot in a public repository, we'll add an environment
variable for the token in this example. Please set it with
We highly recommend you to keep your bot access token outside the code base,
preferably as an environmental variable:

export BOT_TOKEN=<your token here>


Here is an example "helloworld" bot, written with telebot:
Here is an example bot powered by Telebot:

```go
package main

import (
"log"
"time"
"os"
"github.com/tucnak/telebot"
"log"
"time"
"os"
"github.com/tucnak/telebot"
)

func main() {
bot, err := telebot.NewBot(os.Getenv("BOT_TOKEN"))
if err != nil {
log.Fatalln(err)
}

messages := make(chan telebot.Message)
bot.Listen(messages, 1*time.Second)

for message := range messages {
if message.Text == "/hi" {
bot.SendMessage(message.Chat,
"Hello, "+message.Sender.FirstName+"!", nil)
}
}
bot, err := telebot.NewBot(os.Getenv("BOT_TOKEN"))
if err != nil {
log.Fatalln(err)
}

// routes are compiled as regexps
bot.Handle("/hi", func (context telebot.Context) {
bot.SendMessage(context.Message.Chat, "Hi!", nil)
})

// named groups found in routes will get injected in the controller as arguments
bot.Handle("/greet (?P<name>[a-z]+)", func(ctx telebot.Context) {
bot.SendMessage(ctx.Message.Chat, "Hello "+ctx.Args["name"], nil)
})

bot.Serve()
}
```

## Inline mode

As of January 4, 2016, Telegram added inline mode support for bots.
Telebot support inline mode in a fancy manner. Here's a nice way to handle both incoming messages and inline queries:
As of January 4, 2016, Telegram added inline mode support for bots. Here's
a nice way to handle both incoming messages and inline queries in the meantime:

```go
package main

import (
"log"
"time"
"os"
"github.com/tucnak/telebot"
"log"
"time"
"os"
"github.com/tucnak/telebot"
)

var bot *telebot.Bot

func main() {
var err error
bot, err = telebot.NewBot(os.Getenv("BOT_TOKEN"))
if err != nil {
log.Fatalln(err)
}
bot, err := telebot.NewBot(os.Getenv("BOT_TOKEN"))
if err != nil {
log.Fatalln(err)
}

bot.Messages = make(chan telebot.Message, 1000)
bot.Queries = make(chan telebot.Query, 1000)
bot.Messages = make(chan telebot.Message, 1000)
bot.Queries = make(chan telebot.Query, 1000)

go messages()
go queries()
go messages(bot)
go queries(bot)

bot.Start(1 * time.Second)
bot.Start(1 * time.Second)
}

func messages() {
for message := range bot.Messages {
log.Printf("Received a message from %s with the text: %s\n", message.Sender.Username, message.Text)
}
func messages(bot *telebot.Bot) {
for message := range bot.Messages {
log.Printf("Received a message from %s with the text: %s\n",
message.Sender.Username, message.Text)
}
}

func queries() {
for query := range bot.Queries {
log.Println("--- new query ---")
log.Println("from:", query.From.Username)
log.Println("text:", query.Text)

// Create an article (a link) object to show in our results.
article := &telebot.InlineQueryResultArticle{
Title: "Telegram bot framework written in Go",
URL: "https://github.com/tucnak/telebot",
InputMessageContent: &telebot.InputTextMessageContent{
Text: "Telebot is a convenient wrapper to Telegram Bots API, written in Golang.",
DisablePreview: false,
},
}

// Build the list of results. In this instance, just our 1 article from above.
results := []telebot.InlineQueryResult{article}

// Build a response object to answer the query.
response := telebot.QueryResponse{
Results: results,
IsPersonal: true,
}

// And finally send the response.
if err := bot.AnswerInlineQuery(&query, &response); err != nil {
log.Println("Failed to respond to query:", err)
}
}
func queries(bot *telebot.Bot) {
for query := range bot.Queries {
log.Println("--- new query ---")
log.Println("from:", query.From.Username)
log.Println("text:", query.Text)

// Create an article (a link) object to show in results.
article := &telebot.InlineQueryResultArticle{
Title: "Telebot",
URL: "https://github.com/tucnak/telebot",
InputMessageContent: &telebot.InputTextMessageContent{
Text: "Telebot is a Telegram bot framework.",
DisablePreview: false,
},
}

// Build the list of results (make sure to pass pointers!).
results := []telebot.InlineQueryResult{article}

// Build a response object to answer the query.
response := telebot.QueryResponse{
Results: results,
IsPersonal: true,
}

// Send it.
if err := bot.AnswerInlineQuery(&query, &response); err != nil {
log.Println("Failed to respond to query:", err)
}
}
}
```

## Files

Telebot lets you upload files from the file system:

```go
boom, err := telebot.NewFile("boom.ogg")
if err != nil {
return err
return err
}

audio := telebot.Audio{File: boom}
Expand All @@ -139,22 +136,22 @@ err = bot.SendAudio(recipient, &audio, nil)
```

## Reply markup

Sometimes you wanna send a little complicated messages with some optional parameters. The third argument of all `Send*` methods accepts `telebot.SendOptions`, capable of defining an advanced reply markup:

```go
// Send a selective force reply message.
bot.SendMessage(user, "pong", &telebot.SendOptions{
ReplyMarkup: telebot.ReplyMarkup{
ForceReply: true,
Selective: true,
ReplyMarkup: telebot.ReplyMarkup{
ForceReply: true,
Selective: true,

CustomKeyboard: [][]string{
[]string{"1", "2", "3"},
[]string{"4", "5", "6"},
[]string{"7", "8", "9"},
[]string{"*", "0", "#"},
},
},
},
},
},
)
```
40 changes: 40 additions & 0 deletions bot.go
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"log"
"regexp"
"strconv"
"time"
)
Expand All @@ -15,6 +16,8 @@ type Bot struct {
Messages chan Message
Queries chan Query
Callbacks chan Callback

handlers map[*regexp.Regexp]Handler
}

// NewBot does try to build a Bot with token `token`, which
Expand All @@ -28,6 +31,7 @@ func NewBot(token string) (*Bot, error) {
return &Bot{
Token: token,
Identity: user,
handlers: map[*regexp.Regexp]Handler{},
}, nil
}

Expand Down Expand Up @@ -847,3 +851,39 @@ func (b *Bot) GetFileDirectURL(fileID string) (string, error) {
}
return "https://api.telegram.org/file/bot" + b.Token + "/" + f.FilePath, nil
}

// Handle registers a handler for a message which text matches the provided regular expression
func (b *Bot) Handle(command string, handler Handler) {
reg := regexp.MustCompile(command)
b.handlers[reg] = handler
}

// Serve listens for messages and route them to the appropiate handler
func (b *Bot) Serve() {
messages := make(chan Message)
b.Listen(messages, 1*time.Second)

for message := range messages {
if handler, args := b.route(&message); handler != nil {
handler(Context{Message: &message, Args: args})
}
}
}

func (b *Bot) route(message *Message) (Handler, map[string]string) {
for reg, handler := range b.handlers {

if matches := reg.FindStringSubmatch(message.Text); len(matches) > 0 {
args := map[string]string{}

for x, name := range reg.SubexpNames() {
if x != 0 {
args[name] = matches[x]
}
}
return handler, args
}
}

return nil, nil
}
9 changes: 9 additions & 0 deletions types.go
Expand Up @@ -257,3 +257,12 @@ type UserProfilePhotos struct {
Count int `json:"total_count"`
Photos [][]Photo `json:"photos"`
}

// Context is passed to message handlers
type Context struct {
Message *Message
Args map[string]string
}

// Handler represents a message handler
type Handler func(Context)

0 comments on commit 9e485b0

Please sign in to comment.