echotron

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2021 License: GPL-3.0 Imports: 14 Imported by: 1

README

echotron Language PkgGoDev Go Report Card License

Library for telegram bots written in pure go

Fetch with

go get -u github.com/NicoNex/echotron

Usage

Long Polling

A very simple implementation:

package main

import "github.com/NicoNex/echotron"

type bot struct {
    chatId int64
    echotron.Api
}

const TOKEN = "YOUR TELEGRAM TOKEN"

func newBot(chatId int64) echotron.Bot {
    return &bot{
        chatId,
        echotron.NewApi(TOKEN),
    }
}

func (b *bot) Update(update *echotron.Update) {
    if update.Message.Text == "/start" {
        b.SendMessage("Hello world", b.chatId)
    }
}

func main() {
    dsp := echotron.NewDispatcher(TOKEN, newBot)
    dsp.Run()
}

Also proof of concept with self destruction for low ram usage

package main

import (
    "time"

    "github.com/NicoNex/echotron"
)

type bot struct {
    chatId int64
    echotron.Api
}

const TOKEN = "YOUR TELEGRAM TOKEN"

var dsp echotron.Dispatcher

func newBot(chatId int64) echotron.Bot {
    var bot = &bot{
        chatId,
        echotron.NewApi(TOKEN),
    }
    go bot.selfDestruct(time.After(time.Hour))
    return bot
}

func (b *bot) selfDestruct(timech <- chan time.Time) {
    select {
    case <-timech:
        b.SendMessage("goodbye", b.chatId)
        dsp.DelSession(b.chatId)
    }
}

func (b *bot) Update(update *echotron.Update) {
    if update.Message.Text == "/start" {
        b.SendMessage("Hello world", b.chatId)
    }
}

func main() {
    dsp = echotron.NewDispatcher(TOKEN, newBot)
    dsp.Run()
}
Webhook
package main

import "github.com/NicoNex/echotron"

type bot struct {
	chatId int64
	echotron.Api
}

const TOKEN = "YOUR TELEGRAM TOKEN"

func newBot(chatId int64) echotron.Bot {
	return &bot{
		chatId,
		echotron.NewApi(TOKEN),
	}
}

func (b *bot) Update(update *echotron.Update) {
	if update.Message.Text == "/start" {
		b.SendMessage("Hello world", b.chatId)
	}
}

func main() {
	dsp := echotron.NewDispatcher(TOKEN, newBot)
	dsp.ListenWebhook("https://newworld:443/bot", 23456)
}

Documentation

Index

Constants

View Source
const (
	PARSE_MARKDOWN           Option = "&parse_mode=markdown"
	PARSE_HTML                      = "&parse_mode=html"
	DISABLE_WEB_PAGE_PREVIEW        = "&disable_web_page_preview=true"
	DISABLE_NOTIFICATION            = "&disable_notification=true"
)
View Source
const (
	TYPING            ChatAction = "typing"
	UPLOAD_PHOTO                 = "upload_photo"
	RECORD_VIDEO                 = "record_video"
	UPLOAD_VIDEO                 = "upload_video"
	RECORD_AUDIO                 = "record_audio"
	UPLOAD_AUDIO                 = "upload_audio"
	UPLOAD_DOCUMENT              = "upload_document"
	FIND_LOCATION                = "find_location"
	RECORD_VIDEO_NOTE            = "record_video_note"
	UPLOAD_VIDEO_NOTE            = "upload_video_note"
)

Variables

This section is empty.

Functions

func SendGetRequest

func SendGetRequest(url string) []byte

func SendPostForm

func SendPostForm(destUrl string, keyVals map[string]string) ([]byte, error)

func SendPostRequest

func SendPostRequest(url string, filename string, filetype string) []byte

Types

type APIResponseBase

type APIResponseBase struct {
	Ok          bool   `json:"ok"`
	ErrorCode   int    `json:"error_code,omitempty"`
	Description string `json:"description,omitempty"`
}

type APIResponseCommands

type APIResponseCommands struct {
	APIResponseBase
	Result []BotCommand `json:"result,omitempty"`
}

type APIResponseMessage

type APIResponseMessage struct {
	APIResponseBase
	Result *Message `json:"result,omitempty"`
}

This object represents the incoming response from Telegram servers. Used by the methods in the api.go module (since they return a Message).

type APIResponseUpdate

type APIResponseUpdate struct {
	APIResponseBase
	Result []*Update `json:"result,omitempty"`
}

This object represents the incoming response from Telegram servers. Used by getUpdates (since it returns an array of Updates).

type Api

type Api string

func NewApi

func NewApi(token string) Api

NewApi returns a new Api object.

func (Api) AnswerCallbackQuery

func (a Api) AnswerCallbackQuery(id, text string, showAlert bool) (response APIResponseMessage)

func (Api) Command

func (a Api) Command(command, description string) BotCommand

func (Api) DeleteMessage

func (a Api) DeleteMessage(chatId int64, messageId int) (response APIResponseMessage)

func (Api) DeleteWebhook

func (a Api) DeleteWebhook() (response APIResponseUpdate)

DeleteWebhook deletes webhook

func (Api) EditMessageReplyMarkup

func (a Api) EditMessageReplyMarkup(chatId int64, messageId int, keyboard []byte) (response APIResponseMessage)

func (Api) EditMessageText

func (a Api) EditMessageText(chatId int64, messageId int, text string, opts ...Option) (response APIResponseMessage)

func (Api) EditMessageTextWithKeyboard

func (a Api) EditMessageTextWithKeyboard(chatId int64, messageId int, text string, keyboard []byte, opts ...Option) (response APIResponseMessage)

func (Api) GetChat

func (a Api) GetChat(chatId int64) (response Chat)

Returns the current chat in use.

func (Api) GetMyCommands

func (a Api) GetMyCommands() (response APIResponseCommands)

func (Api) GetStickerSet

func (a Api) GetStickerSet(name string) (response StickerSet)

func (Api) GetUpdates

func (a Api) GetUpdates(offset, timeout int) (response APIResponseUpdate)

GetResponse returns the incoming updates from telegram.

func (Api) InlineKbdBtn

func (a Api) InlineKbdBtn(text, url, callbackData string) InlineButton

Returns a new inline keyboard button with the provided data.

func (Api) InlineKbdBtnCbd

func (a Api) InlineKbdBtnCbd(text, callbackData string) InlineButton

Same as InlineKbdBtn, but only with callbackData.

func (Api) InlineKbdBtnUrl

func (a Api) InlineKbdBtnUrl(text, url string) InlineButton

Same as InlineKbdBtn, but only with url.

func (Api) InlineKbdMarkup

func (a Api) InlineKbdMarkup(inlineKbdRows ...InlineKbdRow) (jsn []byte)

Returns a byte slice containing the inline keyboard json data.

func (Api) InlineKbdRow

func (a Api) InlineKbdRow(inlineButtons ...InlineButton) InlineKbdRow

Returns a new inline keyboard row with the given buttons.

func (Api) KeyboardButton

func (a Api) KeyboardButton(text string, requestContact, requestLocation bool) Button

func (Api) KeyboardMarkup

func (a Api) KeyboardMarkup(resizeKeyboard, oneTimeKeyboard, selective bool, keyboardRows ...KbdRow) (kbd []byte)

func (Api) KeyboardRemove

func (a Api) KeyboardRemove(selective bool) (kbdrmv []byte)

func (Api) KeyboardRow

func (a Api) KeyboardRow(buttons ...Button) (kbdRow KbdRow)

func (Api) SendAnimation

func (a Api) SendAnimation(filename, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendAnimationByID

func (a Api) SendAnimationByID(animationId string, chatId int64) (response APIResponseMessage)

func (Api) SendAudio

func (a Api) SendAudio(filename, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendAudioByID

func (a Api) SendAudioByID(audioId, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendChatAction

func (a Api) SendChatAction(action ChatAction, chatId int64) (response APIResponseMessage)

func (Api) SendContact

func (a Api) SendContact(phoneNumber, firstName, lastName string, chatId int64) (response APIResponseMessage)

func (Api) SendDocument

func (a Api) SendDocument(filename, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendDocumentByID

func (a Api) SendDocumentByID(documentId, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendMessage

func (a Api) SendMessage(text string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendMessageReply

func (a Api) SendMessageReply(text string, chatId int64, messageId int, opts ...Option) (response APIResponseMessage)

Sends a message as a reply to a previously received one.

func (Api) SendMessageWithKeyboard

func (a Api) SendMessageWithKeyboard(text string, chatId int64, keyboard []byte, opts ...Option) (response APIResponseMessage)

func (Api) SendPhoto

func (a Api) SendPhoto(filename, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendPhotoByID

func (a Api) SendPhotoByID(photoId, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendPhotoWithKeyboard

func (a Api) SendPhotoWithKeyboard(filename, caption string, chatId int64, keyboard []byte, opts ...Option) (response APIResponseMessage)

func (Api) SendStickerByID

func (a Api) SendStickerByID(stickerId string, chatId int64) (response APIResponseMessage)

func (Api) SendVideo

func (a Api) SendVideo(filename, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendVideoByID

func (a Api) SendVideoByID(videoId, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendVideoNoteByID

func (a Api) SendVideoNoteByID(videoId string, chatId int64) (response APIResponseMessage)

func (Api) SendVoice

func (a Api) SendVoice(filename, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SendVoiceByID

func (a Api) SendVoiceByID(voiceId, caption string, chatId int64, opts ...Option) (response APIResponseMessage)

func (Api) SetMyCommands

func (a Api) SetMyCommands(commands ...BotCommand) (response APIResponseCommands)

func (Api) SetWebhook

func (a Api) SetWebhook(url string) (response APIResponseUpdate)

SetWebhook sets the webhook to bot on Telegram servers

type Audio

type Audio struct {
	FileId    string     `json:"file_id"`
	Duration  int        `json:"duration"`
	Performer string     `json:"performer,omitempty"`
	Title     string     `json:"title,omitempty"`
	MimeType  string     `json:"mime_type,omitempty"`
	FileSize  int        `json:"file_size,omitempty"`
	Thumb     *PhotoSize `json:"thumb,omitempty"`
}

This object represents an audio file to be treated as music by the Telegram clients.

type Bot

type Bot interface {
	// Update will be called upon receiving any update from Telegram.
	Update(*Update)
}

Bot is the interface that must be implemented by your definition of the struct thus it represent each open session with a user on Telegram.

type BotCommand

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

type Button

type Button struct {
	Text            string `json:"text"`
	RequestContact  bool   `json:"request_contact,omitempty"`
	RequestLocation bool   `json:"request_location,omitempty"`
}

This object represents a button in a keyboard.

type CallbackQuery

type CallbackQuery struct {
	ID              string   `json:"id"`
	User            *User    `json:"from"`
	Message         *Message `json:"message,omitempty"`
	InlineMessageId string   `json:"inline_message_id,omitempty"`
	Data            string   `json:"data,omitempty"`
}

This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.

type Chat

type Chat struct {
	ID                 int64    `json:"id"`
	Type               string   `json:"type"`
	Title              string   `json:"title,omitempty"`
	Username           string   `json:"username,omitempty"`
	FirstName          string   `json:"first_name,omitempty"`
	LastName           string   `json:"last_name,omitempty"`
	AllMembersAreAdmin bool     `json:"all_members_are_administrators,omitempty"`
	Description        string   `json:"description,omitempty"`
	InviteLink         string   `json:"invite_link,omitempty"`
	PinnedMessage      *Message `json:"pinned_message,omitempty"`
}

This object represents a chat.

type ChatAction

type ChatAction string

type ChosenInlineResult

type ChosenInlineResult struct {
	ID              string `json:"result_id"`
	User            *User  `json:"user"`
	InlineMessageId string `json:"inline_message_id,omitempty"`
	Query           string `json:"query,omitempty"`
}

Represents a result of an inline query that was chosen by the user and sent to their chat partner.

type Contact

type Contact struct {
	PhoneNumber string `json:"phone_number"`
	FirstName   string `json:"first_name"`
	LastName    string `json:"last_name,omitempty"`
	UserID      int    `json:"user_id,omitempty"`
	Vcard       string `json:"vcard,omitempty"`
}

This object represents a phone contact.

type Dispatcher

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

func NewDispatcher

func NewDispatcher(token string, newBot NewBotFn) Dispatcher

NewDispatcher returns a new instance of the Dispatcher object; useful for polling telegram and dispatch every update to the corresponding Bot instance.

func (*Dispatcher) AddSession

func (d *Dispatcher) AddSession(chatId int64)

AddSession allows to arbitrarily create a new Bot instance.

func (*Dispatcher) DelSession

func (d *Dispatcher) DelSession(chatId int64)

DelSession deletes the Bot instance, seen as a session, from the map with all of them.

func (*Dispatcher) ListenWebhook

func (d *Dispatcher) ListenWebhook(url string, internalPort int)

ListenWebhook sets a webhook and listens for incoming updates

func (*Dispatcher) Poll

func (d *Dispatcher) Poll()

Poll starts the polling loop so that the dispatcher calls the function Update upon receiving any update from Telegram.

type Document

type Document struct {
	FileId   string     `json:"file_id"`
	Thumb    *PhotoSize `json:"thumb,omitempty"`
	FileName string     `json:"file_name,omitempty"`
	MimeType string     `json:"mime_type,omitempty"`
	FileSize int        `json:"file_size,omitempty"`
}

This object represents a general file (as opposed to photos, voice messages and audio files).

type InlineButton

type InlineButton struct {
	Text         string `json:"text"`
	URL          string `json:"url,omitempty"`
	CallbackData string `json:"callback_data,omitempty"`
}

This object represents a button in an inline keyboard.

type InlineKbdRow

type InlineKbdRow []InlineButton

This object represents a row of buttons in an inline keyboard.

type InlineKeyboard

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

This object represents an inline keyboard.

type InlineQuery

type InlineQuery struct {
	ID     string `json:"id"`
	User   *User  `json:"user"`
	Query  string `json:"query"`
	Offset string `json:"offset"`
}

This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.

type KbdRow

type KbdRow []Button

This object represents a row of buttons in a keyboard.

type Keyboard

type Keyboard struct {
	Keyboard        []KbdRow `json:"keyboard"`
	ResizeKeyboard  bool     `json:"resize_keyboard,omitempty"`
	OneTimeKeyboard bool     `json:"one_time_keyboard,omitempty"`
	Selective       bool     `json:"selective,omitempty"`
}

This object represents a keyboard.

type KeyboardRemove

type KeyboardRemove struct {
	RemoveKeyboard bool `json:"remove_keyboard"`
	Selective      bool `json:"selective,omitempty"`
}

This object represents a keyboard removal request.

type Location

type Location struct {
	Longitude float32
	Latitude  float32
}

This object represents a point on the map.

type MaskPosition

type MaskPosition struct {
	Point  string  `json:"point"`
	XShift float32 `json:"x_shift"`
	YShift float32 `json:"y_shift"`
	Scale  float32 `json:"scale"`
}

This object describes the position on faces where a mask should be placed by default.

type Message

type Message struct {
	ID             int              `json:"message_id"`
	User           *User            `json:"from"`
	Chat           *Chat            `json:"chat"`
	Date           int64            `json:"date"`
	Text           string           `json:"text"`
	Entities       []*MessageEntity `json:"entities,omitempty"`
	Audio          *Audio           `json:"audio,omitempty"`
	Document       *Document        `json:"document,omitempty"`
	Photo          []*PhotoSize     `json:"photo,omitempty"`
	MediaGroupId   string           `json:"media_group_id,omitempty"`
	Sticker        *Sticker         `json:"sticker,omitempty"`
	Video          *Video           `json:"video,omitempty"`
	VideoNote      *VideoNote       `json:"video_note,omitempty"`
	Voice          *Voice           `json:"voice,omitempty"`
	Caption        string           `json:"caption,omitempty"`
	Contact        *Contact         `json:"contact,omitempty"`
	Location       *Location        `json:"location,omitempty"`
	NewChatMember  []*User          `json:"new_chat_members,omitempty"`
	LeftChatMember *User            `json:"left_chat_member,omitempty"`
	PinnedMessage  *Message         `json:"pinned_message,omitempty"`
}

WIP: this object represents a message.

type MessageEntity

type MessageEntity struct {
	Type   string `json:"type"`
	Offset int    `json:"offset"`
	Length int    `json:"Length"`
	Url    string `json:"url,omitempty"`
	User   *User  `json:"user,omitempty"`
}

This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.

type NewBotFn

type NewBotFn func(chatId int64) Bot

type Option

type Option string

type PhotoSize

type PhotoSize struct {
	FileId   string `json:"file_id"`
	Width    int    `json:"width"`
	Height   int    `json:"height"`
	FileSize int    `json:"FileSize"`
}

This object represents one size of a photo or a file / sticker thumbnail.

type Sticker

type Sticker struct {
	FileId       string       `json:"file_id"`
	Width        int          `json:"width"`
	Height       int          `json:"height"`
	Thumb        *PhotoSize   `json:"thumb,omitempty"`
	Emoji        string       `json:"emoji,omitempty"`
	SetName      string       `json:"set_name,omitempty"`
	FileSize     int          `json:"file_size,omitempty"`
	MaskPosition MaskPosition `json:"mask_position"`
}

This object represents a sticker.

type StickerSet

type StickerSet struct {
	Name          string     `json:"name"`
	Title         string     `json:"title"`
	ContainsMasks bool       `json:"contains_masks"`
	Stickers      []*Sticker `json:"sticker"`
}

This object represents a sticker set.

type Update

type Update struct {
	ID                 int                 `json:"update_id"`
	Message            *Message            `json:"message,omitempty"`
	EditedMessage      *Message            `json:"edited_message,omitempty"`
	ChannelPost        *Message            `json:"channel_post,omitempty"`
	EditedChannelPost  *Message            `json:"edited_channel_post,omitempty"`
	InlineQuery        *InlineQuery        `json:"inline_query,omitempty"`
	ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result,omitempty"`
	CallbackQuery      *CallbackQuery      `json:"callback_query,omitempty"`
}

This object represents an incoming update. At most one of the optional parameters can be present in any given update.

type User

type User struct {
	ID           int    `json:"id"`
	IsBot        bool   `json:"is_bot"`
	FirstName    string `json:"first_name"`
	LastName     string `json:"last_name,omitempty"`
	Username     string `json:"username,omitempty"`
	LanguageCode string `json:"language_code,omitempty"`
}

This object represents a Telegram user or bot.

type Video

type Video struct {
	FileId   string     `json:"file_id"`
	Width    int        `json:"width"`
	Height   int        `json:"height"`
	Duration int        `json:"duration"`
	Thumb    *PhotoSize `json:"thumb,omitempty"`
	MimeType string     `json:"mime_type,omitempty"`
	FileSize int        `json:"file_size,omitempty"`
}

This object represents a video file.

type VideoNote

type VideoNote struct {
	FileId   string     `json:"file_id"`
	Length   int        `json:"length"`
	Duration int        `json:"duration"`
	Thumb    *PhotoSize `json:"thumb,omitempty"`
	FileSize int        `json:"file_size,omitempty"`
}

This object represents a video message.

type Voice

type Voice struct {
	FileId   string `json:"file_id"`
	Duration int    `json:"duration"`
	MimeType string `json:"mime_type,omitempty"`
	FileSize int    `json:"FileSize,omitempty"`
}

This object represents a voice note.

Jump to

Keyboard shortcuts

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