Connecting joe with the Telegram chat application. https://github.com/go-joe/joe
This repository contains a module for the Joe Bot library. Built using telegram-bot-api.
This library is packaged using Go modules. You can get it via:
go get github.com/robertgzr/joe-telegram-adapter
In order to connect your bot to telegram you can simply pass it as module when creating a new bot:
package main
import (
"github.com/go-joe/joe"
"github.com/robertgzr/joe-telegram-adapter"
)
func main() {
b := joe.New("example-bot",
telegram.Adapter(os.Getenv("TELEGRAM_BOT_TOKEN")),
…
)
b.Respond("ping", Pong)
err := b.Run()
if err != nil {
b.Logger.Fatal(err.Error())
}
}
For how to create a telegram bot and connect to it, see here.
This adapter will emit the following events to the robot brain:
joe.ReceiveMessageEvent
ReceiveCommandEvent
A common use-case is handling Telegram bot commands, /command
. To make this
easy a custom event type is emitted:
package main
import (
"github.com/go-joe/joe"
"github.com/robertgzr/joe-telegram-adapter"
)
type ExampleBot {
*joe.Bot
}
func main() {
b := &ExampleBot{
Bot: joe.New("example-bot",
telegram.Adapter(os.Getenv("TELEGRAM_BOT_TOKEN")),
…
),
}
b.Brain.RegisterHandler(b.HandleTelegramCommands)
b.Respond("ping", Pong)
err := b.Run()
if err != nil {
b.Logger.Fatal(err.Error())
}
}
func (b *ExampleBot) HandleTelegramCommands(ev telegram.ReceiveCommandEvent) error {
switch ev.Arg0 {
case "command":
b.Say(ev.Channel(), "Hello, world!")
return nil
default:
return errors.New("unknown command")
}
}
Some features available via the Bot API is nice to have when writing bots:
tg, ok := Bot.Adapter.(*telegram.TelegramAdapter)
tg.BotAPI
allows full access to the Bot API interface.
This package also provides some abstractions for ease of use:
// photo/gif/sticker can be file, FileReader, or FileBytes which will upload a
// new instance; or a string which assumes a telegram fileID
tg.SendPhoto(msg.Channel, photo, "caption")
tg.SendGif(msg.Channel, gif, "caption")
tg.SendSticker(msg.Channel, sticker)