telebot

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2021 License: MIT Imports: 10 Imported by: 0

README

Telebot

Go Reference

Telebot is a Go wrapper for the Telegram Bot API. It provides a convenient way to write a Telegram in Go whitout diving in Telegram API. Updates are receveived from Telegram either with Telegram Webhook or with calls to Telegram /getUpdates API endpoint.

How to build a Go Telegram bot with telebot ?

In order to build a bot, follow the steps :

  • Create a bot with the appropriate config
    const apiToken = "<your token>"
    // Ignore config if you don't want to use Webhook
    config := make(map[string]string)

    config["WebhookUrl"] = "<public url of your bot>"
    config["IpAddr"] = "<ip of your bot>"
    config["SslCertificate"] = "<path to .crt SSL cert file>"
    config["SslPrivkey"] = "<path to .key SSL cert file>"

    // Replace config with nil if you want to fetch Updates with the /getUpdates endpoint.
    bot := telebot.CreateBot(apiToken, config)
  • Write handlers and link it to your bot with the OnText function
    bot.OnText("/test", func(u *telebot.Update) {
    const text = "I hear you loud and clear !"
    const chatId = u.Message.Chat.Id
    _, err := telebot.SendTextMessage(chatId, text, telebot.SendMessageOptions{})

    if err != nil {
        log.Printf("Error sending message: %s", err.Error())
        }
    })

    bot.OnCommand("/repeat", func(u *telebot.Update) {
        payload := u.Message.Text[len("/repeat"):]
        chatId := u.Message.Chat.Id

        _, err := bot.SendTextMessage(chatId, payload, telebot.SendMessageOptions{})

        if err != nil {
            log.Printf("Error sending message: %s", err.Error())
        }
    })
  • And last but not least, start the bot
    bot.Start()
List of events available

The Events are defined in constants.go.

  • ONCOMMAND: Match messages starting with a command (Ex : In /repeat Hello World !, the command is /repeat and the payload is Hello World !)

Below is an example making the bot repeat the payload:

bot.OnCommand("/repeat", func(u *telebot.Update) {
    payload := u.Message.Text[len("/repeat"):]
    chatId := u.Message.Chat.Id

    _, err := bot.SendTextMessage(chatId, payload, telebot.SendMessageOptions{})

    if err != nil {
        log.Printf("Error sending message: %s", err.Error())
    }
})
  • ONTEXT: Match exactly the text of the message

Below is an example matching the message /hello but not /hello you:

bot.OnText("/hello", func(u *telebot.Update) {
    text := "Hello World !"
    chatId := u.Message.Chat.Id
    _, err := bot.SendTextMessage(chatId, text, telebot.SendMessageOptions{})

    if err != nil {
        log.Printf("Error sending message: %s", err.Error())
    }
})
  • ONCALLBACK: Match a CallbackQuery with exact data match

Below is an example matching a callback with Yes as data and deleting the message linked to the callback.

bot.OnCallback("Yes", func(u *telebot.Update) {
    chatId := u.CallbackQuery.Message.Chat.Id
    messageId := u.CallbackQuery.Message.Id

    res, err := bot.DeleteMessage(chatId, messageId)

    if err != nil {
        log.Printf("Error deleting message: %s", err.Error())
    }
})
  • ONPAYLOAD: Match a CallbackQuery with data starting with the filter

Below is an example matching a callback event with a payload starting with Yes and delete the source message.

bot.OnPayload("Yes", func(u *telebot.Update) {
    chatId := u.CallbackQuery.Message.Chat.Id
    messageId := u.CallbackQuery.Message.Id

    res, err := bot.DeleteMessage(chatId, messageId)

    if err != nil {
        log.Printf("Error deleting message: %s", err.Error())
    }
})

How to make the bot send content to Telegram chat with telebot ?

In addition to update reception, telebot has some functions designed to make your bot send content. You can use it in your handlers.

List of message methods available

Methods aiming at sending messages are defined in messages.go.

  • SendTextMessage: Sends a text message.
bot.SendTextMessage(chatId int, text string, options telebot.SendMessageOptions)
    bot.OnCommand("/repeat", func(u *telebot.Update) {
        payload := u.Message.Text[len("/repeat"):]
        chatId := u.Message.Chat.Id

        _, err := bot.SendTextMessage(chatId, payload, telebot.SendMessageOptions{ReplyToMessageId: u.Message.Id, AllowSendingWithoutReply: true, DisableWebPagePreview: true})

        if err != nil {
            log.Printf("Error sending message: %s", err.Error())
        }
    })

Options are a struct with type and supports telegram API options described here with the same name.

type SendMessageOptions struct {
    ParseMode                string
    DisableWebPagePreview    bool
    DisableNotification      bool
    ReplyToMessageId         int
    AllowSendingWithoutReply bool
}
  • SendReplyKeyboardMarkupTextMessage: Send a text message with a ReplyKeyboardMarkup keyboard.
bot.SendReplyKeyboardMarkupTextMessage(chatId int, text string, keyboard ReplyKeyboardMarkup, options SendMessageOptions)

You can create a custom reply keyboard and send the message with the following code snippet.

text := "Your text here"
yesButton := telebot.KeyboardButton{"Yes"}
noButton := telebot.KeyboardButton{"No"}
firstRow := []telebot.KeyboardButton{yesButton, noButton}
keyboard := telebot.ReplyKeyboardMarkup{Keyboard: [][]telebot.KeyboardButton{firstRow}}

res, err := bot.SendReplyKeyboardMarkupTextMessage(chatId, text, keyboard, telebot.SendMessageOptions{})
  • SendReplyKeyboardRemoveTextMessage: Send a text message with a ReplyKeyboardRemove keyboard
bot.SendReplyKeyboardRemoveTextMessage(chatId int, text string, selective bool, options SendMessageOptions)
  • SendInlineKeyboardMarkupTextMessage: Send a text message with an inline keyboard
bot.SendInlineKeyboardMarkupTextMessage(chatId int, text string, keyboard InlineKeyboardMarkup, options SendMessageOptions)

You can define a custom inline keyboard the same way as below.

bot.OnText("/hello", func(u *telebot.Update) {
    chatId := u.Message.Chat.Id
    text := "Hello ?"

    yesButton := telebot.InlineKeyboardButton{"Hello !", "Hello"}
    noButton := telebot.InlineKeyboardButton{"WHo are you", "WhoAreYou"}

    firstRow := []telebot.InlineKeyboardButton{yesButton, noButton}
    keyboard := telebot.InlineKeyboardMarkup{[][]telebot.InlineKeyboardButton{firstRow}}

    res, err := bot.SendInlineKeyboardMarkupTextMessage(chatId, text, keyboard, telebot.SendMessageOptions{})

    if err != nil {
            log.Printf("Error sending message: %s", err.Error())
        }

})
  • EditTextMessage: Edit a text message
bot.EditTextMessage(chatId int, newText string, messageId int, options SendMessageOptions)

Some message options are available. Specify the options using SendMessageOptions like if you were using SendTextMessage to send a message.

  • EditInlineKeyboardTextMessage: Edit a text message with InlineKeyboardMarkup
bot.EditInlineKeyboardTextMessage(chatId int, newText string, messageId int, newKeyboard InlineKeyboardMarkup, options SendMessageOptions)
  • EditMessageInlineKeyboardMarkup: Edit the inline keyboard of a message
bot.EditMessageInlineKeyboardMarkup(chatId int, messageId int, newKeyboard InlineKeyboardMarkup)
  • DeleteMessage: Delete a message
bot.DeleteMessage(chatId int, messageId int)
List of callback methods available

Some methods defined in callback.go can be used to answer CallbackQueries.

  • AnswerCallbackQuery: Answer a callback query without notification
bot.AnswerCallbackQuery(callbackQueryId string)
  • AnswerCallbackQueryNotification: Answer a callback query with notification
bot.AnswerCallbackQueryNotification(callbackQueryId string, text string, showAlert bool)
List of chat methods available

You can use the methods defined in chat.go to manage a channel (kick, unban users)

  • KickChatMember: Kick an user from a group
bot.KickChatMember(chatId int, userId int)
  • UnbanChatMember: Unban an user from a group
bot.UnbanChatMember(chatId int, userId int)
List of dice methods

The methods defined in dice.go allow your bot to send random animated emoji such as a dice toss

  • SendDice: Sends a dice.
bot.SendDice(chatId int, options telebot.SendMessageOptions)
    bot.OnText("/dice", func(u *telebot.Update) {
        chatId := u.Message.Chat.Id

        _, err := bot.SendDice(chatId, telebot.SendMessageOptions{ReplyToMessageId: u.Message.Id, AllowSendingWithoutReply: true})

        if err != nil {
            log.Printf("Error sending message: %s", err.Error())
        }
    })
  • SendRandomDice: send a random dice
bot.SendRandomDice(chatId int, options SendMessageOptions)
  • SendDiceEmoji: Send a dice Emoji (Supported emojis : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Default is “🎲”. )
bot.SendDiceEmoji(chatId int, emoji string, options SendMessageOptions)

Check the Telegram API documentation to see the options of Telegram sendDice API function supported (defined in telebot.SendMessageOptions).

Example bot

Below is an example of a simple bot that you can use to experiment with telebot.

package main

import (
    "log"

    "github.com/fabienzucchet/telebot"
)

func main() {

    // Define Telegram API token.
    const apiToken = "changeme"

    // If you want to use webhook, define config.
    config := make(map[string]string)

    config["WebhookUrl"] = "changeme"
    config["IpAddr"] = "changeme"
    config["SslCertificate"] = "changeme"
    config["SslPrivkey"] = "changeme"

    // Replace config with nil below to use an update loop instead of a webhook.
    bot := telebot.CreateBot(apiToken, config)

    // Bind a handler to the message /text.
    bot.OnText("/test", func(u *telebot.Update) {
        text := "I hear you <strong>loud and clear </strong> !"
        chatId := u.Message.Chat.Id
        parseMode := "HTML"

        _, err := bot.SendTextMessage(chatId, text, telebot.SendMessageOptions{ParseMode: parseMode})

        if err != nil {
            log.Printf("Error sending message: %s", err.Error())
        }
    })

    // Bin a handler to the command /repeat
    bot.OnCommand("/repeat", func(u *telebot.Update) {
        payload := u.Message.Text[len("/repeat"):]
        chatId := u.Message.Chat.Id

        _, err := bot.SendTextMessage(chatId, payload, telebot.SendMessageOptions{ReplyToMessageId: u.Message.Id, AllowSendingWithoutReply: true, DisableWebPagePreview: true})

        if err != nil {
            log.Printf("Error sending message: %s", err.Error())
        }
    })

    // Start the bot.
    bot.Start()

}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ONCALLBACK = Event{
	Identifier: "oncallback",
	Checker: func(toCheck string, filter string) bool {
		return toCheck == filter
	},
}

Match a CallbackQuery with exact data match

View Source
var ONCOMMAND = Event{
	Identifier: "oncommand",
	Checker: func(toCheck string, filter string) bool {

		var match bool

		if len(toCheck) > 0 && toCheck[0:1] == "/" {
			match, _ = regexp.MatchString("^"+toCheck+".*", filter)
		} else {
			match, _ = regexp.MatchString("^/"+toCheck+".*", filter)
		}
		return match
	},
}

Match commands (i.e. when text starts with the filter but can contain more text)

View Source
var ONPAYLOAD = Event{
	Identifier: "onpayload",
	Checker: func(toCheck string, filter string) bool {
		match, _ := regexp.MatchString("^"+toCheck+".*", filter)
		return match
	},
}

Match a CallbackQuery with data starting with filter

View Source
var ONTEXT = Event{
	Identifier: "ontext",
	Checker: func(toCheck string, filter string) bool {
		return toCheck == filter
	},
}

Match text (i.e. exact match between text and filter)

Functions

This section is empty.

Types

type Bot

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

Bot object definition.

func CreateBot

func CreateBot(apiToken string, config map[string]string) Bot

Create a bog with the appropriate config.

func (*Bot) AnswerCallbackQuery added in v0.4.0

func (b *Bot) AnswerCallbackQuery(callbackQueryId string) (string, error)

Answer a callback query without notification

func (*Bot) AnswerCallbackQueryNotification added in v0.4.0

func (b *Bot) AnswerCallbackQueryNotification(callbackQueryId string, text string, showAlert bool) (string, error)

Answer a callback query with notification

func (*Bot) DeleteMessage added in v0.5.0

func (b *Bot) DeleteMessage(chatId int, messageId int) (string, error)

Delete a message

func (*Bot) EditInlineKeyboardTextMessage added in v0.5.0

func (b *Bot) EditInlineKeyboardTextMessage(chatId int, newText string, messageId int, newKeyboard InlineKeyboardMarkup, options SendMessageOptions) (string, error)

Edit a text message with InlineKeyboardMarkup

func (*Bot) EditMessageInlineKeyboardMarkup added in v0.5.0

func (b *Bot) EditMessageInlineKeyboardMarkup(chatId int, messageId int, newKeyboard InlineKeyboardMarkup) (string, error)

Edit the inline keyboard of a message

func (*Bot) EditTextMessage added in v0.5.0

func (b *Bot) EditTextMessage(chatId int, newText string, messageId int, options SendMessageOptions) (string, error)

Edit a text message.

func (*Bot) KickChatMember added in v0.3.3

func (b *Bot) KickChatMember(chatId int, userId int) (string, error)

Kick an user from a group.

func (*Bot) OnCallback added in v0.4.0

func (b *Bot) OnCallback(data string, handler func(u *Update))

Match CallbackQuery

func (*Bot) OnCommand added in v0.2.0

func (b *Bot) OnCommand(text string, description string, handler func(u *Update))

Match commands (i.e. when text starts with the filter but can contain more text)

func (*Bot) OnPayload added in v0.4.0

func (b *Bot) OnPayload(data string, handler func(u *Update))

Match CallbackQuery with payload

func (*Bot) OnText

func (b *Bot) OnText(text string, handler func(u *Update))

Trigger handler if the text of the update matches the variable text.

func (*Bot) SendDice added in v0.3.2

func (b *Bot) SendDice(chatId int, options SendMessageOptions) (string, error)

send a dice

func (*Bot) SendDiceEmoji added in v1.0.0

func (b *Bot) SendDiceEmoji(chatId int, emoji string, options SendMessageOptions) (string, error)

Send a dice Emoji (Supported emojis : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Default is “🎲”. )

func (*Bot) SendInlineKeyboardMarkupTextMessage added in v0.4.0

func (b *Bot) SendInlineKeyboardMarkupTextMessage(chatId int, text string, keyboard InlineKeyboardMarkup, options SendMessageOptions) (string, error)

Send a text message with an inline keyboard

func (*Bot) SendRandomDice added in v1.0.0

func (b *Bot) SendRandomDice(chatId int, options SendMessageOptions) (string, error)

send a random dice

func (*Bot) SendReplyKeyboardMarkupTextMessage added in v0.4.0

func (b *Bot) SendReplyKeyboardMarkupTextMessage(chatId int, text string, keyboard ReplyKeyboardMarkup, options SendMessageOptions) (string, error)

Send a text message with a ReplyKeyboardMarkup keyboard

func (*Bot) SendReplyKeyboardRemoveTextMessage added in v0.4.0

func (b *Bot) SendReplyKeyboardRemoveTextMessage(chatId int, text string, selective bool, options SendMessageOptions) (string, error)

Send a text message with a ReplyKeyboardRemove keyboard

func (*Bot) SendTextMessage added in v0.2.0

func (b *Bot) SendTextMessage(chatId int, text string, options SendMessageOptions) (string, error)

Send the message text in the chat chatId.

func (*Bot) Start

func (b *Bot) Start()

Start the bot.

func (*Bot) UnbanChatMember added in v0.3.3

func (b *Bot) UnbanChatMember(chatId int, userId int) (string, error)

Unban a member from a group.

type BotCommand added in v0.6.0

type BotCommand struct {
	Command     string `json:"command"`
	Description string `json:"description"`
}

type CallbackQuery added in v0.4.0

type CallbackQuery struct {
	Id      string  `json:"id"`
	From    User    `json:"from"`
	Message Message `json:"message"`
	Data    string  `json:"data"`
}

type Cert

type Cert struct {
	Privkey     string
	Certificate string
}

Paths to SSL certificate .key and .crt file

type Chat

type Chat struct {
	Id int `json:"id"`
}

Chat type corresponding to the interesting part of the Chat Object in the Telegram API.

type Event added in v0.2.0

type Event struct {
	Identifier string
	Checker    func(toCheck string, filter string) bool
}

Event type : contains an identifier and a checker function.

type GetUpdateResponse

type GetUpdateResponse struct {
	Ok     bool     `json:"ok"`
	Result []Update `json:"result"`
}

Structure of the /getUpdates response body.

type InlineKeyboardButton added in v0.4.0

type InlineKeyboardButton struct {
	Text         string `json:"text"`
	CallbackData string `json:"callback_data"`
}

type InlineKeyboardMarkup added in v0.4.0

type InlineKeyboardMarkup struct {
	InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
}

type KeyboardButton added in v0.4.0

type KeyboardButton struct {
	Text string `json:"text"`
}

type Message

type Message struct {
	Id   int    `json:"message_id"`
	Text string `json:"text"`
	From User   `json:"from"`
	Chat Chat   `json:"chat"`
}

Message type corresponding to the interesting part of the Message Object in the Telegram API.

type ReplyKeyboardMarkup added in v0.4.0

type ReplyKeyboardMarkup struct {
	Keyboard        [][]KeyboardButton `json:"keyboard"`
	ResizeKeyboard  bool               `json:"resize_keyboard"`
	OneTimeKeyboard bool               `json:"one_time_keyboard"`
	Selective       bool               `json:"selective"`
}

type ReplyKeyboardRemove added in v0.4.0

type ReplyKeyboardRemove struct {
	RemoveKeyboard bool `json:"remove_keyboard"`
	Selective      bool `json:"selective"`
}

type SendMessageOptions added in v0.3.1

type SendMessageOptions struct {
	ParseMode                string
	DisableWebPagePreview    bool
	DisableNotification      bool
	ReplyToMessageId         int
	AllowSendingWithoutReply bool
}

Option type for the sendMessage API

type Update

type Update struct {
	UpdateId      int           `json:"update_id"`
	Message       Message       `json:"message"`
	CallbackQuery CallbackQuery `json:"callback_query"`
}

Update type corresponding to the interesting part of the Update Object in the Telegram API.

type User

type User struct {
	Id       int    `json:"id"`
	Username string `json:"username"`
}

User type corresponding to the interesting part of the User Object in the Telegram API.

Jump to

Keyboard shortcuts

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