tg

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 17 Imported by: 3

README

nxs-go-telegram

Nxs-go-telegram based on Go Telegram Bot API and has built-in sessions allows you to develop complex bots. Your bot may use either webhook or get update modes.

The main idea of nxs-go-telegram based on a states and handlers. Each handler does some actions and returns (switches bot to) a new state. First user interaction with bot starts a session. During a session life cycle bot has a certain state.

General nxs-go-telegram components are follows:

  • Queue
  • Updates chain
  • Session

General components

Queue

Every update from Telegram received by the bot seves in the appropriate queue in Redis. Queues are separated by a chat ID and user ID got from updates. After update arrived to bot it puts into queue. Each queue contains one or more updates with protected time interval (stored in meta). After new update adds into the queue this interval increases for specified amount of time. A queue can be processed only after protected time interval has been reached.

In accordance with the selected mode (webhook or get update) you are able to choose following methods to put obtained update into the queue:

  • For webhook mode After new update arrived to an endpoint in your app's API use the tg.UpdateAbsorb() to add it into queue.
  • For get update mode Use tg.GetUpdates() to get available updates from Telegram. This function creates and listens a special channel and calls tg.UpdateAbsorb() for every updates.
Updates chain

In order to processing an update queues use Processing() method for your bot. This method will lookups an available queue with reached protected time interval and wolly extracts into updates chain. Updates chain will got a type by the first update in the queue. All updates with different types will be dropped while extracted. After an updates chain has been formed it will be processed in accordance with bot description and current session state.

At this time updates chain can take the following values:

  • Message
  • Callback
Sessions

Bot's behaviour based on session model and described by different states. As a queue, session defines by chat ID and user ID and has the following values:

  • State: it is a name of stated defined in bot description.
  • Slots: in other words it is a build-in storage. You may put and get to/from the specified slot any data you want on every state of session. You may operate with slots within an any handler.

Bot description

Bot description defines following elements:

  • Commands
  • States
  • InitHandler
  • ErrorHandler
  • DestroyHandler

Note that it is not recommended to send messages to user directly from any handler.

Commands

It is a set of Telegram commands that can be used by users. Each command has the following properties:

  • Command: string, defines a command name (excluding leading '/' character).
  • Description: string, defines a command description.
  • Handler: function, determines a function that will be done when user execute appropriate command. Handler function does defined actions and returns a new state bot will be switched to.

After your app has been started defined commands will be automatically set for your bot.

States

Each session state has following properties:

  • StateHandler
  • MessageHandler
  • CallbackHandler
  • SentHandler

Library has two special states you may use within a your handlers:

  • tg.SessStateBreak(): do not switch a session into new state (stay in a current state).
  • tg.SessStateDestroy(): destroy session. It will be clear all session data including session state and slots. Bot will go to its original state.
  • tg.SessStateContinue(): used only for PrimeHandler to continue execute of source handler after PrimeHandler was called.

In other cases to switch session to state you want use tg.SessState(botNewState).

StateHandler

This handler called when session switched to appropriate state. The main goal of this handler is a prepare message (incl. text and buttons) will be sent to user and define a new session state. If MessageHandler defined for state a session will not be switched to a new state and specified new state will be ignored.

Note that after any user actions bot will switched its states until goes a state with break next state or defined MessageHandler.

MessageHandler

This handler is called for an appropriate state when user sends a message. After message has been processed handler must returns a new session state.

If this handler is defined bot can change its state only in following cases:

  • User send a message to bot
  • User click some button
  • User execute some defined command
CallbackHandler

This handler is called for an appropriate state when user send a callback (click the button). After callback has been processed handler must returns a new session state.

If this handler is not defined bot will ignore any user buttons click for appropriate state.

SentHandler

This handler is called for an appropriate state after message prepared in StateHandler is sent to user. It useful for get sent messages ID.

PrimeHandler

PrimeHandler is a handler called before any user action handlers, i.e. CommandHandler, InitHandler, MessageHandler, CallbackHandler. If PrimeHandler returns an error, ErrorHandler will be called. If PrimeHandler returns a continue session state as a new session state, following handlers will be called. Otherwise session will be switched to specified state.

Also PrimeHandler has an HandlerSource arg indicates a source handler where PrimeHandler was called.

You may use PrimeHandler to do some general actions for bot handlers. E.g., check user authentication

InitHandler

This handler is called when session has not been started yet. The main goal for this handler it's a do some initial actions (eg. check auth or something like) and return a first state session will be swiched to.

ErrorHandler

This handler is called when any other handler returned an error. The main goal for this handler it's a do some common actions (eg. send user a message via Telegram) and return a new session state.

DestroyHandler

This handler is called before session will be destroyed. The main goal of this handler is a do some common actions with data collected during the session (e.g. delete some files, cleanup some records in DB, etc) to prevent leak the memory and space.

Example of usage

You can find the example of very simple bot below. Bot asks to user several simple questions and sends summary.

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	tg "github.com/nixys/nxs-go-telegram"
)

func main() {

	// Example of user context used within the bot handlers
	botCompany := "Nixys"

	// Bot description
	botDescription := tg.Description{
		Commands: []tg.Command{
			{
				Command:     "sayhello",
				Description: "Bot says you hello and begins a conversation",
				Handler:     sayHelloCmd,
			},
			{
				Command:     "destroy",
				Description: "Destroy current session",
				Handler:     destroyCmd,
			},
		},
		InitHandler: botInit,
		States: map[tg.SessionState]tg.State{
			tg.SessState("hello"): {
				StateHandler: helloState,
			},
			tg.SessState("name"): {
				StateHandler:   nameState,
				MessageHandler: nameMsg,
			},
			tg.SessState("gender"): {
				StateHandler:    genderState,
				CallbackHandler: genderCallback,
			},
			tg.SessState("age"): {
				StateHandler:   ageState,
				MessageHandler: ageMsg,
			},
			tg.SessState("info"): {
				StateHandler: infoState,
			},
			tg.SessState("bye"): {
				StateHandler: byeState,
			},
		},
	}

	// Initialize the bot
	bot, err := tg.Init(tg.Settings{
		BotSettings: tg.SettingsBot{
			BotAPI: os.Getenv("BOT_API_TOKEN"),
		},
		RedisHost: os.Getenv("REDIS_HOST"),
	}, botDescription, botCompany)
	if err != nil {
		fmt.Println("bot setup error:", err)
		return
	}

	// Runtime the bot
	runtime(bot)
}

func runtime(bot tg.Telegram) {

	fmt.Println("bot started")

	// Updates runtime
	ctxUpdates, cfUpdates := context.WithCancel(context.Background())
	chUpdates := make(chan error)

	// Queue runtime
	ctxQueue, cfQueue := context.WithCancel(context.Background())
	chQueue := make(chan error)

	// Defer call cancel functions
	defer cfUpdates()
	defer cfQueue()

	go runtimeBotUpdates(ctxUpdates, bot, chUpdates)
	go runtimeBotQueue(ctxQueue, bot, chQueue)

	for {
		select {
		case e := <-chUpdates:
			fmt.Println("got error from runtime update:", e)
			return
		case e := <-chQueue:
			fmt.Println("got error from runtime queue:", e)
			return
		}
	}
}

// runtimeBotUpdates checks updates at Telegram and put it into queue
func runtimeBotUpdates(ctx context.Context, bot tg.Telegram, ch chan error) {
	if err := bot.GetUpdates(ctx); err != nil {
		if err == tg.ErrUpdatesChanClosed {
			ch <- nil
		} else {
			ch <- err
		}
	} else {
		ch <- nil
	}
}

// runtimeBotQueue processes an updaates from queue
func runtimeBotQueue(ctx context.Context, bot tg.Telegram, ch chan error) {
	timer := time.NewTimer(time.Duration(1) * time.Second)
	for {
		select {
		case <-timer.C:
			if err := bot.Processing(); err != nil {
				ch <- err
			}
			timer.Reset(time.Duration(1) * time.Second)
		case <-ctx.Done():
			return
		}
	}
}

// botInit represents InitHandler for bot
func botInit(t *tg.Telegram, s *tg.Session) (tg.InitHandlerRes, error) {
	return tg.InitHandlerRes{
		NextState: tg.SessState("name"),
	}, nil
}

// sayHelloCmd handles a `/sayhello` command
func sayHelloCmd(t *tg.Telegram, s *tg.Session, cmd string, args string) (tg.CommandHandlerRes, error) {
	return tg.CommandHandlerRes{
		NextState: tg.SessState("hello"),
	}, nil
}

// destroyCmd handles a `/destroy` command
func destroyCmd(t *tg.Telegram, s *tg.Session, cmd string, args string) (tg.CommandHandlerRes, error) {
	return tg.CommandHandlerRes{
		NextState: tg.SessState("bye"),
	}, nil
}

// Hello

// helloState represents StateHandler for `hello` state
func helloState(t *tg.Telegram, s *tg.Session) (tg.StateHandlerRes, error) {
	c := t.UsrCtxGet().(string)
	return tg.StateHandlerRes{
		Message:   "Hello! I'm a bot created by " + c + " developers",
		NextState: tg.SessState("name"),
	}, nil
}

// Name

// nameState represents StateHandler for `name` state
func nameState(t *tg.Telegram, s *tg.Session) (tg.StateHandlerRes, error) {
	return tg.StateHandlerRes{
		Message: "Please, enter your name",
	}, nil
}

// nameMsg represents MessageHandler for `name` state
func nameMsg(t *tg.Telegram, s *tg.Session) (tg.MessageHandlerRes, error) {

	m := s.UpdateChain().MessageTextGet()
	if len(m) == 0 {
		return tg.MessageHandlerRes{}, fmt.Errorf("empty message")
	}

	if err := s.SlotSave("name", m[0]); err != nil {
		return tg.MessageHandlerRes{}, err
	}

	return tg.MessageHandlerRes{
		NextState: tg.SessState("gender"),
	}, nil
}

// Gender

// genderState represents StateHandler for `gender` state
func genderState(t *tg.Telegram, s *tg.Session) (tg.StateHandlerRes, error) {
	return tg.StateHandlerRes{
		Message: "Select your gender",
		Buttons: [][]tg.Button{
			{
				{
					Text:       "Male",
					Identifier: "male",
				},
			},
			{
				{
					Text:       "Female",
					Identifier: "female",
				},
			},
		},
		NextState: tg.SessStateBreak(),
	}, nil
}

// genderCallback represents CallbackHandler for `gender` state
func genderCallback(t *tg.Telegram, s *tg.Session, identifier string) (tg.CallbackHandlerRes, error) {
	switch identifier {
	case "male":
		if err := s.SlotSave("gender", "Male"); err != nil {
			return tg.CallbackHandlerRes{}, err
		}
	case "female":
		if err := s.SlotSave("gender", "Female"); err != nil {
			return tg.CallbackHandlerRes{}, err
		}
	}
	return tg.CallbackHandlerRes{
		NextState: tg.SessState("age"),
	}, nil
}

// Age

// ageState represents StateHandler for `age` state
func ageState(t *tg.Telegram, s *tg.Session) (tg.StateHandlerRes, error) {
	return tg.StateHandlerRes{
		Message:      "How old are you?",
		StickMessage: true,
	}, nil
}

// ageMsg represents MessageHandler for `age` state
func ageMsg(t *tg.Telegram, s *tg.Session) (tg.MessageHandlerRes, error) {

	m := s.UpdateChain().MessageTextGet()
	if len(m) == 0 {
		return tg.MessageHandlerRes{}, fmt.Errorf("empty message")
	}

	if err := s.SlotSave("age", m[0]); err != nil {
		return tg.MessageHandlerRes{}, err
	}

	return tg.MessageHandlerRes{
		NextState: tg.SessState("info"),
	}, nil
}

// Info

// infoState represents StateHandler for `info` state
func infoState(t *tg.Telegram, s *tg.Session) (tg.StateHandlerRes, error) {

	var (
		name   string
		gender string
		age    string
	)

	if _, err := s.SlotGet("name", &name); err != nil {
		return tg.StateHandlerRes{}, err
	}

	if _, err := s.SlotGet("gender", &gender); err != nil {
		return tg.StateHandlerRes{}, err
	}

	if _, err := s.SlotGet("age", &age); err != nil {
		return tg.StateHandlerRes{}, err
	}

	m := fmt.Sprintf("Info:\n"+
		"  Name: %s\n"+
		"  Gender: %s\n"+
		"  Age: %s",
		name,
		gender,
		age)

	return tg.StateHandlerRes{
		Message:   m,
		NextState: tg.SessState("bye"),
	}, nil
}

// Bye

// byeState represents StateHandler for `bye` state
func byeState(t *tg.Telegram, s *tg.Session) (tg.StateHandlerRes, error) {
	return tg.StateHandlerRes{
		Message:   "Bye!",
		NextState: tg.SessStateDestroy(),
	}, nil
}

Run:

go mod init test
go mod tidy
BOT_API_TOKEN="YOUR_BOT_API_TOKEN" REDIS_HOST="YOUR_REDIS_HOST_AND_PORT" go run main.go

Feedback

For support and feedback please contact me:

License

nxs-go-telegram is released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCallbackDataFormat contains error "wrong callback data format"
	ErrCallbackDataFormat = errors.New("wrong callback data format")

	// ErrDescriptionState contains error "session state not defined in bot description"
	ErrDescriptionStateMissing = errors.New("session state not defined in bot description")

	// ErrUpdatesChanClosed contains error "updates channel has been closed"
	ErrUpdatesChanClosed = errors.New("updates channel has been closed")

	// ErrUpdateChainZeroLen contains error "update has zero len"
	ErrUpdateChainZeroLen = errors.New("update has zero len")

	// ErrUpdateWrongType contains error "update has wrong type"
	ErrUpdateWrongType = errors.New("update has wrong type")

	// ErrSessionNotExist contains error "session does not exist"
	ErrSessionNotExist = errors.New("session does not exist")
)

Functions

This section is empty.

Types

type Button

type Button struct {

	// Button text
	Text string

	// Defines a button identifier for processing in handler
	Identifier string

	// Defines a button mode for processing in handler ("data" (default), "url", "switch")
	Mode ButtonMode
}

Button contains buttons data for state

type ButtonMode

type ButtonMode int

ButtonMode it's a type of button mode (see https://core.telegram.org/bots/api#inlinekeyboardbutton for details)

const (
	ButtonModeData ButtonMode = iota
	ButtonModeURL
	ButtonModeSwitch
)

func (ButtonMode) String

func (b ButtonMode) String() string

type CallbackHandlerRes

type CallbackHandlerRes struct {

	// NextState contains next session state
	NextState SessionState
}

CallbackHandlerRes contains data returned by the CallbackHandler

type ChatMember

type ChatMember tgbotapi.ChatMember

ChatMember it's an alias for tgbotapi.ChatMember

type Command

type Command struct {

	// Command able to execute by user (without leading
	// '/' character)
	Command string

	// Command description that users will see in Telegram
	Description string

	// Handler to processing command received from user
	Handler func(t *Telegram, s *Session, cmd string, args string) (CommandHandlerRes, error)
}

Command contains data for command

type CommandHandlerRes

type CommandHandlerRes struct {

	// NextState contains next session state
	NextState SessionState
}

CommandHandlerRes contains data returned by the CommandHandler

type Description

type Description struct {

	// Commands contains Telegram commands available for bot.
	// Each record it's a command name (without leading
	// '/' character), its description and handler
	Commands []Command

	// States contains the states description.
	// Map key it's a state name that must be set with the
	// tg.SessState() function
	States map[SessionState]State

	// InitHandler is a handler to processing Telegram updates
	// when session has not been started yet.
	// This element returns only next state.
	InitHandler func(t *Telegram, s *Session) (InitHandlerRes, error)

	// ErrorHandler is a handler called if any other handlers returned an error
	ErrorHandler func(t *Telegram, s *Session, e error) (ErrorHandlerRes, error)

	// PrimeHandler is a handler called before any user action handlers, i.e.
	// CommandHandler, InitHandler, MessageHandler, CallbackHandler.
	// If PrimeHandler returns an error, ErrorHandler will be called.
	// If PrimeHandler returns a `sessionContinue` as a new session state, following handlers
	// will be called. Otherwise session will be switched to specified state.
	PrimeHandler func(t *Telegram, s *Session, hs HandlerSource) (PrimeHandlerRes, error)

	// DestroyHandler is a handler called before session will be destroyed
	DestroyHandler func(t *Telegram, s *Session) error
}

Description describes bot

type ErrorHandlerRes

type ErrorHandlerRes struct {

	// New state to switch the session.
	// All values of NextState must exist in States map
	// within the bot description
	NextState SessionState
}

ErrorHandlerRes contains data returned by the ErrorHandler

type File

type File struct {
	FileSize int
	FileName string
	// contains filtered or unexported fields
}

File contains file descrition received from Telegram

type FileSend

type FileSend struct {
	FileType  FileType
	FilePath  string
	Caption   string
	ParseMode ParseMode
	Buttons   [][]Button
}

FileSend contains options for sending file to Telegram

type FileSendStream

type FileSendStream struct {
	FileType  FileType
	FileName  string
	FileSize  int64
	Caption   string
	ParseMode ParseMode
	Buttons   [][]Button
}

FileSendStream contains options for sending file to Telegram as stream

type FileType

type FileType int

FileType specifies uploading file type

const (
	FileTypeDocument FileType = iota
	FileTypePhoto
	FileTypeVoice
	FileTypeVideo
	FileTypeAudio
	FileTypeSticker
)

func (FileType) String

func (f FileType) String() string

type HandlerSource

type HandlerSource string

HandlerSource is a type of source handler where PrimeHandler was called

const (
	HandlerSourceInit     HandlerSource = "init"
	HandlerSourceCommand  HandlerSource = "command"
	HandlerSourceMessage  HandlerSource = "message"
	HandlerSourceCallback HandlerSource = "callback"
)

func (HandlerSource) String

func (hs HandlerSource) String() string

type InitHandlerRes

type InitHandlerRes struct {

	// New state to switch the session.
	// All values of NextState must exist in States map
	// within the bot description
	NextState SessionState
}

InitHandlerRes contains data returned by the InitHandler

type MessageHandlerRes

type MessageHandlerRes struct {

	// NextState contains next session state
	NextState SessionState
}

MessageHandlerRes contains data returned by the MessageHandler

type MessageSent

type MessageSent tgbotapi.Message

MessageSent it's an alias for tgbotapi.Message

type ParseMode added in v1.1.0

type ParseMode int
const (
	ParseModeMarkdown ParseMode = iota
	ParseModeMarkdownV2
	ParseModeHTML
)

func (ParseMode) String added in v1.1.0

func (p ParseMode) String() string

type PrimeHandlerRes

type PrimeHandlerRes struct {

	// New state to switch the session.
	// All values of NextState must exist in States map
	// within the bot description.
	NextState SessionState
}

PrimeHandlerRes contains data returned by the PrimeHandler

type SendMessageData

type SendMessageData struct {

	// Message defines a message text will sent to user
	Message string

	// ParseMode defines a Telegram message Parse mode
	ParseMode ParseMode

	// DisableWebPagePreview defines whether or not
	// disabling web page preview in messages
	DisableWebPagePreview bool

	// Button defines buttons for message
	Buttons [][]Button

	// `ButtonState` set a state from bot description
	// with callback handler for spcified buttons
	ButtonState SessionState
}

SendMessageData contains an options for message

type Session

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

session it is a session context structure

func (*Session) ChatIDGet

func (s *Session) ChatIDGet() int64

ChatIDGet gets current session chat ID

func (*Session) SlotDel

func (s *Session) SlotDel(slot string) error

SlotDel deletes spcified slot

func (*Session) SlotGet

func (s *Session) SlotGet(slot string, data interface{}) (bool, error)

SlotGet gets data from specified slot

func (*Session) SlotSave

func (s *Session) SlotSave(slot string, data interface{}) error

SlotSave saves data into specified slot

func (*Session) StateGet

func (s *Session) StateGet() (SessionState, bool, error)

stateGet gets current session state

func (*Session) UpdateChain

func (s *Session) UpdateChain() *UpdateChain

UpdateChain gets update chain from session

func (*Session) UserFirstNameGet

func (s *Session) UserFirstNameGet() string

UserFirstNameGet gets current session user first name

func (*Session) UserIDGet

func (s *Session) UserIDGet() int64

UserIDGet gets current session user ID

func (*Session) UserLastNameGet

func (s *Session) UserLastNameGet() string

UserLastNameGet gets current session user last name

func (*Session) UserNameGet

func (s *Session) UserNameGet() string

UserNameGet gets current session user name

type SessionState

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

func SessState

func SessState(stateName string) SessionState

SessState creates a specified session state

func SessStateBreak

func SessStateBreak() SessionState

SessStateBreak creates a `break` session state

func SessStateContinue

func SessStateContinue() SessionState

SessStateBreak creates a `continue` session state

func SessStateDestroy

func SessStateDestroy() SessionState

SessStateBreak creates a `destroy` session state

func (SessionState) String

func (s SessionState) String() string

type Settings

type Settings struct {
	BotSettings     SettingsBot
	RedisHost       string
	UpdateQueueWait time.Duration
}

Settings contains data to setting up bot

type SettingsBot

type SettingsBot struct {
	BotAPI  string
	Webhook *SettingsBotWebhook
	Proxy   *SettingsBotProxy
}

SettingsBot contains settings for Telegram bot

type SettingsBotProxy

type SettingsBotProxy struct {
	Type     string
	Host     string
	Login    string
	Password string
}

SettingsBotProxy contains proxy settings for Telegram bot

type SettingsBotWebhook

type SettingsBotWebhook struct {
	URL      string
	BotToken string
	CertFile string
	WithCert bool
}

SettingsBotWebhook contains settings to set Telegram webhook

type State

type State struct {

	// Handler to processing new bot state.
	StateHandler func(t *Telegram, s *Session) (StateHandlerRes, error)

	// Handler to processing messages received from user
	MessageHandler func(t *Telegram, s *Session) (MessageHandlerRes, error)

	// Handler to processing callbacks received from user for specific state of session
	CallbackHandler func(t *Telegram, s *Session, identifier string) (CallbackHandlerRes, error)

	// Handler to processing sent message to telegram.
	// E.g. useful for get sent messages ID
	SentHandler func(t *Telegram, s *Session, messages []MessageSent) error
}

State contains session state description

type StateHandlerRes

type StateHandlerRes struct {

	// Message contains message text to be sent to user.
	// Message can not be zero length
	Message string

	// ParseMode defines a Telegram message Parse mode
	ParseMode ParseMode

	// DisableWebPagePreview defines whether or not
	// disabling web page preview in messages
	DisableWebPagePreview bool

	// Buttons contains buttons for message to be sent to user.
	// If Buttons has zero length message will not contains buttons
	Buttons [][]Button

	// NextState defines next state for current session.
	// NextState will be ignored if MessageHandler defined for state
	NextState SessionState

	// Whether or not stick message. If true appropriate message will
	// be updated when a new state initiate by the `update` of callback type
	StickMessage bool
}

StateHandlerRes contains data returned by the StateHandler

type Telegram

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

Telegram it is a module context structure

func Init

func Init(s Settings, description Description, usrCtx interface{}) (Telegram, error)

Init initializes Telegram bot

func (*Telegram) ChatMemberGet

func (t *Telegram) ChatMemberGet(chatID, userID int64) (ChatMember, error)

func (*Telegram) DownloadFile

func (t *Telegram) DownloadFile(file File, dstPath string) error

DownloadFile downloads file from Telegram to specified path

func (*Telegram) DownloadFileStream

func (t *Telegram) DownloadFileStream(file File) (io.ReadCloser, error)

DownloadFileStream returns io.ReadCloser to download specified file

func (*Telegram) GetUpdates

func (t *Telegram) GetUpdates(ctx context.Context) error

GetUpdates creates to Telegram API and processes a receiving updates

func (*Telegram) Processing

func (t *Telegram) Processing() error

Processing processes available updates from queue

func (*Telegram) SelfIDGet

func (t *Telegram) SelfIDGet() int64

func (*Telegram) SendMessage

func (t *Telegram) SendMessage(chatID int64, messageID int, msgData SendMessageData) ([]MessageSent, error)

sendMessage sends specified message to client Messages can be of two types: either new message, or edit existing message (if messageID is set).

func (*Telegram) UpdateAbsorb

func (t *Telegram) UpdateAbsorb(update Update) error

UpdateAbsorb absorbs specified `update` and put it into queue

func (*Telegram) UploadFile

func (t *Telegram) UploadFile(chatID int64, file FileSend) (MessageSent, error)

UploadFile uploads file as to Telegram

func (*Telegram) UploadFileStream

func (t *Telegram) UploadFileStream(chatID int64, file FileSendStream, r io.Reader) (MessageSent, error)

UploadFileStream uploads file to Telegram by specified reader

func (*Telegram) UsrCtxGet

func (t *Telegram) UsrCtxGet() interface{}

UsrCtxGet gets user context

type Update

type Update tgbotapi.Update

Update is an update response, from Telegram GetUpdates.

type UpdateChain

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

UpdateChain contains chain of updates

func (*UpdateChain) CallbackQueryIDGet

func (uc *UpdateChain) CallbackQueryIDGet() string

CallbackQueryIDGet gets callback ID from first update element from chain. Chain must have callback type

func (*UpdateChain) FilesGet

func (uc *UpdateChain) FilesGet(t Telegram) ([]File, error)

FilesGet gets files from update chain. At the time only Photo, Document and Voice types are supported

func (*UpdateChain) Get

func (uc *UpdateChain) Get() []Update

Get gets all updates from chain

func (*UpdateChain) MessageTextGet

func (uc *UpdateChain) MessageTextGet() []string

MessageTextGet gets messages text or captions for every update from chain. Chain must have message type

func (*UpdateChain) MessagesIDGet

func (uc *UpdateChain) MessagesIDGet() int

MessagesIDGet gets update id from first update element from chain

func (*UpdateChain) MessagesIDsGet

func (uc *UpdateChain) MessagesIDsGet() []int

MessagesIDsGet gets update ids from updates chain

func (*UpdateChain) TypeGet

func (uc *UpdateChain) TypeGet() UpdateType

TypeGet gets chain type

type UpdateType

type UpdateType int

UpdateType is a type of update chain

const (

	// UpdateTypeNone - type `none` for update chain.
	// No type has not been set yet or chain has been cleaned up.
	UpdateTypeNone UpdateType = iota

	// UpdateTypeUnknown - unknown update type
	UpdateTypeUnknown

	// UpdateTypeMessage - type message
	UpdateTypeMessage

	// UpdateTypeCallback - type callback
	UpdateTypeCallback
)

func (UpdateType) String

func (u UpdateType) String() string

Jump to

Keyboard shortcuts

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