ubot

package module
v0.0.0-...-ba71d09 Latest Latest
Warning

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

Go to latest
Published: May 24, 2021 License: MIT Imports: 16 Imported by: 0

README

uBot

uBot is a minimalistic Telegram BOT API library for Golang that aims to be complete, idiomatic and extensible.

Overview

uBot is a bot framework for Telegram Bot API that I'm writing to support my own bot implementations. Instead of providing a full API mapping, uBot relies on axon for JSON handling, which in turn is a minimal wrapper around Golang JSON marshal/unmarshal functionalities.

It features a simple but extensible mechanism for message routing and filtering that allows the developers to write, reuse and compose their own matchers and handlers.

The methods of Telegram bot API are mappped one on one onto the Bot object.

The messages that are sent to the server are to be composed as specified on Telegram's BOT API reference. There's no need to memorize an additional layer nor coding conventions (in turn there's no guarantee that the sent messages are well formed, beware of HTTP 400 errors).

Messages are plain axon objects:

sentMsg, err := bot.SendMessage(axon.O{
	"chat_id": 123456789,
	"text": "Hello uBot!",
})

same are responses. You can access JSON properties with the dotted notation:

sentMsg.GetInteger()

Strengths or uBot are:

  • Minimal footprint
  • Easily extensible
  • It doesn't create any additional abstraction layer over Telegram bot API.
  • Intuitive JSON response handling
  • Pluggable update source for receiving updates (in progress)
  • Context and WaitGroup aware bots
  • Custom method invocations. Invoke latest API methods even if the current uBot version isn't up to date.

weaknesses are:

  • Not completely type safe
  • Not as proven as other libraries
  • API still not fully tested (help needed)

This package has been written in the process of learning Golang, critics and contributions are welcome.

Get started

A basic bot that can receive a message and send a reply, getting updates via long poll:


func main() (result *ubot.Bot, err error) {  
	bot := ubot.NewBot(ubot.Configuration{APIToken: "<yourAPIToken>", LongPoll: true})

	bot.AddMessageHandler(ubot.Any,
	), func(ctx context.Context, bot *ubot.Bot, message ubot.O) (done bool, err error) {
        var chatID int64
		if chatID, err = message.GetInteger("from.id"); err == nil {
		    _, err = bot.SendMessage(O{"chat_id": chatID, "text": "I got your message"})
        }
		return
	})

    var wg sync.WaitGroup
    go bot.Forever(context.BackgroundContext(), &wg)
    wg.Add(1)

    wg.Wait()
}

Matcher and Handler

An Matcher is a func that is executed to check wheter an update is to be handled:

type Matcher func(*Bot, O) bool

An Handler is a func that actually handles the incoming payload:

type Handler func(context.Context, *Bot, O) (bool, error)

Matcher(s) can be reused and composed, uBot provides quite a few boolean operators that help to compose simpler matchers.

Caveats

Methods mapping is still not complete.

License

uBot is distributed under MIT.

Documentation

Overview

Package ubot provides types and

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Always

func Always(bot *Bot, update axon.O) (result bool)

func GetUpdatesSource

func GetUpdatesSource(bot *Bot, ctx context.Context, updatesChan chan axon.O)

GetUpdatesSource is a ServerSource tha get updates vi long polling See https://core.telegram.org/bots/api#getupdates

func MessageHasCommand

func MessageHasCommand(entity string) func(bot *Bot, message axon.O) (result bool)

MessageHasCommand matches if update has axon.A certain message entity

func MessageHasEntities

func MessageHasEntities(bot *Bot, message axon.O) (result bool)

MatchMessageEntities matches if update has message entities

func MessageHasPhoto

func MessageHasPhoto(bot *Bot, message axon.O) (result bool)

MessageHasPhoto matches if updates has axon.A photo

func MessageInGroup

func MessageInGroup(bot *Bot, message axon.O) (result bool)

MessageInGroup matches if a message is from a group

func MessageIsPrivate

func MessageIsPrivate(bot *Bot, message axon.O) (result bool)

MessageIsPrivate matchs is message chat type is private

func ServerSource

func ServerSource(bot *Bot, ctx context.Context, updatesChan chan axon.O)

ServerSource is ServerSource that receives updates by exposing an http endpoint. The endpoint is exposed at http://hostname:<port>/bot<apiToken>.

Types

type Bot

type Bot struct {
	Configuration Configuration

	BotUser User
	// contains filtered or unexported fields
}

Bot is the main type of ubot. It implements a bot API frontend.

func NewBot

func NewBot(configuration *Configuration) (result *Bot)

NewBot creates a new Bot for the given configuration

func (*Bot) AddCallbackQueryHandler

func (b *Bot) AddCallbackQueryHandler(matcher Matcher, handler Handler)

AddCallbackQueryHandler adds an handler for callback_query updates.

func (*Bot) AddChannelPostHandler

func (b *Bot) AddChannelPostHandler(matcher Matcher, handler Handler)

AddChannelPostHandler adds an handler for channel_post updates.

func (*Bot) AddChatMemberHandler

func (b *Bot) AddChatMemberHandler(matcher Matcher, handler Handler)

AddChatMemberHandler adds an handler for chat_member updates.

func (*Bot) AddChosenInlineResultHandler

func (b *Bot) AddChosenInlineResultHandler(matcher Matcher, handler Handler)

AddChosenInlineResultHandler adds an handler for inline_query updates.

func (*Bot) AddEditedChannelPostHandler

func (b *Bot) AddEditedChannelPostHandler(matcher Matcher, handler Handler)

AddEditedChannelPostHandler adds an handler for edited_channel_post updates.

func (*Bot) AddEditedMessageHandler

func (b *Bot) AddEditedMessageHandler(matcher Matcher, handler Handler)

AddEditedMessageHandler adds an handler for edited_message updates.

func (*Bot) AddInlineQueryHandler

func (b *Bot) AddInlineQueryHandler(matcher Matcher, handler Handler)

AddInlineQueryHandler adds an handler for inline_query updates.

func (*Bot) AddMessageHandler

func (b *Bot) AddMessageHandler(matcher Matcher, handler Handler)

AddMessageHandler adds an handler for message updates.

func (*Bot) AddMyChatMemberHandler

func (b *Bot) AddMyChatMemberHandler(matcher Matcher, handler Handler)

AddMyChatMemberHandler adds an handler for my_chat_member updates.

func (*Bot) AddPollAnswerHandler

func (b *Bot) AddPollAnswerHandler(matcher Matcher, handler Handler)

AddPollAnswerHandler adds an handler for callback_query updates.

func (*Bot) AddPollHandler

func (b *Bot) AddPollHandler(matcher Matcher, handler Handler)

AddPollHandler adds an handler for callback_query updates.

func (*Bot) AddPreCheckoutQueryHandler

func (b *Bot) AddPreCheckoutQueryHandler(matcher Matcher, handler Handler)

AddPreCheckoutQueryHandler adds an handler for callback_query updates.

func (*Bot) AddShippingQueryHandler

func (b *Bot) AddShippingQueryHandler(matcher Matcher, handler Handler)

AddShippingQueryHandler adds an handler for callback_query updates.

func (*Bot) AnswerCallbackQuery

func (b *Bot) AnswerCallbackQuery(request axon.O) (result bool, err error)

AnswerCallbackQuery send an answer to the given callback query https://core.telegram.org/bots/api#answercallbackquery

func (*Bot) Close

func (b *Bot) Close() (err error)

Close closea the bot instance see https://core.telegram.org/bots/api#close

func (*Bot) CopyMessage

func (b *Bot) CopyMessage(request axon.O) (result axon.O, err error)

CopyMessage copy messages of any kind. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. see https://core.telegram.org/bots/api#copymessage

func (*Bot) DeleteChatStickerSet

func (b *Bot) DeleteChatStickerSet(request axon.O) (result bool, err error)

DeleteChatStickerSet set a new group sticker set for a supergroup. see https://core.telegram.org/bots/api#deletechatstickerset

func (*Bot) DeleteWebhook

func (b *Bot) DeleteWebhook(request axon.O) (result bool, err error)

DeleteWebhook implements deleteWebhook from Telegram Bot API see https://core.telegram.org/bots/api#deletewebhook

func (*Bot) EditMessageLiveLocation

func (b *Bot) EditMessageLiveLocation(request axon.O) (result axon.O, err error)

EditMessageLiveLocation sends a location see https://core.telegram.org/bots/api#editmessagelivelocation

func (*Bot) Forever

func (b *Bot) Forever(ctx context.Context, wg *sync.WaitGroup, source UpdatesSource) error

Forever starts the bot and processes updates until context is done.

func (*Bot) ForwardMessage

func (b *Bot) ForwardMessage(request axon.O) (result axon.O, err error)

ForwardMessage forwards messages of any kind see https://core.telegram.org/bots/api#forwardmessage

func (*Bot) GetChat

func (b *Bot) GetChat(request axon.O) (result axon.O, err error)

GetChat get up to date information about the chat. see https://core.telegram.org/bots/api#getchat

func (*Bot) GetChatAdministrators

func (b *Bot) GetChatAdministrators(request axon.O) (result axon.A, err error)

GetChatAdministrators get the number of members in a chat. see https://core.telegram.org/bots/api#getchatmemberscount

func (*Bot) GetChatMember

func (b *Bot) GetChatMember(request axon.O) (result axon.O, err error)

GetChatMember gets information about a member of a chat. see https://core.telegram.org/bots/api#getchatmember

func (*Bot) GetChatMembersCount

func (b *Bot) GetChatMembersCount(request axon.O) (result int64, err error)

GetChatMembersCount get the number of members in a chat. see https://core.telegram.org/bots/api#getchatmemberscount

func (*Bot) GetFile

func (b *Bot) GetFile(fileId string) (result axon.O, err error)

GetFile gets basic info about a file and prepare it for downloading. see https://core.telegram.org/bots/api#getfile

func (*Bot) GetMe

func (b *Bot) GetMe() (result *User, err error)

GetMe returns basic information about the bot in form of a User object. see https://core.telegram.org/bots/api#getme

func (*Bot) GetMyCommands

func (b *Bot) GetMyCommands() (result axon.A, err error)

GetMyCommands send an answer to the given callback query https://core.telegram.org/bots/api#getmycommands

func (*Bot) GetUserProfilePhotos

func (b *Bot) GetUserProfilePhotos(request axon.O) (result axon.O, err error)

GetUserProfilePhotos gets user profile photos. see https://core.telegram.org/bots/api#getuserprofilephotos

func (*Bot) GetWebhookInfo

func (b *Bot) GetWebhookInfo() (result axon.O, err error)

GetWebhookInfo get current webhook status https://core.telegram.org/bots/api#getwebhookinfo

func (*Bot) KickChatMember

func (b *Bot) KickChatMember(request axon.O) (result bool, err error)

KickChatMember kicks a user from a group, a supergroup or a channel. see https://core.telegram.org/bots/api#kickchatmember

func (*Bot) LeaveChat

func (b *Bot) LeaveChat(request axon.O) (result bool, err error)

LeaveChat leave a group, supergroup or channel. see https://core.telegram.org/bots/api#leavechat

func (*Bot) LogOut

func (b *Bot) LogOut() (err error)

LogOut logs the bot out of the cloud Bot API server see https://core.telegram.org/bots/api#logout

func (*Bot) PinChatMessage

func (b *Bot) PinChatMessage(request axon.O) (result bool, err error)

PinChatMessage pins a message for the given chat https://core.telegram.org/bots/api#pinchatmessage

func (*Bot) PromoteChatMember

func (b *Bot) PromoteChatMember(request axon.O) (result bool, err error)

PromoteChatMember unban a previously kicked user in a supergroup or channel. see https://core.telegram.org/bots/api#promotechatmember

func (*Bot) RestrictChatMember

func (b *Bot) RestrictChatMember(request axon.O) (result bool, err error)

RestrictChatMember unban a previously kicked user in a supergroup or channel. see https://core.telegram.org/bots/api#restrictchatmember

func (*Bot) SendAnimation

func (b *Bot) SendAnimation(request axon.O) (result axon.O, err error)

SendAnimation sends an animation see https://core.telegram.org/bots/api#sendanimation

func (*Bot) SendAudio

func (b *Bot) SendAudio(request axon.O) (result axon.O, err error)

SendAudio sends an audio see https://core.telegram.org/bots/api#sendaudio

func (*Bot) SendChatAction

func (b *Bot) SendChatAction(request axon.O) (result bool, err error)

SendChatAction sends a chat action see https://core.telegram.org/bots/api#sendchataction

func (*Bot) SendContact

func (b *Bot) SendContact(request axon.O) (result axon.O, err error)

SendContact sends a venue see https://core.telegram.org/bots/api#sendcontact

func (*Bot) SendDice

func (b *Bot) SendDice(request axon.O) (result axon.O, err error)

SendDice sends a dice see https://core.telegram.org/bots/api#senddice

func (*Bot) SendDocument

func (b *Bot) SendDocument(request axon.O) (result axon.O, err error)

SendVideo sends a video see https://core.telegram.org/bots/api#senddocument

func (*Bot) SendLocation

func (b *Bot) SendLocation(request axon.O) (result axon.O, err error)

SendLocation sends a location see https://core.telegram.org/bots/api#sendlocation

func (*Bot) SendMediaGroup

func (b *Bot) SendMediaGroup(request axon.O) (result axon.O, err error)

SendVoice sends a media group see https://core.telegram.org/bots/api#sendmediagroup

func (*Bot) SendMessage

func (b *Bot) SendMessage(request axon.O) (result axon.O, err error)

SendMessage sends a text message see https://core.telegram.org/bots/api#sendmessage

func (*Bot) SendPhoto

func (b *Bot) SendPhoto(request axon.O) (result axon.O, err error)

SendPhoto sends a photo see https://core.telegram.org/bots/api#sendphoto

func (*Bot) SendPoll

func (b *Bot) SendPoll(request axon.O) (result axon.O, err error)

SendPoll sends a poll see https://core.telegram.org/bots/api#sendpoll

func (*Bot) SendVenue

func (b *Bot) SendVenue(request axon.O) (result axon.O, err error)

SendVenue sends a venue see https://core.telegram.org/bots/api#sendvenue

func (*Bot) SendVideo

func (b *Bot) SendVideo(request axon.O) (result axon.O, err error)

SendVideo sends a video see https://core.telegram.org/bots/api#sendvideo

func (*Bot) SendVideoNote

func (b *Bot) SendVideoNote(request axon.O) (result axon.O, err error)

SendVoice sends a video note see https://core.telegram.org/bots/api#sendvideonote

func (*Bot) SendVoice

func (b *Bot) SendVoice(request axon.O) (result axon.O, err error)

SendVoice sends a voice see https://core.telegram.org/bots/api#sendvoice

func (*Bot) SetChatStickerSet

func (b *Bot) SetChatStickerSet(request axon.O) (result bool, err error)

SetChatStickerSet set a new group sticker set for a supergroup. see https://core.telegram.org/bots/api#setchatstickerset

func (*Bot) SetMyCommands

func (b *Bot) SetMyCommands(request axon.O) (result bool, err error)

SetMyCommands AnswerCallbackQuery send an answer to the given callback query https://core.telegram.org/bots/api#setmycommands

func (*Bot) SetWebhook

func (b *Bot) SetWebhook(request axon.O) (result bool, err error)

SetWebhook implements setWebhook from Telegram Bot API. see https://core.telegram.org/bots/api#setwebhook

func (*Bot) StopMessageLiveLocation

func (b *Bot) StopMessageLiveLocation(request axon.O) (result axon.O, err error)

StopMessageLiveLocation sends a location see https://core.telegram.org/bots/api#stopmessagelivelocation

func (*Bot) UnbanChatMember

func (b *Bot) UnbanChatMember(request axon.O) (result bool, err error)

UnbanChatMember unban a previously kicked user in a supergroup or channel. see https://core.telegram.org/bots/api#unbanchatmember

func (*Bot) UnpinAllChatMessages

func (b *Bot) UnpinAllChatMessages(request axon.O) (result bool, err error)

UnpinAllChatMessages clears the list of pinned messages in a chat. see https://core.telegram.org/bots/api#unpinallchatmessages

func (*Bot) UnpinChatMessage

func (b *Bot) UnpinChatMessage(request axon.O) (result bool, err error)

UnpinChatMessage removes a message from the list of pinned messages in a chat. see https://core.telegram.org/bots/api#unpinchatmessage

type Configuration

type Configuration struct {
	APIToken   string `json:"api_token"`
	ServerPort string `json:"server_port"`
	WebhookUrl string `json:"webhook_url"`
	WorkerNo   int    `json:"worker_no"`
}

Configuration struct holds configuration data for the bot

type Handler

type Handler func(context.Context, *Bot, axon.O) (bool, error)

Handler is a function that will handle an API update

type Matcher

type Matcher func(*Bot, axon.O) bool

Matcher is a function that will decide wheter an update will be handled by a Matcher

func And

func And(matchers ...Matcher) Matcher

func ChatType

func ChatType(chatType string) Matcher

ChatType matches axon.A certain chat type

func IsFrom

func IsFrom(userID int64) Matcher

IsFrom matches private messages from axon.A known userID

func Not

func Not(matcher Matcher) Matcher

func Or

func Or(matchers ...Matcher) Matcher

type UpdatesSource

type UpdatesSource func(*Bot, context.Context, chan axon.O)

UpdatesSource are function that will get updates from the API server or any other source and publish them onto a channel. A proper UpdateSource will handle the context argument as needed.

type UploadFile

type UploadFile struct {
	FileName string
	Data     []byte
}

type User

type User struct {
	ID                      int64  `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"`
	CanJoinGroups           bool   `json:"can_join_groups,omitempty"`
	CanReadAllGroupMessages bool   `json:"can_read_all_group_messages,omitempty"`
	SupportsInlineQueries   bool   `json:"supports_inline_queries,omitempty"`
}

User struct stores user infos for the bot user

Jump to

Keyboard shortcuts

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