gotbot

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2023 License: GPL-3.0 Imports: 12 Imported by: 0

README

gotbot

A generic telegram bot api client made with go.
Introduction

This package was a result of my first telegram bot implementation. When I started that project I planned to only be concerned with my bot's functionality and not the details of handling requests and responses from the telegram bot api server. But after browsing for telegram api client packages written with go, I wasn't satisfied with what I found and I finally decided it was better to write one myself.

Since the telegram bot api is very vast, only some of the functionalities are currently implemented. But a contribution from you would very much be appreciated to minimize this limitation as much as possible.

Getting started

in order to start using this package, use the following command to add this package to your project.

go get github.com/roskee/gotbot

once you have successfully installed the package, you can use the methods and models specified in the package to set up and manage your bot.

Basics

Assuming you have created your bot on telegram and have your token. you can use the NewBot function to connect your bot.
Learn more about creating your first bot

apiToken := os.Getenv("API_KEY")
bot := gotbot.NewBot(apiToken, gotbot.BotOptions{})

Then you can use the RegisterMethod to register your first command.
Learn more about commands

err := bot.RegisterMethod("start", "start command", func(update entity.Update) {
    fmt.Println("start command was sent")
    // do you thing... maybe reply to the user
})

Finally, you have to start your server to actually listen for user interactions with your bot. There are two mutually exclusive ways of doing this.

polling

you can call getUpdates method periodically to get all user interactions since your last call to it. your server will indefinitely (with the given interval) ask the telegram bot api for new updates.

err = bot.Poll(5 * time.Second, entity.UpdateConfig{})
webhook

you can also register a webhook url for the telegram bot api server to call whenever there is a new update. This method only works with these security configurations

webhook := entity.Webhook{
    URL: "https://myurl.com/updatesCallback",
}
err = bot.Listen(5000, webhook, entity.UpdateConfig{})

Best Wishes!
Kirubel Adamu

Documentation

Overview

Package gotbot is used to manage a telegram bot. It can send requests to the telegram server on behalf of a bot and handle both polling and webhook requests to that bot.

Index

Constants

View Source
const (
	// MessageText is for text message.
	MessageText MessageType = "sendMessage"
	// MessagePhoto is for single photo message.
	MessagePhoto = "sendPhoto"
	// MessageAudio is for single audio message.
	MessageAudio = "sendAudio"
	// MessageDocument is for single document message.
	MessageDocument = "sendDocument"
	// MessageVideo is for single video message.
	MessageVideo = "sendVideo"
	// MessageAnimation is for single animation message.
	MessageAnimation = "sendAnimation"
	// MessageVoice is for single voice message.
	MessageVoice = "sendVoice"
	// MessageVideoNote is for rounded, 1 minute MPEG4 videos.
	MessageVideoNote = "sendVideoNote"
	// MessageMediaGroup is for a group of media messages including photos, audios, videos, documents.
	MessageMediaGroup = "sendMediaGroup"
	// MessageLocation is for  location message.
	MessageLocation = "sendLocation"
	// MessageVenue is for venue message.
	MessageVenue = "sendVenue"
	// MessageContact is for phone contact message.
	MessageContact = "sendContact"
	// MessagePoll is for poll message.
	MessagePoll = "sendPoll"
	// MessageDice is for dice message.
	MessageDice = "sendDice"
	// MessageChatAction is for chat action message.
	MessageChatAction = "sendChatAction"
)

Variables

View Source
var (
	// SetApplicationJSON is a function that sets the content-type of a request to application/json
	SetApplicationJSON = func(req *http.Request) error {
		req.Header.Set("Content-Type", "application/json")
		return nil
	}
	// SetMultipartFormData is a function that sets the content-type of a request to multipart/form-data
	SetMultipartFormData = func(req *http.Request) error {
		req.Header.Set("Content-Type", "multipart/form-data")
		return nil
	}
)

request setups

View Source
var (
	// GetJSONBody marshals a given object to a json serialized string
	GetJSONBody = func(value any) (io.Reader, BodyOptions, error) {
		body, err := json.Marshal(value)
		return bytes.NewBuffer(body), BodyOptions{ContentType: "application/json"}, err
	}
	// GetMultipartBody creates a form data with the given fields and files.
	// if `files` contains an element with the same name in `msg`, only the file is added to the body.
	GetMultipartBody = func(msg any, attachedFiles ...entity.FileEnvelop) (io.Reader, BodyOptions, error) {
		body := &bytes.Buffer{}
		writer := multipart.NewWriter(body)

		if err := writeFields(msg, body, writer); err != nil {
			return nil, BodyOptions{}, err
		}

		for _, v := range attachedFiles {
			if err := v.SetValue(writer, ""); err != nil {
				return nil, BodyOptions{}, err
			}
		}

		return body, BodyOptions{ContentType: writer.FormDataContentType()}, writer.Close()
	}
)

body setters

Functions

This section is empty.

Types

type BodyOptions

type BodyOptions struct {
	ContentType string
}

type Bot

type Bot interface {

	// SendRawRequest sends a request to the telegram server and returns the result part of the response as a serialized json body
	SendRawRequest(httpMethod, function string, getBody func() (io.Reader, BodyOptions, error), setReq func(req *http.Request) error) ([]byte, error)

	// RegisterMethod registers a new bot command with its name, description and implementation to the telegram server
	RegisterMethod(name, description string, function func(update entity.Update)) error

	// SendMessage is the implementation of the builtin sendMessage function of the bot.
	// It sends the given message to the sender user
	SendMessage(msg entity.MessageEnvelop) (entity.Message, error)

	// SendMessageAny can be used to send any kind of message manually.
	// All other Send* messages use this method internally.
	SendMessageAny(msgType MessageType, message entity.MessageEnvelop, response any, attachedFiles ...entity.FileEnvelop) error

	// GetMyCommands is the implementation of the builtin getMyCommands function of the bot.
	// It returns the list of all currently registered commands
	GetMyCommands() ([]entity.Command, error)

	// SetMyCommands is the implementation of the builtin setMyCommands function of the bot.
	SetMyCommands(commands []entity.Command) error

	// DeleteMyCommands is the implementation of the builtin deleteMyCommands function of the bot.
	DeleteMyCommands(commandScope envelop.DeleteMyCommandsEnvelop) (bool, error)

	// GetMe is the implementation of the builtin getMe function of the bot
	GetMe() (entity.User, error)

	// Listen creates a http server to listen for updates as a webhook handler.
	// It returns on failure only
	Listen(port int, webhook entity.Webhook, config entity.UpdateConfig) error

	// Poll initiates a manual poll to get updates from the telegram server.
	// instructions on what to do on the updates should be set on config.
	// note that registered methods are automatically called.
	//
	// It returns on failure only
	Poll(duration time.Duration, configs entity.UpdateConfig) error

	// AnswerCallbackQuery send answers to callback queries sent from entity.InlineKeyboardMarkup.
	AnswerCallbackQuery(options entity.AnswerCallbackQueryEntity) error

	// ForwardMessage is used to forward messages of any kind.
	// Service messages can't be forwarded.
	ForwardMessage(msgEnvelop envelop.ForwardMessageEnvelop) (entity.Message, error)

	// CopyMessage is used to copy messages of any kind.
	// Service messages and invoice messages can't be copied.
	// A quiz poll can be copied only if the value of
	// the field 'correct_option_id' is known to the bot.
	CopyMessage(msgEnvelop envelop.CopyMessageEnvelop) (int64, error)

	// SendPhoto is used to send photos.
	SendPhoto(msg entity.MessageEnvelop) (entity.Message, error)

	// SendAudio is used to send audio files.
	// For telegrm to show the audio in the music player,
	// it must be in the format .mp3 or .m4a.
	//
	// Note: bots can only send audio files up to 50 MB in size.
	SendAudio(msg entity.MessageEnvelop) (entity.Message, error)

	// SendVideo is used to send video files.
	// Only MPEG4 videos are supported.
	// (other formats can be sent as a document)
	//
	// Note: bots can only send video files up to 50 MB in size.
	SendVideo(msg entity.MessageEnvelop) (entity.Message, error)

	// SendLocation is used to send location
	SendLocation(msg entity.MessageEnvelop) (entity.Message, error)

	SendDocument(msg entity.MessageEnvelop) (entity.Message, error)

	SendVoice(msg entity.MessageEnvelop) (entity.Message, error)

	// SendMediaGroup is used to send a group of photos, videos, documents or audios as an album.
	//
	// Note: Documents and audio files can be only grouped in an album with messages of the same type.
	SendMediaGroup(msg entity.MessageEnvelop) ([]entity.Message, error)

	// SendVideoNote is used to send rounded square mp4 videos of up to 1 minute long.
	SendVideoNote(msg entity.MessageEnvelop) (entity.Message, error)

	// SendContact is used to send phone contacts.
	SendContact(msg entity.MessageEnvelop) (entity.Message, error)
	// GetUserProfilePhotos is used to get a list of profile pictures for a user.
	GetUserProfilePhotos(options envelop.GetUserProfilePhotos) (entity.UserProfilePhotos, error)
	// GetFile is used to get basic info about a file and prepare it for downloading.
	// For the moment, bots can download files of up to 20MB in size.
	GetFile(options envelop.GetFile) (entity.File, error)
	// DownloadFile downloads a file from the telegram server.
	DownloadFile(file entity.File) ([]byte, error)
	// SendPoll is used to send a native poll.
	SendPoll(msg entity.MessageEnvelop) (entity.Message, error)
	// SendChatAction is used to send a chat action.
	SendChatAction(msg entity.MessageEnvelop) (bool, error)
	// SendAnimation is used to send animation files.
	// For the moment, bots can send animation files of up to 50 MB in size.
	SendAnimation(msg entity.MessageEnvelop) (entity.Message, error)
	// SendDice is used to send an animated emoji that will display a random value.
	SendDice(msg entity.MessageEnvelop) (entity.Message, error)
	// SendVenue is used to send information about a venue.
	SendVenue(msg entity.MessageEnvelop) (entity.Message, error)
	// SetChatAdministratorCustomTitle is used to set a custom title for an administrator
	// in a supergroup promoted by the bot.
	SetChatAdministratorCustomTitle(title envelop.SetChatAdministratorCustomTitle) (bool, error)
	// EditMessageText is used to edit text and game messages.
	EditMessageText(msg envelop.EditMessageTextEnvelop) (entity.Message, error)
	// EditMessageCaption is used to edit captions of messages.
	EditMessageCaption(msg envelop.EditMessageCaptionEnvelop) (entity.Message, error)
	// EditMessageMedia is used to edit animation, audio, document, photo, or video messages.
	EditMessageMedia(msg envelop.EditMessageMediaEnvelop) (entity.Message, error)
	// EditMessageLiveLocation is used to edit live location messages.
	EditMessageLiveLocation(msg envelop.EditMessageLiveLocationEnvelop) (entity.Message, error)
	// StopMessageLiveLocation is used to stop updating a live location message before live_period expires.
	StopMessageLiveLocation(msg envelop.StopMessageLiveLocationEnvelop) (entity.Message, error)
	// EditMessageReplyMarkup is used to edit only the reply markup of messages.
	EditMessageReplyMarkup(msg envelop.EditMessageReplyMarkupEnvelop) (entity.Message, error)
	// StopPoll is used to stop a poll which was sent by the bot.
	StopPoll(msg envelop.StopPollEnvelop) (entity.Poll, error)
	// DeleteMessage is used to delete a message, including service messages, with the following limitations:
	// - A message can only be deleted if it was sent less than 48 hours ago.
	// - Bots can delete outgoing messages in private chats, groups, and supergroups.
	// - Bots can delete incoming messages in private chats.
	// - Bots granted can_post_messages permissions can delete outgoing messages in channels.
	// - If the bot is an administrator of a group, it can delete any message there.
	// - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
	DeleteMessage(msg envelop.DeleteMessageEnvelop) (bool, error)
}

Bot is a gateway to manage a telegram bot

func NewBot

func NewBot(apiKey string, options BotOptions) Bot

NewBot returns a new bot with the token apiKey

type BotOptions

type BotOptions struct {
	// Logger is the logger to use for logging
	Logger Logger
	// Client is the http client to use for sending requests
	Client http.Client
}

BotOptions hold the options for the bot

type Fields

type Fields map[string]any

type JSONLogger

type JSONLogger struct {
	// TimeFormat contains the layout of the time field on the log.
	// It can be one of the standard time layouts from `time` package.
	TimeFormat string
}

JSONLogger is the default logger.

func (*JSONLogger) Debug

func (d *JSONLogger) Debug(msg string, fields Fields)

func (*JSONLogger) Error

func (d *JSONLogger) Error(msg string, fields Fields)

func (*JSONLogger) Info

func (d *JSONLogger) Info(msg string, fields Fields)

func (*JSONLogger) Warn

func (d *JSONLogger) Warn(msg string, fields Fields)

type Level

type Level string

Level is the level of the log generated. It can be one of `Debug`, `Info`, `Warn`, or `Error`

const (
	Debug Level = "debug"
	Info  Level = "info"
	Warn  Level = "warn"
	Error Level = "error"
)

type Logger

type Logger interface {
	Debug(msg string, fields Fields)
	Info(msg string, fields Fields)
	Warn(msg string, fields Fields)
	Error(msg string, fields Fields)
}

Logger is used to print any messages that might be generated inside this package. The default log is json formatted.

Note: default fields such as `time` are not included on `fields`. So if you plan on creating a custom logger, be sure to include those fields as well.

type MessageType

type MessageType string

Directories

Path Synopsis
Package entity contains abstractions of all json objects that might be sent from the telegram server
Package entity contains abstractions of all json objects that might be sent from the telegram server
Package envelop contains models that will be used for sending requests.
Package envelop contains models that will be used for sending requests.
Package router contains models and methods associated with polling and webhooks
Package router contains models and methods associated with polling and webhooks

Jump to

Keyboard shortcuts

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