tg

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2022 License: ISC Imports: 14 Imported by: 1

README

Bot API for Telegram bots

Impromptu docs at: https://godoc.org/git.fromouter.space/Hamcha/tg

Should work if you can put the time to figure out how it works (check client_test.go or better yet, clessy)

(Yes this needs proper docs and everything but I'm kinda busy doing other stuff)

Documentation

Index

Examples

Constants

View Source
const APIEndpoint = "https://api.telegram.org/"

APIEndpoint is Telegram's current Bot API base url endpoint

Variables

View Source
var (
	// ErrMalformed represents an error that was encountered while processing the request (json encode/decode error etc)
	ErrMalformed = errors.New("Error while handling request")
)

Functions

func CreateBrokerClient

func CreateBrokerClient(brokerAddr string, updateFn UpdateHandler) error

CreateBrokerClient creates a connection to a broker and sends all webhook updates to a given function. This is the intended way to create clients, please refer to examples for how to make a simple client.

Example

This example creates a basic client that connects to a broker and checks for message containing greetings. If it finds a greeting message it will greet back the user (using the reply_to parameter)

package main

import (
	"git.fromouter.space/hamcha/tg"
)

func main() {
	tg.CreateBrokerClient("localhost:7314", func(broker *tg.Broker, update tg.APIUpdate) {
		// Check if it's a text message
		if update.Message != nil && update.Message.Text != nil {
			// Check that it's a greeting
			if *(update.Message.Text) == "hello" || *(update.Message.Text) == "hi" {
				// Reply with a greeting!
				broker.SendTextMessage(update.Message.Chat, "Hello!", &tg.MessageOptions{
					ReplyID: &update.Message.MessageID,
				})
			}
		}
	})
}
Output:

func RunBrokerClient

func RunBrokerClient(broker *Broker, updateFn UpdateHandler) error

RunBrokerClient is a slimmer version of CreateBrokerClient for who wants to keep its own broker connection

Types

type APIAudio

type APIAudio 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"`
}

APIAudio represents the "Audio" JSON structure

type APICallbackQuery

type APICallbackQuery struct {
	ID       string      `json:"id"`
	User     APIUser     `json:"from"`
	Message  *APIMessage `json:"message,omitempty"`
	InlineID *string     `json:"inline_message_id,omitempty"`
	ChatID   string      `json:"chat_instance"`
	Data     *string     `json:"data,omitempty"`
}

APICallbackQuery is a callback query triggered by an inline button

type APIChat

type APIChat struct {
	ChatID    int64    `json:"id"`
	Type      ChatType `json:"type"`
	Title     *string  `json:"title,omitempty"`
	Username  *string  `json:"username,omitempty"`
	FirstName *string  `json:"first_name,omitempty"`
	LastName  *string  `json:"last_name,omitempty"`
}

APIChat represents the "Chat" JSON structure

type APIContact

type APIContact struct {
	PhoneNumber string  `json:"phone_number"`
	FirstName   string  `json:"first_name"`
	LastName    *string `json:"last_name,omitempty"`
	UserID      *int64  `json:"user_id,omitempty"`
}

APIContact represents the "Contact" JSON structure

type APIDocument

type APIDocument struct {
	FileID    string        `json:"file_id"`
	Thumbnail *APIPhotoSize `json:"thumb,omitempty"`
	Filename  string        `json:"file_name"`
	MimeType  *string       `json:"mime_type,omitempty"`
	FileSize  *int          `json:"file_size,omitempty"`
}

APIDocument represents the "Document" JSON structure

type APIFile

type APIFile struct {
	FileID string  `json:"file_id"`
	Size   *int    `json:"file_size,omitempty"`
	Path   *string `json:"file_path,omitempty"`
}

APIFile represents the "File" JSON structure

type APIForceReply

type APIForceReply struct {
	ForceReply bool `json:"force_reply"`
	Selective  bool `json:"selective,omitempty"`
}

APIForceReply forces the reply textbox to open after receiving a message

type APIInlineKeyboardButton

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

APIInlineKeyboardButton is an inline message button

type APIInlineKeyboardMarkup

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

type APIInlineQuery

type APIInlineQuery struct {
	QueryID  string       `json:"id"`
	From     APIUser      `json:"from"`
	Location *APILocation `json:"location,omitempty"`
	Query    string       `json:"query"`
	Offset   string       `json:"offset"`
}

APIInlineQuery represents an inline query from telegram

type APIInlineQueryResultPhoto

type APIInlineQueryResultPhoto struct {
	Type        string      `json:"type"`
	ResultID    string      `json:"id"`
	PhotoURL    string      `json:"photo_url"`
	ThumbURL    string      `json:"thumb_url"`
	Width       int         `json:"photo_width,omitempty"`
	Height      int         `json:"photo_height,omitempty"`
	Title       string      `json:"title,omitempty"`
	Description string      `json:"description,omitempty"`
	Caption     string      `json:"caption,omitempty"`
	ParseMode   string      `json:"parse_mode,omitempty"`
	ReplyMarkup interface{} `json:"reply_markup,omitempty"`
}

APIInlineQueryResultPhoto is an image result for an inline query

type APIInputMediaPhoto

type APIInputMediaPhoto struct {
	Type      string `json:"type"`
	Media     string `json:"media"`
	Caption   string `json:"caption,omitempty"`
	ParseMode string `json:"parse_mode,omitempty"`
}

APIInputMediaPhoto is a media photo element (already on telegram servers or via HTTP URL) for albums and other cached pictures

type APIKeyboardButton

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

APIKeyboardButton is a custom keyboard button

type APILocation

type APILocation struct {
	Longitude float64 `json:"longitude"`
	Latitude  float64 `json:"latitude"`
}

APILocation represents the "Location" JSON structure

type APIMessage

type APIMessage struct {
	MessageID         int64          `json:"message_id"`
	User              APIUser        `json:"from"`
	Time              int64          `json:"date"`
	Chat              *APIChat       `json:"chat"`
	FwdUser           *APIUser       `json:"forward_from,omitempty"`
	FwdTime           *int           `json:"forward_date,omitempty"`
	ReplyTo           *APIMessage    `json:"reply_to_message,omitempty"`
	Text              *string        `json:"text,omitempty"`
	Audio             *APIAudio      `json:"audio,omitempty"`
	Document          *APIDocument   `json:"document,omitempty"`
	Photo             []APIPhotoSize `json:"photo,omitempty"`
	Sticker           *APISticker    `json:"sticker,omitempty"`
	Video             *APIVideo      `json:"video,omitempty"`
	Voice             *APIVoice      `json:"voice,omitempty"`
	Caption           *string        `json:"caption,omitempty"`
	Contact           *APIContact    `json:"contact,omitempty"`
	Location          *APILocation   `json:"location,omitempty"`
	NewUser           *APIUser       `json:"new_chat_partecipant,omitempty"`
	LeftUser          *APIUser       `json:"left_chat_partecipant,omitempty"`
	PhotoDeleted      *bool          `json:"delete_chat_photo,omitempty"`
	GroupCreated      *bool          `json:"group_chat_created,omitempty"`
	SupergroupCreated *bool          `json:"supergroup_chat_created,omitempty"`
	ChannelCreated    *bool          `json:"channel_chat_created,omitempty"`
	GroupToSuper      *int64         `json:"migrate_to_chat_id,omitempty"`
	GroupFromSuper    *int64         `json:"migrate_from_chat_id,omitempty"`
}

APIMessage represents the "Message" JSON structure

type APIPhotoSize

type APIPhotoSize struct {
	FileID   string `json:"file_id"`
	Width    int    `json:"width"`
	Height   int    `json:"height"`
	FileSize *int   `json:"file_size,omitempty"`
}

APIPhotoSize represents the "PhotoSize" JSON structure

type APIReplyKeyboardMarkup

type APIReplyKeyboardMarkup struct {
	Keyboard  [][]APIKeyboardButton `json:"keyboard"` // Grid of buttons
	Resize    bool                  `json:"resize_keyboard,omitempty"`
	OneTime   bool                  `json:"one_time_keyboard,omitempty"`
	Selective bool                  `json:"selective,omitempty"`
}

type APIReplyKeyboardRemove

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

type APIResponse

type APIResponse struct {
	Ok          bool    `json:"ok"`
	ErrCode     *int    `json:"error_code,omitempty"`
	Description *string `json:"description,omitempty"`
}

APIResponse represents a response from the Telegram API

type APISticker

type APISticker struct {
	FileID    string        `json:"file_id"`
	Width     int           `json:"width"`
	Height    int           `json:"height"`
	Thumbnail *APIPhotoSize `json:"thumb,omitempty"`
	FileSize  *int          `json:"file_size,omitempty"`
}

APISticker represents the "Sticker" JSON structure

type APIUpdate

type APIUpdate struct {
	UpdateID int64             `json:"update_id"`
	Message  *APIMessage       `json:"message"`
	Inline   *APIInlineQuery   `json:"inline_query,omitempty"`
	Callback *APICallbackQuery `json:"callback_query,omitempty"`
}

APIUpdate represents the "Update" JSON structure

type APIUser

type APIUser struct {
	UserID                  int64  `json:"id"`
	FirstName               string `json:"first_name"`
	LastName                string `json:"last_name,omitempty"`
	Username                string `json:"username,omitempty"`
	IsBot                   bool   `json:"is_bot"`
	LanguageCode            string `json:"language_code,omitempty"`
	CanJoinGroups           bool   `json:"can_join_groups,omitempty"`
	CanReadAllGroupMessages bool   `json:"can_read_all_group_messages,omitempty"`
	SupportsInlineQueries   bool   `json:"supports_inline_queries,omitempty"`
}

APIUser represents the "User" JSON structure

type APIVideo

type APIVideo struct {
	FileID    string        `json:"file_id"`
	Width     int           `json:"width"`
	Height    int           `json:"height"`
	Duration  int           `json:"duration"`
	Thumbnail *APIPhotoSize `json:"thumb,omitempty"`
	MimeType  *string       `json:"mime_type,omitempty"`
	FileSize  *int          `json:"file_size,omitempty"`
}

APIVideo represents the "Video" JSON structure

type APIVoice

type APIVoice struct {
	FileID   string  `json:"file_id"`
	Duration int     `json:"duration"`
	MimeType *string `json:"mime_type,omitempty"`
	FileSize *int    `json:"file_size,omitempty"`
}

APIVoice represents the "Voice" JSON structure

type Broker

type Broker struct {
	Socket    net.Conn
	Callbacks []BrokerCallback
	// contains filtered or unexported fields
}

Broker is a broker connection handler with callback management functions

func ConnectToBroker

func ConnectToBroker(brokerAddr string) (*Broker, error)

ConnectToBroker creates a Broker connection

func (*Broker) AnswerInlineQuery

func (b *Broker) AnswerInlineQuery(response InlineQueryResponse)

AnswerInlineQuery sends the results of an inline query

func (*Broker) Close

func (b *Broker) Close()

Close closes a broker connection

func (*Broker) ForwardMessage

func (b *Broker) ForwardMessage(chat *APIChat, message APIMessage)

ForwardMessage forwards a message between chats.

func (*Broker) GetFile

func (b *Broker) GetFile(fileID string, fn BrokerCallback) int

GetFile sends a file retrieval request to the Broker. This function is asynchronous as data will be delivered to the given callback.

func (*Broker) RegisterCallback

func (b *Broker) RegisterCallback(fn BrokerCallback) int

RegisterCallback assigns a callback ID to the given callback and puts it on the callback list. This function should never be called by clients.

func (*Broker) RemoveCallback

func (b *Broker) RemoveCallback(id int)

RemoveCallback removes a callback from the callback list by ID. This function should never be called by clients.

func (*Broker) SendChatAction

func (b *Broker) SendChatAction(chat *APIChat, action ChatAction)

SendChatAction sets a chat action for 5 seconds or less (canceled at first message sent)

func (*Broker) SendPhoto

func (b *Broker) SendPhoto(chat *APIChat, data []byte, filename string, caption string, extra *MessageOptions)

SendPhoto sends a photo with an optional caption to a chat. A reply_to message ID can be specified as optional parameter.

func (*Broker) SendTextMessage

func (b *Broker) SendTextMessage(chat *APIChat, text string, extra *MessageOptions)

SendTextMessage sends a HTML-styles text message to a chat. A reply_to message ID can be specified as optional parameter.

func (*Broker) SpliceCallback

func (b *Broker) SpliceCallback(id int) BrokerCallback

SpliceCallback retrieves a callback by ID and removes it from the list. This function should never be called by clients.

type BrokerCallback

type BrokerCallback func(broker *Broker, update BrokerUpdate)

BrokerCallback is a callback for broker responses to client requests

type BrokerUpdate

type BrokerUpdate struct {
	Type     BrokerUpdateType
	Callback *int       `json:",omitempty"`
	Error    *string    `json:",omitempty"`
	Data     *APIUpdate `json:",omitempty"`
	Bytes    *string    `json:",omitempty"`
}

BrokerUpdate is what is sent by the broker as update

type BrokerUpdateType

type BrokerUpdateType string

BrokerUpdateType distinguishes update types coming from the broker

const (
	// BMessage is a message update (mostly webhook updates)
	BMessage BrokerUpdateType = "message"

	// BFile is a file retrieval response update
	BFile BrokerUpdateType = "file"

	// BError is an error the broker occurred while fulfilling a request
	BError BrokerUpdateType = "error"
)

type ChatAction

type ChatAction string

ChatAction is the action name for CmdSendChatAction requests

const (
	ActionTyping            ChatAction = "typing"
	ActionUploadingPhoto    ChatAction = "upload_photo"
	ActionRecordingVideo    ChatAction = "record_video"
	ActionUploadingVideo    ChatAction = "upload_video"
	ActionRecordingAudio    ChatAction = "record_audio"
	ActionUploadingAudio    ChatAction = "upload_audio"
	ActionUploadingDocument ChatAction = "upload_document"
	ActionFindingLocation   ChatAction = "find_location"
)

Telegram chat actions

type ChatType

type ChatType string

ChatType defines the type of chat

const (
	// ChatTypePrivate is a private chat (between user and bot)
	ChatTypePrivate ChatType = "private"

	// ChatTypeGroup is a group chat (<100 members)
	ChatTypeGroup ChatType = "group"

	// ChatTypeSupergroup is a supergroup chat (>=100 members)
	ChatTypeSupergroup ChatType = "supergroup"

	// ChatTypeChannel is a channel (Read-only)
	ChatTypeChannel ChatType = "channel"
)

type ClientAlbumData

type ClientAlbumData struct {
	ChatID  int64
	Media   interface{}
	Silent  bool
	ReplyID *int64 `json:",omitempty"`
}

ClientAlbumData is the required data for a CmdSendAlbum request

type ClientCallbackQueryData

type ClientCallbackQueryData struct {
	QueryID   string
	Text      string
	ShowAlert bool
	URL       string
	CacheTime int64
}

ClientCallbackQueryData is the required data for a CmdAnswerCallback request

type ClientChatActionData

type ClientChatActionData struct {
	ChatID int64
	Action ChatAction
}

ClientChatActionData is the required data for a CmdSendChatAction request

type ClientCommand

type ClientCommand struct {
	Type               ClientCommandType
	TextMessageData    *ClientTextMessageData    `json:",omitempty"`
	PhotoData          *ClientPhotoDataNet       `json:",omitempty"`
	ForwardMessageData *ClientForwardMessageData `json:",omitempty"`
	ChatActionData     *ClientChatActionData     `json:",omitempty"`
	InlineQueryResults *InlineQueryResponse      `json:",omitempty"`
	FileRequestData    *FileRequestData          `json:",omitempty"`
	Callback           *int                      `json:",omitempty"`
}

ClientCommand is a request sent by clients to the broker

type ClientCommandType

type ClientCommandType string

ClientCommandType distinguishes requests sent by clients to the broker

const (
	// CmdSendTextMessage requests the broker to send a text message to a chat
	CmdSendTextMessage ClientCommandType = "sendText"

	// CmdSendPhoto requests the broker to send a photo to a chat
	CmdSendPhoto ClientCommandType = "sendPhoto"

	// CmdForwardMessage requests the broker to forward a message between chats
	CmdForwardMessage ClientCommandType = "forwardMessage"

	// CmdGetFile requests the broker to get a file from Telegram
	CmdGetFile ClientCommandType = "getFile"

	// CmdSendChatAction requests the broker to set a chat action (typing, etc.)
	CmdSendChatAction ClientCommandType = "sendChatAction"

	// CmdAnswerInlineQuery requests the broker sends results of an inline query
	CmdAnswerInlineQuery ClientCommandType = "answerInlineQuery"

	// CmdSendAlbum requests the broker sends an album of photos or videos
	CmdSendAlbum ClientCommandType = "sendAlbum"

	// CmdAnswerCallback requests the broker to reply to a incoming callback query
	CmdAnswerCallback ClientCommandType = "answerCallback"

	// CmdEditCaption requests to broker to replace the caption of a media (photo, doc, etc) message
	CmdEditCaption ClientCommandType = "editCaption"

	// CmdEditMedia requests to broker to replace the media contents of a message
	CmdEditMedia ClientCommandType = "editMedia"
)

type ClientEditCaptionData

type ClientEditCaptionData struct {
	ChatID      int64
	MessageID   int64
	InlineID    string
	Caption     string
	ReplyMarkup interface{} `json:",omitempty"`
}

ClientEditCaptionData is the required data for a CmdEditCaption request

type ClientEditMediaData

type ClientEditMediaData struct {
	ChatID      int64
	MessageID   int64
	InlineID    string
	Media       interface{}
	ReplyMarkup interface{} `json:",omitempty"`
}

ClientEditMediaData is the required data for a CmdEditMedia request

type ClientEditTextData

type ClientEditTextData struct {
	ChatID      int64
	MessageID   int64
	InlineID    string
	Text        string
	ReplyMarkup interface{} `json:",omitempty"`
}

ClientEditTextData is the required data for a CmdEditText request

type ClientForwardMessageData

type ClientForwardMessageData struct {
	ChatID     int64
	FromChatID int64
	MessageID  int64
}

ClientForwardMessageData is the required data for a CmdForwardMessage request

type ClientPhotoData

type ClientPhotoData struct {
	ChatID   int64
	Bytes    []byte
	Filename string
	Caption  string `json:",omitempty"`
	ReplyID  *int64 `json:",omitempty"`
}

ClientPhotoData is the required data for a CmdSendPhoto request

type ClientPhotoDataNet added in v0.2.1

type ClientPhotoDataNet struct {
	ChatID   int64
	Bytes    string
	Filename string
	Caption  string `json:",omitempty"`
	ReplyID  *int64 `json:",omitempty"`
}

ClientPhotoDataNet is the required data for a CmdSendPhoto request over the wire

type ClientTextMessageData

type ClientTextMessageData struct {
	ChatID      int64
	Text        string
	ReplyID     *int64      `json:",omitempty"`
	ReplyMarkup interface{} `json:",omitempty"`
}

ClientTextMessageData is the required data for a CmdSendTextMessage request

type FileRequestData

type FileRequestData struct {
	FileID string
}

FileRequestData is the required data for a CmdGetFile request

type InlineQueryResponse

type InlineQueryResponse struct {
	QueryID    string
	Results    interface{}
	CacheTime  *int   `json:",omitempty"`
	IsPersonal bool   `json:",omitempty"`
	NextOffset string `json:",omitempty"`
	PMText     string `json:",omitempty"`
	PMParam    string `json:",omitempty"`
}

InlineQueryResponse is the response to an inline query

type MessageOptions

type MessageOptions struct {
	ReplyID     *int64
	ReplyMarkup interface{}
}

type Telegram

type Telegram struct {
	Token string
}

Telegram is the API client for the Telegram Bot API

func MakeAPIClient

func MakeAPIClient(token string) *Telegram

MakeAPIClient creates a Telegram instance from a Bot API token

func (Telegram) AnswerCallback

func (t Telegram) AnswerCallback(data ClientCallbackQueryData)

AnswerCallback stops the progress bar after a callback query is initiated

func (Telegram) AnswerInlineQuery

func (t Telegram) AnswerInlineQuery(data InlineQueryResponse) error

AnswerInlineQuery replies to an inline query

func (Telegram) EditCaption

func (t Telegram) EditCaption(data ClientEditCaptionData) error

EditCaption modifies the caption of a photo/document/etc message

func (Telegram) EditMedia

func (t Telegram) EditMedia(data ClientEditMediaData) error

EditMedia modifies the media content (like photo) of a message

func (Telegram) EditText

func (t Telegram) EditText(data ClientEditTextData) error

EditText modifies a text message

func (Telegram) ForwardMessage

func (t Telegram) ForwardMessage(data ClientForwardMessageData) (APIMessage, error)

ForwardMessage forwards an existing message to a chat

func (Telegram) GetFile

func (t Telegram) GetFile(data FileRequestData) ([]byte, error)

GetFile sends a "getFile" API call to Telegram's servers and fetches the file specified afterward. The file will be then send back to the client that requested it with the specified callback id.

func (Telegram) GetFileNet added in v0.2.0

func (t Telegram) GetFileNet(data FileRequestData, client net.Conn, callback int)

func (Telegram) GetMe

func (t Telegram) GetMe() (APIUser, error)

func (Telegram) HandleWebhook

func (t Telegram) HandleWebhook(bind string, webhook string, handler WebhookHandler) error

HandleWebhook is a webhook HTTP handler for standalone bots

func (Telegram) SendAlbum

func (t Telegram) SendAlbum(data ClientAlbumData) ([]APIMessage, error)

SendAlbum sends an album of photos or videos

func (Telegram) SendChatAction

func (t Telegram) SendChatAction(data ClientChatActionData)

SendChatAction sends a 5 second long action (X is writing, sending a photo ecc.)

func (Telegram) SendPhoto

func (t Telegram) SendPhoto(data ClientPhotoData) (APIMessage, error)

SendPhoto sends a picture to a chat as a photo

func (Telegram) SendPhotoNet added in v0.2.1

func (t Telegram) SendPhotoNet(data ClientPhotoDataNet) (APIMessage, error)

SendPhotoNet decodes a network SendPhoto request and executes it

func (Telegram) SendTextMessage

func (t Telegram) SendTextMessage(data ClientTextMessageData) (APIMessage, error)

SendTextMessage sends an HTML-styled text message to a specified chat

func (Telegram) SetWebhook

func (t Telegram) SetWebhook(webhook string)

SetWebhook sets the webhook address so that Telegram knows where to send updates

type UpdateHandler

type UpdateHandler func(broker *Broker, data APIUpdate)

UpdateHandler is an update handler for webhook updates

type WebhookHandler

type WebhookHandler func(APIUpdate)

WebhookHandler is a function that handles updates

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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