telego

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2021 License: MIT Imports: 16 Imported by: 1

README

Telego

GitHubActions Go Report Card GoDoc

Telego is a Go framework for Telegram bots. It helps you building Telegram applications interacting with the Telegram Bot API for you. It also gives you tools like flows which gives you the abiity to define steps for specific messages from the users.

Usage

For full details of all the available functionallity that Telego provides, please go to the full docs

Initialise Telego

The first thing that you have to do to use telego is create a Telegram bot and get its bot token. Once you have the token, you can initialise your bot doing:

bot = telego.Initialise("110201543:testTraceToken")

This method is going to initialise the basics to make the bot work. At this point, your bot is not going to be able to read any message. In order to get messages from Telegram, there are different ways of getting updates, this bot (for now) only supports long polling. To start the long poll, you will need to execute the Listen metho that it's available from the Telego structure:

bot = telego.Initialise("110201543:testTraceToken")
bot.Listen()

Listen, on an infinite loop, makes a request to Telegram to get the latest messages for your bot.

Message handlers

Telego provides an easy way to handle different kind of messages. In order to handle messages, you will need first to define different FlowStep functions.

This functions are going to have two paramenters the Update which si going to contain the message that the user has sent to the bot and the Conversation which is going to allow you to easily message back the user and access the conversation context. This functions are also going to return another FlowStep function, which is going to be used for flows.

This is the simplest example of a FlowStep function, which is going to send to the user the same message that they have sent and will finish the flow after that.

func echoStep(u api.Update, c telego.Conversation) telego.FlowStep {
	c.SendMessage(u.Message.Text)
	return nil
}

In order to make your bot react to different messages, there are three different kind of handlers:

Kind handler

You can define handlers for the different kind of messages that the user can send to your bot. All the different kinds are defined here.

On this example, we are going to reply just to the messages that are a location sending the user a message back:

package main

import (
	"github.com/davilag/telego"
	"github.com/davilag/telego/api"
	"github.com/davilag/telego/kind"
)

func main() {
	bot := telego.Initialise("110201543:testTraceToken")

	bot.AddKindHandler(kind.Location, locationHandler)
	bot.Listen()
}

func locationHandler(u api.Update, c telego.Conversation) telego.FlowStep {
	c.SendMessage("That's a nice place!")
	return nil
}

And this is the output that we are going to have from our bot:

Command handler

The normal way of starting an interaction with a bot are commands. In order to set a handler for commands, we will need to call AddCommandHandler.

This example shows how to handle the /test command:

package main

import (
	"github.com/davilag/telego"
	"github.com/davilag/telego/api"
)

func main() {
	bot := telego.Initialise("110201543:testTraceToken")

	bot.AddCommandHandler("test", commandHandler)
	bot.Listen()
}

func commandHandler(u api.Update, c telego.Conversation) telego.FlowStep {
	c.SendMessage("¯Not sure what to do...")
	return nil
}

And this is the result of interacting with the bot:

Default handler

With Telego you also have the ability to react by default to any message. This is usually used to show the user a help message, for example to show them all the commands that you have. To initialise the default handler, you will need to use SetDefaultMessageHandler.

This default handler will be the last option of the bot in order to respond to the user's message. This is, if the message is compilant with another other defined handler (eg. kind or command), then this handler is not going to be executed.

On this example, we are going to be handling three kinds of messages, a /test command message, a /help command message and a default message which is going to show the help information:

package main

import (
	"github.com/davilag/telego"
	"github.com/davilag/telego/api"
)

func main() {
	bot := telego.Initialise("110201543:testTraceToken")
	bot.SetDefaultMessageHandler(helpCommand)
	bot.AddCommandHandler("test", testCommand)
	bot.AddCommandHandler("help", helpCommand)
	bot.Listen()
}

func helpCommand(u api.Update, c telego.Conversation) telego.FlowStep {
	c.SendMessage(`This are the different commands that this bot accepts:
		/test - Executes the test command.
		/help - Will show the help text.`)
	return nil
}

func testCommand(u api.Update, c telego.Conversation) telego.FlowStep {
	c.SendMessage("Executing the test command!")
	return nil
}

This configuration has the next output:

TODO List

  • Expand client to support more Telegram API features
  • Implement more unit tests

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Conversation

type Conversation struct {
	ChatID int // Chat ID to which we are storing the session

	Flow Flow // Flow that is going to be executed in this instance of he conversation

	Context map[string]interface{} // Context which is going to allow to the user store data which is going to be accessible from every step
	// contains filtered or unexported fields
}

Conversation abstraction to make send messages to an specific chat.

func (*Conversation) ReplyToMessage

func (c *Conversation) ReplyToMessage(m string, messageID int) (api.Message, error)

ReplyToMessage replies to a message in the conversation.

func (*Conversation) SendMessage

func (c *Conversation) SendMessage(m string) (api.Message, error)

SendMessage sends a message to the conversation

func (*Conversation) SendMessageWithKeyboard

func (c *Conversation) SendMessageWithKeyboard(m string, keyboardOptions []string) (api.Message, error)

SendMessageWithKeyboard sends a message showing a list of options to the user as a custom keyboard

func (*Conversation) SendVideo

func (c *Conversation) SendVideo(fileName string, file []byte) (api.Message, error)

SendVideo sends a video to the conversation given the filename and the file contents

type Flow

type Flow struct {
	ActualStep FlowStep // Step that has to be executed the next time that we receive an update
	TimeToLive int32    // Time to live of the session when executing this flow
}

Flow has the information about the next step that has to be executed into the flow and the time to live for that flow.

type FlowStep

type FlowStep func(api.Update, Conversation) FlowStep

FlowStep it accepts an update and a conversation and it returns the next step. In order to no execute any more steps, it has to return nil

type Telego

type Telego struct {
	Client TelegramClient // Client allows send messages to Telegram chats
	// contains filtered or unexported fields
}

Telego is the main struct on which we can define all the flows and handlers.

func Initialise

func Initialise(accessToken string) *Telego

Initialise inits the telegram instance with the telegram bot access token. See https://core.telegram.org/bots/api#authorizing-your-bot

func (*Telego) AddCommandHandler added in v0.1.2

func (t *Telego) AddCommandHandler(c string, fs FlowStep)

AddCommandHandler adds the step that it is going to be executed when we receive a certain command

func (*Telego) AddCommandHandlerSession added in v0.1.2

func (t *Telego) AddCommandHandlerSession(c string, fs FlowStep, ttl int32)

AddCommandHandlerSession adds the step that it is going to be executed when we receive a message certain command, keeping the information that the handler saves for the time defined in ttl

func (*Telego) AddKindHandler

func (t *Telego) AddKindHandler(k kind.Kind, fs FlowStep)

AddKindHandler adds the step that it is going to be executed when we receive a message of a certain kind

func (*Telego) AddKindHandlerSession

func (t *Telego) AddKindHandlerSession(k kind.Kind, fs FlowStep, ttl int32)

AddKindHandlerSession adds the step that it is going to be executed when we receive a message of a certain kind, keeping the information that the handler saves for the time defined in ttl

func (*Telego) Listen

func (t *Telego) Listen()

Listen main loop which is going to be listening for updates.

func (*Telego) SetDefaultMessageHandler

func (t *Telego) SetDefaultMessageHandler(f FlowStep)

SetDefaultMessageHandler Sets the default message handler for the telegram bot. It defines what we are going to do with messages that by default the bot doesn't understand (eg. send a description of the commands)

func (*Telego) SetTelegramHost

func (t *Telego) SetTelegramHost(tm string)

SetTelegramHost sets the telegram host where telegram is running

func (*Telego) SetupMetrics

func (t *Telego) SetupMetrics()

SetupMetrics sets up the metrics for a telegram bot. It exposes metrics when the bot sends a message, when the bot receives a message and the sessions that the bot is keeping with chat information.

type TelegramClient

type TelegramClient struct {
	AccessToken string
}

TelegramClient manages the connection to the Telegram API

func (*TelegramClient) ReplyToMessage

func (c *TelegramClient) ReplyToMessage(message string, chatID int, messageID int) (api.Message, error)

ReplyToMessage sends a message to a chat replying to the indicated message.

func (*TelegramClient) SendMessage

func (c *TelegramClient) SendMessage(mo api.MessageOut) (api.Message, error)

SendMessage sends a message with the filled MessageOut object.

func (*TelegramClient) SendMessageText

func (c *TelegramClient) SendMessageText(message string, chatID int) (api.Message, error)

SendMessageText sends the given message to the given chat ID

func (*TelegramClient) SendMessageWithKeyboard

func (c *TelegramClient) SendMessageWithKeyboard(message string, chatID int, keyboardOptions []string) (api.Message, error)

SendMessageWithKeyboard sends a message showing a list of options to the user as a custom keyboard

func (*TelegramClient) SendVideo

func (c *TelegramClient) SendVideo(fileName string, file []byte, chatID int) (api.Message, error)

SendVideo gets the filename and the slice of bytes with the contents of the file and sends it to the provided chat.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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