telego

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2022 License: MIT Imports: 8 Imported by: 6

README

Telego

Go Reference example workflow Go Report Card Version Development status

A Go library for creating telegram bots.

telego logo inspired by Golang logo


Features

  • Fast and reliable
  • Highly customizable
  • Webhook support
  • Full support for telegram bot api
  • Offers two different ways for managing the bot updates :
    1. Handlers.
    2. Special channels
  • Automatic poll management : You don't need to worry about poll updates. Telego takes care of that for you. Just create a poll, send it and sit back and monitor the poll update via a go channel.
  • You can create keyboards and inline keyboards easily.

Requirements

  • Go 1.17 or higher.
  • Small and basic knowledge about telegram bots.

Installation

Install the package into your $GOPATH with the go command from terminal :

$ go get -u github.com/SakoDroid/telego

Git needs to be installed on your computer.


Usage

Quick start

The following code creates a bot and starts receiving updates. If the update is a text message that contains "hi" the bot will respond "hi to you too!".

import (
   "fmt"
   
   bt "github.com/SakoDroid/telego"
   cfg "github.com/SakoDroid/telego/configs"
   objs "github.com/SakoDroid/telego/objects"
)

func main(){

   bot, err := bt.NewBot(cfg.Default("your API key"))

   if err == nil{
       err == bot.Run()
       if err == nil{
           go start(bot)
       }
   }
}

func start(bot *bt.Bot){

    //The general update channel.
    updateChannel := bot.GetUpdateChannel()

   //Adding a handler. Everytime the bot receives message "hi" in a private chat, it will respond "hi to you too".
   bot.AddHandler("hi",func(u *objs.Update) {
   	_,err := bot.SendMessage(u.Message.Chat.Id,"hi to you too","",u.Message.MessageId,false,false)
   	if err != nil{
   		fmt.Println(err)
   	}
   },"private")

   //Monitores any other update. (Updates that don't contain text message "hi" in a private chat)
    for {
        update := <- updateChannel

       //Some processing on the update
    }
}

Step by step

Configuring the bot

First you need to import required libraries :

import (
   bt "github.com/SakoDroid/telego"
   cfg "github.com/SakoDroid/telego/configs"
   objs "github.com/SakoDroid/telego/objects"
)

Then you need to create bot configs. You can use default configs by using Default(apiKey string) method of the configs pckage. This method generates a BotConfig that does not use webhook and queries the updates from the server every 300 milli seconds. You can create a BotConfig struct to access more options (including webhook).

BotConfigs struct is located in configs package and contains these fields :

/*This is the bot api server. If you dont have a local bot api server, use "configs.DefaultBotAPI" for this field.*/

BotAPI string

/*The API key for your bot. You can get the api key (token) from botfather*/

APIKey string

/*The settings related to getting updates from the api server. This field shoud only be populated when Webhook field is false, otherwise it is ignored.*/

UpdateConfigs *UpdateConfigs

/*This field idicates if webhook should be used for receiving updates or not.*/

Webhook bool

/*This field represents the configs related to webhook.*/
WebHookConfigs *WebHookConfigs

/*All the logs related to bot will be written in this file. You can use configs.DefaultLogFile for default value*/

LogFileAddress string


//BlockedUsers is a list of blocked users.

BlockedUsers []BlockedUser `json:"blocked_users"`
Not using webhook

To create bot configs you need an UpdateConfigs to populate related field in BotConfigs. UpdateConfigs struct contains following fields :

/*Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.*/

 Limit int

 /*Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.*/

 Timeout int

 /*List of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.
 Please note that this parameter doesnt affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time.*/

 AllowedUpdates []string

 /*This field indicates the frequency to call getUpdates method. Default is one second*/

 UpdateFrequency time.Duration

You can use configs.DefaultUpdateConfigs() to create default update configs. Otherwise, you can create your own custom update configs. You can read

Using webhook

To use webhook you need a key file and a certificate file since webhook is based on HTTPS. Telegram bot API supports self-signed certificates. You can create a self-signed certificate using OpenSSL. Read this article to find out how.

To define the configs for webhook, WebHookConfig struct should be used. It contains the following fields :


type WebHookConfigs struct {

	/*The web hook url.*/
	URL string

	/*The port that webhook server will run on. Telegram api only suppotrs 80,443,88,8443. 8443 is recommended. Pass 0 for default https port (443)*/
	Port int

	/*The address of the public key certificate file.*/
	KeyFile string

	/*The address of the certificate file.*/
	CertFile string

	/*The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS*/
	IP string

	/*Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.*/
	MaxConnections int

	/*List of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.
	Please note that this parameter doesnt affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time.*/
	AllowedUpdates []string

	/*Pass True to drop all pending updates*/
	DropPendingUpdates bool
}

This struct is located in the configs package. To use webhook, first you need to create a WebHooConfigs and populate it's fields. Then populate WebHookConfigs field of the BotConfigs with it. Thats all! We recommend using port 8443 for webhook, using 80 or 443 needs root permession which means your bot will have root permissions which is not safe. You can see an example code below :

Note : UpdateConfigs is no longer needed if you're using webhook. So leave this field empty.

import (
	bt "github.com/SakoDroid/telego"
	cfg "github.com/SakoDroid/telego/configs"
	objs "github.com/SakoDroid/telego/objects"
 )

 func main(){

    //WebHookConfigs. We are using 8443 port here.
    whcfg := &cfg.WebHookConfigs{
		URL:      "https://example.com:8443",
		IP:       "123.45.78.90",
		KeyFile:  "keyfile.key",
		CertFile: "certfile.crt",
		Port:     8443,
	}
    
    cf := cfg.BotConfigs{BotAPI: cfg.DefaultBotAPI, APIKey: "your api key", Webhook: true, WebHookConfigs: whcfg, LogFileAddress: cfg.DefaultLogFile}

    bot, err := bt.NewBot(&cf)
    if err == nil{
        err == bot.Run()
        if err == nil{
            //Do anything you want with the bot.
        }
    }
 }
Loading and saving the configs

You can load the bot configs from config file or save it in the file using Load and Dump methods. Config file's name is config.json. These methods are located in configs package. In the example code below first we create a config, then save it and then load it again into a new config :

bc1 := configs.Default("API key")
_ := configs.Dump(bc1)

bc2, _ := configs.Load()

fmt.Println(reflect.DeepEqual(bc1, bc2)) //Prints true

Note: Since telego 1.7.0 an option has been added which updates the bot configs every second. This option works while the bot is running and reads the configs from the configs.json file. This file is created automatically when the bot starts. With the help of this option you can change the bot configs even when the bot is up and running only by changing the config.json file, this means you don't need to stop the bot to change the configs or to remove a user from the block list.

Creating and starting the bot

After you have created BotConfigs you can create the bot by passing the BotConfigs struct you've created to NewBot method located in telego package. After bot is created call Run() method and your bot will start working and will receive updates from the api server:

Note : Webhook is not used in the example codes. Using webhook only changes the code related to creating the bot and receiving updates or sending data abviously won't be affected.

import (
   bt "github.com/SakoDroid/telego"
   cfg "github.com/SakoDroid/telego/configs"
   objs "github.com/SakoDroid/telego/objects"
)

func main(){
   up := cfg.DefaultUpdateConfigs()
   
   cf := cfg.BotConfigs{BotAPI: cfg.DefaultBotAPI, APIKey: "your api key", UpdateConfigs: up, Webhook: false, LogFileAddress: cfg.DefaultLogFile}

   bot, err := bt.NewBot(&cf)
   if err == nil{
       err == bot.Run()
       if err == nil{
           //Do anything you want with the bot.
       }
   }
}

Now that the bot is running it will receive updates from api server and passes them into UpdateChannel. So you can use this channel to know if an update is received from api server. You can get the channel via GetUpdateChannel() method of the bot :

import (
   bt "github.com/SakoDroid/telego"
   cfg "github.com/SakoDroid/telego/configs"
   objs "github.com/SakoDroid/telego/objects"
)

func main(){
   up := cfg.DefaultUpdateConfigs()
   
   cf := cfg.BotConfigs{BotAPI: cfg.DefaultBotAPI, APIKey: "your api key", UpdateConfigs: up, Webhook: false, LogFileAddress: cfg.DefaultLogFile}

   bot, err := bt.NewBot(&cf)
   if err == nil{
       err == bot.Run()
       if err == nil{
           go start(bot)
       }
   }
}

func start(bot *bt.Bot){
    updateChannel := bot.GetUpdateChannel()
    for {
        update := <- updateChannel
        //Do your own processing.
    }
}
Receiving updates
Handlers

You can use handlers for routing text messages. You specify a function and everytime a text message is received which the handler's regex matches with the text, the specified function will be called. Function format should be like this exampleFunction(*objs.Update). To add a handler you sipmly call AddHandler(pattern string, handler func(*objs.Update), chatTypes ...string). Arguments :

  1. "Pattern" is the regex pattern which will be matched against the received text message.
  2. "chatType" : is a string array containing chat types which the handler will act on. It can be "private","group","supergroup","channel" and "all".
  3. "handler" : is the function that will be called.

Handlers are super easy to use; You can see an example in Quick start section.

Special channels

In telego you can register special channels. Special channels are channels for a specific update type. Meaning this channels will be updated when the specified update type is received from api server, giving the developers a lot more felxibility. To use special channels you need to call RegisterChannel(chatId string, mediaType string) method of the advanced bot (so for using this method, first you should call AdvancedMode() method of the bot). This method is fully documented in the source code but we will describe it here too. This method takes two arguments :

  1. chatId : This is a string representing a certain chat which this channel will be dedicated to. This argument can be chat identification of a chat or username of a channel or supergroup. You can pass an empty string for this argument.
  2. mediaType : This argument specifies an update type which the channel will be dedicated to. For example if you pass "message", the returned channel will only be updated when an update containing message field [for a specified chat] is received. You can pass an empty string for this argument.

Note : Both arguments can be used together to create channels that will be updated only when a certain field (mediaType) is present in the received update for a specified chat (chatId).

Examples :

This method can be used in four ways :

  1. RegisterChannel("123456","message") : The returned channel will be updated when a message (text,photo,video ...) is received from a chat with "123456" as it's chat id.

  2. RegisterChannel("","message") : The returned channel will be updated everytime a message is received from any chat.

  3. RegisterChannel("123456","") : The returned channel will be updated everytime an update of any kind is received for the specified chat.

  4. RegisterChannel("","") : The returned is the global update channel which will be updated everytime an update is received. You can get this channel by calling getUpdateChannel() method too.

Note : When a channel is registered it is not editable. Meaning that calling the RegisterChannel method with the same arugments won't create a new channel and the previously created channel will be returned.

Once a channel is created it cannot be edited, But it can be deleted. To delete a channel (unregister it) call UnRegisterChannel(chatId string,mediaType string) method of the AdvancedBot. If a channel has been registered for the given arguments it will be cleared.

Update receiving priority :

Since different types of channels and handlers may get involved it's important to know the priority of them. Meaning when an update is received which methods have higher priority to be executed and in case of channels which channels will be first considered to have the update passed into them. Basically this is how handlers and channels are prioritized :

  1. Handlers
  2. Chat channels :
    1. Update types
    2. General
  3. Global channels :
    1. Update types
    2. General channel

When an update is received, first it is compared against all the handlers. If a handler's regex matching is successful the handler will be executed. If not handler is successfull then channels are checked. (Hanlders don't have priority and every successful regex match is executed.)

After none of the handlers are executed, the update is checked to see if it contains chat information and if it does, channels registered for that chat are checked. If a channel is registered for the field that the update contains it will be passed into the channel. If no channel is registered for the field then it will be passed into the general channel for the chat.( For example lets assume you haved called RegisterChannel("123456","message") method, in this case if an update for a chat that it's chat id is "123456" is received that contains message field, it will be passed into this channel. ) If this step fails (does not have chat information or no channel is registered for the chat) then the update type channels are checked and if the update contains a field that does have a channel registered for it the related field will be passed into the channel.(For example if the update contains message field and you have called RegisterChannel("","message") method, the update will be passed into the channel). If this step fails too then the update will be passed into general update channel.

To summarize :

Update is received -> Handlers
                          |
                          |
If no hanlder is executed |
                          |
                          |                                                / Specified update type channel
                     Chat channels (if update is relevant to a chat) ----- 
                             |                                             \ General chat channel
                             |
if chat channel check fails  |
                             |
                             |----------> General update type channels
                                                   |
                                                   |
                              if this check fails  |
                                                   |
                                                   |----------> General update channel
                              

Note :

Handlers and special channels can be used together. For example the below code add a handler for text message "hi". Everytime the bot receives "hi" in a private chat it responds "hi to you too, send a location". Then it rgisters a channel for receiving messages in that chat and waits for the user to send a message. After message is received it sends the exact same location the user has sent back to the user :

import (
    "fmt"
    
	bt "github.com/SakoDroid/telego"
	cfg "github.com/SakoDroid/telego/configs"
	objs "github.com/SakoDroid/telego/objects"
 )

 func main(){
    up := cfg.DefaultUpdateConfigs()
    
    cf := cfg.BotConfigs{BotAPI: cfg.DefaultBotAPI, APIKey: "your api key", UpdateConfigs: up, Webhook: false, LogFileAddress: cfg.DefaultLogFile}

    bot, err := bt.NewBot(&cf)

    if err == nil{

        err == bot.Run()

        if err == nil{
            go start(bot)
        }
    }
 }

 func start(bot *bt.Bot){

     //The general update channel.
     updateChannel := bot.GetUpdateChannel()

    //Adding a handler. Everytime the bot receives message "hi" in a private chat, it will respond "hi to you too".

    bot.AddHandler("hi",func(u *objs.Update) {

        //Register channel for receiving messages from this chat.
		cc, _ := bot.AdvancedMode().RegisterChannel(strconv.Itoa(u.Message.Chat.Id), "message")

        //Sends back a message
		_, err := bot.SendMessage(u.Message.Chat.Id, "hi to you too, send me a location", "", u.Message.MessageId, false,false)
		if err != nil {
			fmt.Println(err)
		}

        //Waits for an update from this chat
		up := <-*cc

        //Sends back the received location
		_, err = bot.SendLocation(up.Message.Chat.Id, false,false, up.Message.Location.Latitude, up.Message.Location.Longitude, up.Message.Location.HorizontalAccuracy, up.Message.MessageId)


		if err != nil {
			fmt.Println(err)
		}
	},"private")

    //Monitores any other update. (Updates that don't contain text message "hi" in a private chat)
     for {
         update := <- updateChannel

        //Some processing on the update
     }
 }
Methods

To send back text or media (such as photo, video, gif, ...) you can use Send methods. There are several send methods such as SendMessage and SendPhoto. There is two ways to send back data to the client. First way is using unique chat ids (which are integers that are unique for each chat) to send data to private chats, groups and supergroups. Second way is using chat username which can be used to send back data to supergroups (with username) and channels. Methods that use username as chat identificator end with UN.

We will cover some methods below. All these methods are fully documented in the source code and will be described here briefly. In all methods you can ignore number arguments (int or float) by passing 0 and ignore string arguments by passing empty string ("").

  • Note : All bot methods are simplified to avoid unnecessary arguments. To access more options for each method you can call AdvancedMode() method of the bot that will return an advanced version of bot which will give you full access.
Text messages

To send back text you can use SendMessage (chat id) or SendMessageUN (username).

Formatting text messages

Telegram offers three ways for formatting a text. Formatting means adding style to the text, like bolding a text, adding a url, a link, mentioning a user and etc. These three ways are :

  1. HTML style formatting : You can write the text (can be a message or a caption) you want to send in HTML format and pass "HTML" as the parseMode or captionParseMode argument of the send method. See telegram documentation for HTML style formatting.

  2. Markdown style formatting : You can use markdown also to format your text or media caption. Write the text in markdown format and pass "MarkdownV2" or "Markdown" (according to the markdown syntax you've used) as the parseMode or captionParseMode arguements. See telegram documentation for Markdown style formatting.

  3. Message entities : Message entities can be used to format a text. Telego offers a tool for creating formatted texts called TextFormatter. Call GetTextFormatter() method. This method returns a TextFormatter that has a few methods for adding a styled text to the original text. TextFormatter assembles the text and returns it via GetText() method. You need to pass this text as the "text" or "caption" arguments and pass the returned value of GetEntities() method as the "entities" or "captionEntities" arguments of the ASend methods (located in advanced bot). The example below adds anormal text, a bold text, an italic text, a link, a mention and a spoiler to the text and sends it :

tf := bot.GetTextFormatter()
tf.AddNormal("normal text")
tf.AddMention("@someone_username")
tf.AddBold("bold text")
tf.AddItalic("italic text")
tf.AddSpoiler("spoiler text")
tf.AddTextLink("google", "https://google.com")
_, err := bot.AdvancedMode().ASendMessage(
        msg.Message.Chat.Id, tf.GetText(), "", msg.Message.MessageId, false, false, tf.GetEntities(),
        false, false, nil,
	)
Media messages

To send media types such as photo,video,gif,audio,voice,video note,mpeg4 gif,sticker and document you can use their specified method. In general there are three ways to send media :

  1. By file id : File id is a unique id for a file that already exists in telegram servers. Telegram bot api documentation recommends using file id.
  2. By URL : You can pass an HTTP url to send. The file will be downloaded in telegram servers, and then it will be sent to the specified chat.
  3. By file : You can send a file on your computer. The file will be uploaded to telegram servers, and then it will be sent to the specified chat.

Calling each media sending related method returns a MediaSender. MediaSender has all methods that are needed to send a media. For example lets send photo in our computer :

photoFile,err := os.Open("photo.jpg")

if err == nil{

   ms := bot.SendPhoto(chatId, messageId, "custom caption", "")

   _,err = ms.SendByFile(photoFile,false,false)

   if err != nil{
       fmt.Println(err)
   }

}
Media group messages

To send a group of medias (aka albums) first you need to create a MediaGroup by calling CreateAlbum(replyto int) method of the bot. MediaGroup has several methods for adding photo,video,audio and other media types to the album. Keep in mind that according to Telegram bot api documentation about media groups, documents and audio files can be only grouped in an album with messages of the same type. Also the media group must include 2-10 items. The code below shows how to create a media group, add some photo to it and send it :

mg := bot.CreateAlbum(messageId)

//Add a file on the computer.
fl,_ := os.Open("file.jpg")
pa1,_ := mg.AddPhoto("", "", nil)
err := pa1.AddByFile(fl)
if err != nil{
    fmt.Println(err)
}

//Add a photo by file id or url.
pa2,_ ;= mg.AddPhoto("","",nil)
err = pa2.AddByFileIdOrURL("fileId or HTTP url")
if err != nil{
    fmt.Println(err)
}

//Send the media group
_, err = mg.Send(chatId, false,false)

if err != nil {
   fmt.Println(err)
}
Polls

telego library offers automatic poll management. When you create a poll and send the poll bot will receive updates about the poll. Whene you create a poll by CreatePoll method, it will return a Poll which has methods for managing the poll. You should keep the returned pointer (to Poll) somewhere because everytime an update about a poll is received the bot will process the update and update the related poll and notifies user through a [bool]channel (which you can get by calling GetUpdateChannel method of the poll).

  • Note : If an update is received that contains update about a poll and the poll is not registered with the Polls map, the given update is passed into UpdateChannel of the bot. Otherwise, as described above, the related poll will be updated.

Let's see an example :


//A custom function that creates and sends a poll and listens to its updates.
func pollTest(chatId int) {

    //Creates the poll
	poll, _ := bot.CreatePoll(chatId, "How are you?", "regular")

    //Adds some options
	poll.AddOption("good")
	poll.AddOption("not bad")
	poll.AddOption("alright")
	poll.AddOption("bad")

    //Adds an explanation for the poll.
	poll.SetExplanation("This is just a test for telego framework", "", nil)

    //Sends the poll
	err := poll.Send(false,false, 0)

	if err != nil {
		fmt.Println(err)
	} else {

        //Starts waiting for updates and when poll is updated, the updated result of the bot is printed.
		ch := poll.GetUpdateChannel()
		for {
			<-*ch
			fmt.Println("poll updated.")
			for _, val := range poll.GetResult() {
				fmt.Println(val.Text, ":", val.VoterCount)
			}
		}
	}
}
Files

You can get information about a file that is stored in telegram servers and download it into your computer by calling GetFile method. If you want to download the file, pass true for download argument of the method. The below example downloads a received sticker from the user and saves it into the given file (read full documentation of the method for more information) :

//Receives upadate
update := <- updateChannel

//Get sticker file id
fi := update.Message.Sticker.FileId

//Open a file in the computer.
fl, _ := os.OpenFile("sticker.webp", os.O_CREATE|os.O_WRONLY, 0666)

//Gets the file info and downloads it.
_, err := bot.GetFile(fi, true, fl)
if err != nil {
    fmt.Println(err)
}
fl.Close()

Keyboards

In Telego you can create custom keyboards and inline keyboards easily with an amazing tool. Telegram has two types of keyboards :

  1. Custom keyboard : this type of keyboard will replace letter keyboard.
  2. Inline keyboard : this type of keyboard will be displayed below the message. (aka transparent keyboards)
Custom keyboards

You can create this type of keyboard by calling CreateKeyboard method of the bot. It has some arguments that are fully documented in the source code. Calling this method will return a keyboard which has several methods for adding buttons to it. After you have added the buttons you can pass the keyboard to a method that supports keyboards (for example : ASendMessage). Methods that support keyboards are located in the advanced bot. Example :

 import (
    "fmt"
    
	bt "github.com/SakoDroid/telego"
	cfg "github.com/SakoDroid/telego/configs"
	objs "github.com/SakoDroid/telego/objects"
 )

 func main(){
    up := cfg.DefaultUpdateConfigs()
    
    cf := cfg.BotConfigs{BotAPI: cfg.DefaultBotAPI, APIKey: "your api key", UpdateConfigs: up, Webhook: false, LogFileAddress: cfg.DefaultLogFile}

    bot, err := bt.NewBot(&cf)

    if err == nil{

        err == bot.Run()

        if err == nil{
            go start(bot)
        }
    }
 }

 func start(bot *bt.Bot){

     //The general update channel.
     updateChannel := bot.GetUpdateChannel()

    //Adding a handler. Everytime the bot receives message "hi" in a private chat, it will respond "hi to you too".
    bot.AddHandler("hi",func(u *objs.Update) {
        
        //Create the custom keyboard.
        kb := bot.CreateKeyboard(false,false,false,"type ...")

        //Add buttons to it. First argument is the button's text and the second one is the row number that the button will be added to it.
        kb.AddButton("button1",1)
        kb.AddButton("button2",1)
        kb.AddButton("button3",2)

        //Sends the message along with the keyboard.
		_, err := bot.AdvancedMode().ASendMessage(u.Message.Chat.Id, "hi to you too", "", u.Message.MessageId, false,false, nil, false, false, kb)
		if err != nil {
			fmt.Println(err)
		}
	},"private")

    //Monitores any other update. (Updates that don't contain text message "hi" in a private chat)
     for {
         update := <- updateChannel

        //Some processing on the update
     }
 }

The result of the above code will be like this :

custom keyboards

Inline keyboards

Inline keyboards appear below the message they have been sent with. To create inline keyboards call CreateInlineKeyboard() method of the bot. Calling this method will return an inline keyboard which has several methods for adding buttons to it. After buttons have been added you can pass the inline keyboard to a method that supports keyboards (for example : ASendMessage). Methods that support keyboards are located in the advanced bot. A special button is callback button. When this button is pressed a callback query is sent to the bot that contains a data (callback data). The callback data is set when you add a callback button. Also you can define a handler for the button which will be executed everytime this button is pressed. You can answer callback queries with AAsnwerCallbackQuery method of the advanced bot.

Example :

 import (
    "fmt"
    
	bt "github.com/SakoDroid/telego"
	cfg "github.com/SakoDroid/telego/configs"
	objs "github.com/SakoDroid/telego/objects"
 )

 func main(){
    up := cfg.DefaultUpdateConfigs()
    
    cf := cfg.BotConfigs{BotAPI: cfg.DefaultBotAPI, APIKey: "your api key", UpdateConfigs: up, Webhook: false, LogFileAddress: cfg.DefaultLogFile}

    bot, err := bt.NewBot(&cf)

    if err == nil{

        err == bot.Run()

        if err == nil{
            go start(bot)
        }
    }
 }

 func start(bot *bt.Bot){

     //The general update channel.
     updateChannel := bot.GetUpdateChannel()

    //Adding a handler. Everytime the bot receives message "hi" in a private chat, it will respond "hi to you too".
    bot.AddHandler("hi",func(u *objs.Update) {
        
        //Creates the inline keyboard
        kb := bot.CreateInlineKeyboard()

        //Adds a button that will open a url when pressed.
		kb.AddURLButton("url", "https://google.com", 1)

        //Adds a callback button with no handler
		kb.AddCallbackButton("call back without handler", "callback data 1", 2)

        //Adds a callback button with handler.
		kb.AddCallbackButtonHandler("callabck with handler", "callback data 2", 3, func(u *objs.Update) {
			_, err3 := bot.AdvancedMode().AAnswerCallbackQuery(u.CallbackQuery.Id, "callback received", true, "", 0)
			if err3 != nil {
				fmt.Println(err3)
			}
		})

        //Sends the message along with the keyboard.
		_, err := bot.AdvancedMode().ASendMessage(u.Message.Chat.Id, "hi to you too", "", u.Message.MessageId, false,false, nil, false, false, kb)
		if err != nil {
			fmt.Println(err)
		}
	},"private")

    //Monitores any other update. (Updates that don't contain text message "hi" in a private chat)
     for {
         update := <- updateChannel

        //Some processing on the update
     }
 }

The result of the above code will be like this :

inline key boards

Inline queries

First, if you don't know what inline queries are, check here. For your bot to receive inline queries you should enable this feature via BotFather. To enable this option, send the /setinline command to BotFather and provide the placeholder text that the user will see in the input field after typing your bot’s name.

After you have enabled this option, you can register a channel for inline queries by calling RegisterChannel("","inline_query") method of the advanced bot. Any received inline query will be passed into this channel.

To respond to an inline query you need to use AAnswerInlineQuery method of the advanced bot. Calling this method will return an InlineQueryResponder which you can use to add up to 50 results and then send it. There are 20 different types of inline query results so there is 20 methods for adding a result. All this methods (except AddGame) have an argument called message which is the message that will be sent when user clicks the result you are adding. There are a few methods in InlineQueryResponder that create this message and they all start with Create (like CreateTextMessage). This methods will return an InputMessageContent that can be passed as message argument of the Add methods.

Let's see an example code. The code below registers a channel for inline queries and regardless of their query, adds an article result. If this result is pressed, a text message is sent which will say telego is a go library for creating telegram bots.

import (
    "fmt"
    
	bt "github.com/SakoDroid/telego"
	cfg "github.com/SakoDroid/telego/configs"
	objs "github.com/SakoDroid/telego/objects"
)

func main(){
    up := cfg.DefaultUpdateConfigs()
    
    cf := cfg.BotConfigs{BotAPI: cfg.DefaultBotAPI, APIKey: "your api key", UpdateConfigs: up, Webhook: false, LogFileAddress: cfg.DefaultLogFile}

    bot, err := bt.NewBot(&cf)

    if err == nil{

        err == bot.Run()

        if err == nil{
            go start(bot)
        }
    }
}

func start(bot *bt.Bot){

    //The general update channel.
    updateChannel := bot.GetUpdateChannel()

    //The inline query channel
    inlineQueryChannel, _ := bot.AdvancedMode().RegisterChannel("","inline_query")

    for {
        select {

        case up := <-*updateChannel:
            //Processing received updates other than inline queries.

        case in := <-*inlineQueryChannel:

            //Prints the query
            fmt.Println("inline query :", in.InlineQuery.Query)

            //Create an inline query responder
            iqs := bot.AdvancedMode().AAnswerInlineQuery(in.InlineQuery.Id, 0, false, "", "", "")

            //Create a text message
            message := iqs.CreateTextMessage(
                "telego is a go library for creating telegram bots",
                "",
                nil,
                false,
            )

            //Add an article
            iqs.AddArticle("12345", "telego library", "https://github.com/SakoDroid/telego", "", "", 0, 0, false, message, nil)

            //Send the results
            _, err := iqs.Send()

            if err != nil {
                fmt.Println(err)
            }
        }
    }
}

This is how this code looks like in telegram ( "type test" that is seen in the input field can be set using BotFather ) :

inline query results

And when this result is clicked, the message in the photo below is sent :

Sent message

Stickers

To create stickers first you need to create an sticker set. An sticker set should have an owner, a name, a title and a sticker to begin with. According to telegram bot API,"name" is the short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_bot username”. <bot_username> is case insensitive. 1-64 characters. To create an sticker set, CreateStickerSet method should be called. Pass the userId of the owner,name,title and the information of the first sticker of the set to this method to create the sticker set. Calling this method wil return an sticker set which has some methods for adding new stickers to it and managing the pack such as AddPngSticker,AddAnimatedSticker and AddVideoSticker. Example :

fl1, err := os.Open("Sticker1.png")
if err != nil {
    fmt.Println(err)
}

fl2, err := os.Open("Sticker2.png")
if err != nil {
    fmt.Println(err)
}

//Create the sticker set
st, er := bot.CreateNewStickerSet("owner_user_id", "stickerset_by_TestBot", "stickersettest", "", fl1, nil, "✌", false, nil)
if er != nil {
    fmt.Println(er, st)
}

//Add a new sticker to the set
_, _ = st.AddPngStickerByFile(fl2, "✌", nil)
ms := bot.SendSticker(msg.Message.Chat.Id, msg.Message.MessageId)
_, err = ms.SendByFileIdOrUrl(st.GetStickers()[0].FileId, false, false)
if err != nil {
    fmt.Println(err)
}
Blocking users

Telego gives you the ability to block a user. You can also implement a mechanism to block the user more customized or you can use builtin blocking option. To block a user you can simply call Block method of the bot and pass the User object to the method. When a user is blocked, received updates from the user will be ignored.


License

telego is licensed under MIT lisence. Which means it can be used for commercial and private apps and can be modified.


Chnage logs

v1.7.0
  • Added config updating option while bot is running.
  • Added block option.
  • Added VerifyJoin method for checking if a user has joined a channel or supergroup or not.
  • Added file based configs.
  • Improved logging system.
  • Improved documentation
v1.6.7
  • Added support for telegram bot API 5.7
  • Improved sticker creation experience by adding new separate methods.
  • Correct syntax errors by @ityulkanov
  • Bug fixes
v1.5.7
  • Bug fixes
v1.5.5
  • Added webhook support
  • Improved handlers and regex bug fixed.
  • Some other bug fixes.
v1.4.5
  • Added TextFormatter tool for formatting texts.
  • Bug fixes
v1.3.5
  • Added support for telegram bot API 5.6 .
  • Improved documentation.
v1.3.4
  • Custom keyboard button handler
  • Major bug fixes
v1.3.3
  • Callback handlers
  • keyboard creation tool

telego logo inspired by Golang logo

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Polls = make(map[string]*Poll)

Polls contains the pointers to all of the created maps.

Functions

This section is empty.

Types

type AdvancedBot

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

AdvancedBot is an advanced type of bot which will give you alot more customization for the bot. Methods which are uniquely for advanced bot start with 'A' .

func (*AdvancedBot) AAnswerCallbackQuery

func (bot *AdvancedBot) AAnswerCallbackQuery(callbackQueryId, text string, showAlert bool, url string, cacheTime int) (*objs.LogicalResult, error)

AAnswerCallbackQuery can be used to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.

Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.

func (*AdvancedBot) AAnswerInlineQuery

func (bot *AdvancedBot) AAnswerInlineQuery(id string, cacheTime int, isPersonal bool, nextOffset, switchPmText, switchPmParameter string) *InlineQueryResponder

AAnswerInlineQuery returns an InlineQueryResponder which has several methods for answering an inline query.

--------------------------

Official telegram doc :

Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed.

func (*AdvancedBot) ACopyMessage

func (bot *AdvancedBot) ACopyMessage(messageId int, disableNotif bool, replyTo int, caption, parseMode string, captionEntites []objs.MessageEntity, allowSendingWithoutReply bool, keyboard MarkUps) *MessageCopier

ACopyMessage returns a MessageCopier which has several methods for copying a message

func (*AdvancedBot) ACreateAlbum

func (bot *AdvancedBot) ACreateAlbum(replyTo int, allowSendingWihtoutReply bool, keyboard MarkUps) *MediaGroup

ACreateAlbum creates a MediaGroup for grouping media messages. To ignore replyTo argument, pass 0.

func (*AdvancedBot) ACreateInvoice

func (bot *AdvancedBot) ACreateInvoice(chatId int, title, description, payload, providerToken, currency string, prices []objs.LabeledPrice, maxTipAmount int, suggestedTipAmounts []int, startParameter, providerData, photoURL string, photoSize, photoWidth, photoHeight int, needName, needPhoneNumber, needEmail, needSippingAddress, sendPhoneNumberToProvider, sendEmailToProvider, isFlexible, bool, allowSendingWithoutReply bool, keyboard *inlineKeyboard) *Invoice

ACreateInvoice returns an InvoiceSender which has several methods for creating and sending an invoice.

This method is suitable for sending this invoice to a chat that has an id, to send the invoice to channels use "ACreateInvoiceUN" method.

func (*AdvancedBot) ACreateInvoiceUN

func (bot *AdvancedBot) ACreateInvoiceUN(chatId string, title, description, payload, providerToken, currency string, prices []objs.LabeledPrice, maxTipAmount int, suggestedTipAmounts []int, startParameter, providerData, photoURL string, photoSize, photoWidth, photoHeight int, needName, needPhoneNumber, needEmail, needSippingAddress, sendPhoneNumberToProvider, sendEmailToProvider, isFlexible, bool, allowSendingWithoutReply bool, keyboard *inlineKeyboard) *Invoice

ACreateInvoiceUN returns an InvoiceSender which has several methods for creating and sending an invoice.

func (*AdvancedBot) ACreateLiveLocation

func (bot *AdvancedBot) ACreateLiveLocation(latitude, longitude, accuracy float32, livePeriod, heading, proximtyAlertRadius, replyTo int, allowSendingWihtoutReply bool, keyboard MarkUps) *LiveLocation

ACreateLiveLocation creates a live location which has several methods for managing it.

func (*AdvancedBot) ASendAnimation

func (bot *AdvancedBot) ASendAnimation(chatId int, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, width, height, duration int, allowSendingWihtoutReply bool, keyboard MarkUps) *MediaSender

ASendAnimation returns a MediaSender which has several methods for sending an animation. This method is only used for sending an animation to all types of chat except channels. To send a audio to a channel use "SendAnimationUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASendAnimationUN

func (bot *AdvancedBot) ASendAnimationUN(chatId string, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, width, height, duration int, allowSendingWihtoutReply bool, keyboard MarkUps) *MediaSender

ASendAnimationUN returns a MediaSender which has several methods for sending an animation. This method is only used for sending an animation to channels To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASendAudio

func (bot *AdvancedBot) ASendAudio(chatId, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, duration int, performer, title string, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendAudio returns a MediaSender which has several methods for sending a audio. This method is only used for sending a audio to all types of chat except channels. To send a audio to a channel use "SendAudioUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.

For sending voice messages, use the sendVoice method instead.

func (*AdvancedBot) ASendAudioUN

func (bot *AdvancedBot) ASendAudioUN(chatId string, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, duration int, performer, title string, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendAudioUN returns a MediaSender which has several methods for sending a audio. This method is only used for sending a audio to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.

For sending voice messages, use the sendVoice method instead.

func (*AdvancedBot) ASendContact

func (bot *AdvancedBot) ASendContact(chatId, replyTo int, phoneNumber, firstName, lastName, vCard string, silent, protectContent bool, allowSendingWihtoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendContact sends a contact to all types of chat but channels. To send it to channels use "SendContactUN" method.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send phone contacts. On success, the sent Message is returned.

func (*AdvancedBot) ASendContactUN

func (bot *AdvancedBot) ASendContactUN(chatId string, replyTo int, phoneNumber, firstName, lastName, vCard string, silent, protectContent bool, allowSendingWihtoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendContactUN sends a contact to a channel.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send phone contacts. On success, the sent Message is returned.

func (*AdvancedBot) ASendDice

func (bot *AdvancedBot) ASendDice(chatId, replyTo int, emoji string, silent, protectContent bool, allowSendingWihtoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendDice sends a dice message to all types of chat but channels. To send it to channels use "SendDiceUN" method.

Available emojies : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned

func (*AdvancedBot) ASendDiceUN

func (bot *AdvancedBot) ASendDiceUN(chatId string, replyTo int, emoji string, silent, protectContent bool, allowSendingWihtoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendDiceUN sends a dice message to a channel.

Available emojies : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned

func (*AdvancedBot) ASendDocument

func (bot *AdvancedBot) ASendDocument(chatId, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, disableContentTypeDetection, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendDocument returns a MediaSender which has several methods for sending a document. This method is only used for sending a document to all types of chat except channels. To send a audio to a channel use "SendDocumentUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASendDocumentUN

func (bot *AdvancedBot) ASendDocumentUN(chatId string, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, disableContentTypeDetection, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendDocumentUN returns a MediaSender which has several methods for sending a document. This method is only used for sending a document to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASendGame

func (bot *AdvancedBot) ASendGame(chatId int, gameShortName string, silent bool, replyTo int, allowSendingWithoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendGame sends a game to the chat.

-----------------------

Official telegram doc :

Use this method to send a game. On success, the sent Message is returned.

func (*AdvancedBot) ASendLocation

func (bot *AdvancedBot) ASendLocation(chatId int, silent, protectContent bool, latitude, longitude, accuracy float32, replyTo int, allowSendingWihtoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendLocation sends a location (not live) to all types of chats but channels. To send it to channel use "SendLocationUN" method.

You can not use this methods to send a live location. To send a live location use "ACreateLiveLocation" method.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send point on the map. On success, the sent Message is returned.

func (*AdvancedBot) ASendLocationUN

func (bot *AdvancedBot) ASendLocationUN(chatId string, silent, protectContent bool, latitude, longitude, accuracy float32, replyTo int, allowSendingWihtoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendLocationUN sends a location (not live) to a channel.

You can not use this methods to send a live location. To send a live location use "ACreateLiveLocation" method.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send point on the map. On success, the sent Message is returned.

func (*AdvancedBot) ASendMessage

func (bot *AdvancedBot) ASendMessage(chatId int, text, parseMode string, replyTo int, silent, protectContent bool, entites []objs.MessageEntity, disabelWebPagePreview, allowSendingWithoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendMessage sends a text message to a chat (not channel, use SendMessageUN method for sending messages to channles) and returns the sent message on success If you want to ignore "parseMode" pass empty string. To ignore replyTo pass 0.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*AdvancedBot) ASendMesssageUN

func (bot *AdvancedBot) ASendMesssageUN(chatId, text, parseMode string, replyTo int, silent, protectContent bool, entites []objs.MessageEntity, disabelWebPagePreview, allowSendingWithoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendMesssageUN sends a text message to a channel and returns the sent message on success If you want to ignore "parseMode" pass empty string. To ignore replyTo pass 0.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*AdvancedBot) ASendPhoto

func (bot *AdvancedBot) ASendPhoto(chatId, replyTo int, caption, parseMode string, captionEntites []objs.MessageEntity, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendPhoto returns a MediaSender which has several methods for sending a photo. This method is only used for sending a photo to all types of chat except channels. To send a photo to a channel use "SendPhotoUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

func (*AdvancedBot) ASendPhotoUN

func (bot *AdvancedBot) ASendPhotoUN(chatId string, replyTo int, caption, parseMode string, captionEntites []objs.MessageEntity, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendPhotoUN returns a MediaSender which has several methods for sending a photo. This method is only used for sending a photo to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

func (*AdvancedBot) ASendVenue

func (bot *AdvancedBot) ASendVenue(chatId, replyTo int, latitude, longitude float32, title, address, foursquareId, foursquareType, googlePlaceId, googlePlaceType string, silent bool, allowSendingWihtoutReply, protectContent bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendVenue sends a venue to all types of chat but channels. To send it to channels use "SendVenueUN" method.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send information about a venue. On success, the sent Message is returned.

func (*AdvancedBot) ASendVenueUN added in v1.7.0

func (bot *AdvancedBot) ASendVenueUN(chatId string, replyTo int, latitude, longitude float32, title, address, foursquareId, foursquareType, googlePlaceId, googlePlaceType string, silent, protectContent bool, allowSendingWihtoutReply bool, keyboard MarkUps) (*objs.SendMethodsResult, error)

ASendVenueUN sends a venue to a channel.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

---------------------------------

Official telegram doc :

Use this method to send information about a venue. On success, the sent Message is returned.

func (*AdvancedBot) ASendVideo

func (bot *AdvancedBot) ASendVideo(chatId int, replyTo int, caption, parseMode string, captionEntites []objs.MessageEntity, duration int, supportsStreaming, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendVideo returns a MediaSender which has several methods for sending a video. This method is only used for sending a video to all types of chat except channels. To send a video to a channel use "SendVideoUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASendVideoNote

func (bot *AdvancedBot) ASendVideoNote(chatId int, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, length, duration int, allowSendingWihtoutReply bool, keyboard MarkUps) *MediaSender

ASendVideoNote returns a MediaSender which has several methods for sending a video note. This method is only used for sending a video note to all types of chat except channels. To send a video note to a channel use "SendVideoNoteUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.

func (*AdvancedBot) ASendVideoNoteUN

func (bot *AdvancedBot) ASendVideoNoteUN(chatId string, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, length, duration int, allowSendingWihtoutReply bool, keyboard MarkUps) *MediaSender

ASendVideoNoteUN returns an MediaSender which has several methods for sending a video note. This method is only used for sending a video note to channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.

func (*AdvancedBot) ASendVideoUN

func (bot *AdvancedBot) ASendVideoUN(chatId string, replyTo int, caption, parseMode string, captionEntites []objs.MessageEntity, duration int, supportsStreaming, allowSendingWithoutReply bool, keyboard MarkUps) *MediaSender

ASendVideoUN returns a MediaSender which has several methods for sending a video. This method is only used for sending a video to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASendVoice

func (bot *AdvancedBot) ASendVoice(chatId int, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, duration int, allowSendingWihtoutReply bool, keyboard MarkUps) *MediaSender

ASendVoice returns a MediaSender which has several methods for sending a voice. This method is only used for sending a voice to all types of chat except channels. To send a voice to a channel use "SendVoiceUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASendVoiceUN

func (bot *AdvancedBot) ASendVoiceUN(chatId string, replyTo int, caption, parseMode string, captionEntities []objs.MessageEntity, duration int, allowSendingWihtoutReply bool, keyboard MarkUps) *MediaSender

ASendVoiceUN returns a MediaSender which has several methods for sending a voice. This method is only used for sending a voice to channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

func (*AdvancedBot) ASetGameScore

func (bot *AdvancedBot) ASetGameScore(userId, score, chatId, messageId int, force, disableEditMessage bool, inlineMessageId string) (*objs.DefaultResult, error)

ASetGameScore sets the score of the given user.

-----------------------

Official telegram doc :

Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.

"score" is new score, must be non-negative.

"force" : Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters.

"disableEditMessage" : Pass True, if the game message should not be automatically edited to include the current scoreboard.

"inlineMessageId" : Required if chat_id and message_id are not specified. Identifier of the inline message.

func (*AdvancedBot) GetMyDefaultAdministratorRights added in v1.8.0

func (bot *AdvancedBot) GetMyDefaultAdministratorRights(forChannels bool) (*objs.ChatAdministratorRightsResult, error)

GetMyDefaultAdministratorRights as describe by telegram official doc : Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.

func (*AdvancedBot) RegisterChannel

func (bot *AdvancedBot) RegisterChannel(chatId, mediaType string) (*chan *objs.Update, error)

RegisterChannel can be used to register special channels. Sepcial channels can be used to get only certain types of updates through them. For example you can register a channel to only receive messages or register a channel to only receive edited messages in a certain chat.

"chatId" argument specifies a chat which this channel will be dedicated to. If an empty string is passed it means that no chat is specified and channel will work for all chats. chatIds that are integer should be converted to string.

"mediaType" argument specifies a media type that channel will be dedicated to. If an empty string is passed it means no media type is in mind and channel will work for all media types. mediaType can have the following values :

1. Empty string

2. message

3. edited_message

4. channel_post

5. edited_channel_post

6. inline_query

7. chosen_inline_query

8. callback_query

9. shipping_query

10. pre_checkout_query

11. poll_answer

12. my_chat_member

13. chat_member

14. chat_join_request

bot "chatId" and "mediaType" arguments can be used together to create a channel that will be updated only if a certain type of update is received for a ceratin chat.

Examples :

1. RegisterChannel("123456","message") : The returned channel will be updated when a message (text,photo,video ...) is received from a chat with "123456" as it's chat id.

2. RegiterChannel("","message") : The returned channel will be updated everytime a message is received from any chat.

3. RegisterChannel("123456","") : The returned channel will be updated everytime an update of anykind is received for the specified chat.

4. RegisterChannel("","") : The returned is the global update channel which will be updated everytime an update is received. You can get this channel by calling `getUpdateChannel()` method too.

func (*AdvancedBot) SetMyDefaultAdministratorRights added in v1.8.0

func (bot *AdvancedBot) SetMyDefaultAdministratorRights(forChannels, isAnonymous, canManageChat, canPostmessages, canEditMessages, canDeleteMessages, canManageVideoChats, canRestrictMembers, canPromoteMembers, canChangeInfo, canInviteUsers, canPinMessages bool) (*objs.LogicalResult, error)

SetMyDefaultAdministratorRights as describe by telegram official doc : Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.

func (*AdvancedBot) SetPassportDataErrors

func (bot *AdvancedBot) SetPassportDataErrors(userId int, errors []objs.PassportElementError) (*objs.LogicalResult, error)

SetPassportDataErrors informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.

Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.

func (*AdvancedBot) UnRegisterChannel

func (bot *AdvancedBot) UnRegisterChannel(chatId, mediaType string)

UnRegisterChannel can be used to unregister a channel for the given arguments

type AnimationEditor

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

AnimationEditor is a tool for editing animations.

func (*AnimationEditor) EditByFile

func (ai *AnimationEditor) EditByFile(file *os.File) (*objs.DefaultResult, error)

EditByFile edits this animation by file in the device

func (*AnimationEditor) EditByFileIdOrURL

func (ai *AnimationEditor) EditByFileIdOrURL(fileIdOrUrl string) (*objs.DefaultResult, error)

EditByFileIdOrURL edits this animation file by file id or url

type AnimationInserter

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

AnimationInserter is a tool for inserting animations into the MediaGroup.

func (*AnimationInserter) AddByFile

func (ai *AnimationInserter) AddByFile(file *os.File) error

AddByFile adds an existing file in the device

func (*AnimationInserter) AddByFileIdOrURL

func (ai *AnimationInserter) AddByFileIdOrURL(fileIdOrUrl string)

AddByFileIdOrURL adds this file by file id or url

func (*AnimationInserter) EditThumbnail

func (ai *AnimationInserter) EditThumbnail(fileIdOrURL string)

EditThumbnail edits the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*AnimationInserter) EditThumbnailFile

func (ai *AnimationInserter) EditThumbnailFile(file *os.File) error

EditThumbnailFile edits the thumbnail of the file. It takes a file existing on the device

func (*AnimationInserter) SetThumbnail

func (ai *AnimationInserter) SetThumbnail(fileIdOrURL string)

SetThumbnail sets the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*AnimationInserter) SetThumbnailFile

func (ai *AnimationInserter) SetThumbnailFile(file *os.File) error

SetThumbnailFile sets the tumbnail of the file. It takes a file existing on the device

type AudioEditor

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

AudioEditor is a tool for editing audios.

func (*AudioEditor) EditByFile

func (ai *AudioEditor) EditByFile(file *os.File) (*objs.DefaultResult, error)

EditByFile edits this audio by file in the device

func (*AudioEditor) EditByFileIdOrURL

func (ai *AudioEditor) EditByFileIdOrURL(fileIdOrUrl string) (*objs.DefaultResult, error)

EditByFileIdOrURL edits this file by file id or url

func (*AudioEditor) EditThumbnail

func (ai *AudioEditor) EditThumbnail(fileIdOrURL string)

EditThumbnail edits the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*AudioEditor) EditThumbnailFile

func (ai *AudioEditor) EditThumbnailFile(file *os.File) error

EditThumbnailFile edits the thumbnail of the file. It takes a file existing on the device

type AudioInserter

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

AudioInserter is a tool for inserting audios into the MediaGroup.

func (*AudioInserter) AddByFile

func (ai *AudioInserter) AddByFile(file *os.File) error

AddByFile adds an existing file in the device

func (*AudioInserter) AddByFileIdOrURL

func (ai *AudioInserter) AddByFileIdOrURL(fileIdOrUrl string)

AddByFileIdOrURL adds this file by file id or url

func (*AudioInserter) SetThumbnail

func (ai *AudioInserter) SetThumbnail(fileIdOrURL string)

SetThumbnail sets the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*AudioInserter) SetThumbnailFile

func (ai *AudioInserter) SetThumbnailFile(file *os.File) error

SetThumbnailFile sets the tumbnail of the file. It takes a file existing on the device

type Bot

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

func NewBot

func NewBot(cfg *cfg.BotConfigs) (*Bot, error)

NewBot returns a new bot instance with the specified configs

func (*Bot) AddHandler

func (bot *Bot) AddHandler(pattern string, handler func(*objs.Update), chatTypes ...string) error

AddHandler adds a handler for a text message that matches the given regex pattern and chatType.

"pattern" is a regex pattern.

"chatType" must be "private","group","supergroup","channel" or "all". Any other value will cause the function to return an error.

func (*Bot) AdvancedMode

func (bot *Bot) AdvancedMode() *AdvancedBot

AdvancedMode returns and advanced version of the bot which gives more customized functions to iteract with the bot

func (*Bot) AnswerCallbackQuery

func (bot *Bot) AnswerCallbackQuery(callbackQueryId, text string, showAlert bool) (*objs.LogicalResult, error)

AnswerCallbackQuery can be used to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.

Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.

func (*Bot) AnswerInlineQuery

func (bot *Bot) AnswerInlineQuery(id string, cacheTime int) *InlineQueryResponder

AnswerInlineQuery returns an InlineQueryResponder which has several methods for answering an inline query or web app query. To access more options use "AAsnwerInlineQuery" method in advanced bot.

--------------------------

Official telegram doc :

Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed.

func (*Bot) AnswerPreCheckoutQuery

func (bot *Bot) AnswerPreCheckoutQuery(shippingQueryId string, ok bool, errorMessage string) (*objs.LogicalResult, error)

AnswerPreCheckoutQuery answers a pre checkout query.

-----------------------

Official telegram doc :

Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.

"ok" : Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.

"errorMessage" : Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.

func (*Bot) AnswerShippingQuery

func (bot *Bot) AnswerShippingQuery(shippingQueryId string, ok bool, shippingOptions []objs.ShippingOption, errorMessage string) (*objs.LogicalResult, error)

AnswerShippingQuery answers an incoming shipping query.

-----------------------

Official telegram doc :

If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.

"ok" : Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible).

"shippingOptions" : Required if ok is True. A JSON-serialized array of available shipping options.

"errorMessage" : Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.

func (*Bot) AnswerWebAppQuery added in v1.8.0

func (bot *Bot) AnswerWebAppQuery(webAppQueryId string) *InlineQueryResponder

AnswerWebAppQuery returns an InlineQueryResponder which has several methods for answering an inline query or web app query.

--------------------------

Official telegram doc :

Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.

func (*Bot) BlockUser added in v1.7.0

func (bot *Bot) BlockUser(user *objs.User)

BlockUser blocks a user based on their ID and username.

func (*Bot) CopyMessage

func (bot *Bot) CopyMessage(messageId int, disableNotif, protectContent bool) *MessageCopier

CopyMessage returns a MessageCopier which has several methods for copying a message

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) CreateAlbum

func (bot *Bot) CreateAlbum(replyTo int) *MediaGroup

CreateAlbum returns a MediaGroup for grouping media messages. To ignore replyTo argument, pass 0.

func (*Bot) CreateInlineKeyboard added in v1.3.3

func (bot *Bot) CreateInlineKeyboard() *inlineKeyboard

CreateInlineKeyboard creates a keyboard an returns it. The created keyboard has some methods for adding buttons to it.

You can send the keyboard along with messages by passing the keyboard as the "keyboard" argument of a method. The methods that supoort keyboard are mostly located in the advanced mode.

func (*Bot) CreateInvoice

func (bot *Bot) CreateInvoice(chatId int, title, description, payload, providerToken, currency string) *Invoice

CreateInvoice returns an InvoiceSender which has several methods for creating and sending an invoice.

This method is suitable for sending this invoice to a chat that has an id, to send the invoice to channels use "CreateInvoiceUN" method.

To access more options, use "ACreateInvoice" method in advanced mode.

func (*Bot) CreateInvoiceUN

func (bot *Bot) CreateInvoiceUN(chatId, title, description, payload, providerToken, currency string) *Invoice

CreateInvoiceUN returns an InvoiceSender which has several methods for creating and sending an invoice.

To access more options, use "ACreateInvoiceUN" method in advanced mode.

func (*Bot) CreateKeyboard added in v1.3.3

func (bot *Bot) CreateKeyboard(resizeKeyboard, oneTimeKeyboard, selective bool, inputFieldPlaceholder string) *keyboard

CreateKeyboard creates a keyboard an returns it. The created keyboard has some methods for adding buttons to it.

You can send the keyboard along with messages by passing the keyboard as the "keyboard" argument of the method. The methods that supoort keyboard are mostly located in the advanced mode.

Arguments (as described in telegram bot api):

1. resizeKeyboard : Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.

2. oneTimeKeyboard : Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat – the user can press a special button in the input field to see the custom keyboard again. Defaults to false

3. inputFieldPlaceholder : The placeholder to be shown in the input field when the keyboard is active; 1-64 characters.

4. selective : Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.

Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard.

func (*Bot) CreateNewStickerSet

func (bot *Bot) CreateNewStickerSet(userId int, name, title, pngStickerFileIdOrUrl string, pngStickerFile *os.File, tgsSticker *os.File, webmSticker *os.File, emojies string, containsMask bool, maskPosition *objs.MaskPosition) (*StickerSet, error)

CreateNewStickerSet can be used to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields pngSticker or tgsSticker or webmSticker. Returns the created sticker set on success.

png sticker can be passed as an file id or url (pngStickerFileIdOrUrl) or file(pngStickerFile).

"name" is the short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters.

func (*Bot) CreatePoll

func (bot *Bot) CreatePoll(chatId int, question, pollType string) (*Poll, error)

CreatePoll creates a poll for all types of chat but channels. To create a poll for channels use "CreatePollForChannel" method.

The poll type can be "regular" or "quiz"

func (*Bot) CreatePollForChannel

func (bot *Bot) CreatePollForChannel(chatId, question, pollType string) (*Poll, error)

CreatePollForChannel creates a poll for a channel.

The poll type can be "regular" or "quiz"

func (*Bot) ForwardMessage

func (bot *Bot) ForwardMessage(messageId int, disableNotif, protectContent bool) *MessageForwarder

ForwardMessage returns a MessageForwarder which has several methods for forwarding a message

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) GetChatManagerById

func (bot *Bot) GetChatManagerById(chatId int) *ChatManager

GetChatManagerById creates and returns a ChatManager for groups and other chats witch an integer id.

To manage supergroups and channels which have usernames use "GetChatManagerByUsername".

func (*Bot) GetChatManagerByUsrename

func (bot *Bot) GetChatManagerByUsrename(userName string) *ChatManager

GetChatManagerByUsrename creates and returns a ChatManager for supergroups and channels which have usernames

To manage groups and other chats witch an integer id use "GetChatManagerById".

func (*Bot) GetChatMenuButton added in v1.8.0

func (bot *Bot) GetChatMenuButton(chatId int64) (*objs.MenuButtonResult, error)

GetChatMenuButton gets the current menu button of given chat.

-------------------------

Official telegram doc :

Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.

func (*Bot) GetCommandManager

func (bot *Bot) GetCommandManager() *CommandsManager

GetCommandManager returns a command manager which has several method for manaing bot commands.

func (*Bot) GetFile

func (bot *Bot) GetFile(fileId string, download bool, file *os.File) (*objs.File, error)

GetFile gets a file from telegram server. If it is successful the File object is returned.

If "download option is true, the file will be saved into the given file and if the given file is nil file will be saved in the same name as it has been saved in telegram servers.

func (*Bot) GetGameHighScores

func (bot *Bot) GetGameHighScores(userId, chatId, messageId int, inlineMessageId string) (*objs.GameHighScoresResult, error)

GetGameHighScores returns the high scores of the user.

-------------------------

Official telegram doc :

Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. On success, returns an Array of GameHighScore objects.

This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.

"chatId" : Required if inline_message_id is not specified. Unique identifier for the target chat.

"messageId" : Required if inline_message_id is not specified. Identifier of the sent message.

"inlineMessageId" : Required if chat_id and message_id are not specified. Identifier of the inline message.

func (*Bot) GetMe

func (bot *Bot) GetMe() (*objs.UserResult, error)

GetMe returns the received informations about the bot from api server.

---------------------

Official telegarm doc :

A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.

func (*Bot) GetMsgEditor

func (bot *Bot) GetMsgEditor(chatId int) *MessageEditor

GetMsgEditor returns a MessageEditor for a chat with id which has several methods for editing messages.

To edit messages in a channel or a chat with username, use "GetMsgEditorWithUN"

func (*Bot) GetMsgEditorWithUN

func (bot *Bot) GetMsgEditorWithUN(chatId string) *MessageEditor

GetMsgEditorWithUN returns a MessageEditor for a chat with username which has several methods for editing messages.

func (*Bot) GetStickerSet

func (bot *Bot) GetStickerSet(name string) (*StickerSet, error)

GetStickerSet returns an sticker set with the given name

func (*Bot) GetTextFormatter added in v1.4.5

func (bot *Bot) GetTextFormatter() *TextFormatter

GetTextFormatter returns a MessageFormatter that can be used for formatting a text message. You can add bold,italic,underline,spoiler,mention,url,link and some other texts with this tool.

func (*Bot) GetUpdateChannel

func (bot *Bot) GetUpdateChannel() *chan *objs.Update

GetUpdateChannel returns the channel which new updates received from api server are pushed into.

func (*Bot) GetUserProfilePhotos

func (bot *Bot) GetUserProfilePhotos(userId, offset, limit int) (*objs.ProfilePhototsResult, error)

GetUserProfilePhotos gets the given user profile photos.

"userId" argument is required. Other arguments are optinoal and to ignore them pass 0.

---------------------------------

Official telegram doc :

Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.

func (*Bot) Run

func (bot *Bot) Run() error

Run starts the bot. If the bot has already been started it returns an error.

func (*Bot) SendAnimation

func (bot *Bot) SendAnimation(chatId int, replyTo int, caption, parseMode string) *MediaSender

SendAnimation returns a MediaSender which has several methods for sending an animation. This method is only used for sending an animation to all types of chat except channels. To send a audio to a channel use "SendAnimationUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SendAnimationUN

func (bot *Bot) SendAnimationUN(chatId string, replyTo int, caption, parseMode string) *MediaSender

SendAnimationUN returns a MediaSender which has several methods for sending an animation. This method is only used for sending an animation to channels To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SendAudio

func (bot *Bot) SendAudio(chatId, replyTo int, caption, parseMode string) *MediaSender

SendAudio returns a MediaSender which has several methods for sending a audio. This method is only used for sending a audio to all types of chat except channels. To send a audio to a channel use "SendAudioUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.

For sending voice messages, use the sendVoice method instead.

func (*Bot) SendAudioUN

func (bot *Bot) SendAudioUN(chatId string, replyTo int, caption, parseMode string) *MediaSender

SendAudioUN returns a MediaSender which has several methods for sending a audio. This method is only used for sending a audio to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.

For sending voice messages, use the sendVoice method instead.

func (*Bot) SendChatAction

func (bot *Bot) SendChatAction(chatId int, action string) (*objs.SendMethodsResult, error)

SendChatAction sends a chat action message to all types of chat but channels. To send it to channels use "SendChatActionUN" method.

---------------------------------

Official telegram doc :

Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.

Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.

We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.

action is the type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.

func (*Bot) SendChatActionUN

func (bot *Bot) SendChatActionUN(chatId, action string) (*objs.SendMethodsResult, error)

SendChatActionUN sends a chat action message to a channel.

---------------------------------

Official telegram doc :

Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.

Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.

We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.

action is the type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.

func (*Bot) SendContact

func (bot *Bot) SendContact(chatId, replyTo int, phoneNumber, firstName, lastName string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendContact sends a contact to all types of chat but channels. To send it to channels use "SendContactUN" method.

---------------------------------

Official telegram doc :

Use this method to send phone contacts. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendContactUN

func (bot *Bot) SendContactUN(chatId string, replyTo int, phoneNumber, firstName, lastName string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendContactUN sends a contact to a channel.

---------------------------------

Official telegram doc :

Use this method to send phone contacts. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendDice

func (bot *Bot) SendDice(chatId, replyTo int, emoji string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendDice sends a dice message to all types of chat but channels. To send it to channels use "SendDiceUN" method.

Available emojies : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”.

---------------------------------

Official telegram doc :

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendDiceUN

func (bot *Bot) SendDiceUN(chatId string, replyTo int, emoji string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendDiceUN sends a dice message to a channel.

Available emojies : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”.

---------------------------------

Official telegram doc :

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendDocument

func (bot *Bot) SendDocument(chatId, replyTo int, caption, parseMode string) *MediaSender

SendDocument returns a MediaSender which has several methods for sending a document. This method is only used for sending a document to all types of chat except channels. To send a audio to a channel use "SendDocumentUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SendDocumentUN

func (bot *Bot) SendDocumentUN(chatId string, replyTo int, caption, parseMode string) *MediaSender

SendDocumentUN returns a MediaSender which has several methods for sending a document. This method is only used for sending a document to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SendGame

func (bot *Bot) SendGame(chatId int, gameShortName string, silent bool, replyTo int) (*objs.SendMethodsResult, error)

SendGame sends a game to the chat.

**To access more options use "ASendGame" method in advanced mode.

-----------------------

Official telegram doc :

Use this method to send a game. On success, the sent Message is returned.

func (*Bot) SendLocation

func (bot *Bot) SendLocation(chatId int, silent, protectContent bool, latitude, longitude, accuracy float32, replyTo int) (*objs.SendMethodsResult, error)

SendLocation sends a location (not live) to all types of chats but channels. To send it to channel use "SendLocationUN" method.

You can not use this methods to send a live location. To send a live location use AdvancedBot.

---------------------------------

Official telegram doc :

Use this method to send point on the map. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendLocationUN

func (bot *Bot) SendLocationUN(chatId string, silent, protectContent bool, latitude, longitude, accuracy float32, replyTo int) (*objs.SendMethodsResult, error)

SendLocationUN sends a location (not live) to a channel.

You can not use this methods to send a live location. To send a live location use AdvancedBot.

---------------------------------

Official telegram doc :

Use this method to send point on the map. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendMessage

func (bot *Bot) SendMessage(chatId int, text, parseMode string, replyTo int, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendMessage sens a text message to a chat (not channel, use SendMessageUN method for sending messages to channles) and returns the sent message on success If you want to ignore "parseMode" pass empty string. To ignore replyTo pass 0.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendMessageUN added in v1.7.0

func (bot *Bot) SendMessageUN(chatId, text, parseMode string, replyTo int, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendMesssageUN sens a text message to a channel and returns the sent message on success If you want to ignore "parseMode" pass empty string. To ignore replyTo pass 0.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendPhoto

func (bot *Bot) SendPhoto(chatId, replyTo int, caption, parseMode string) *MediaSender

SendPhoto returns a MediaSender which has several methods for sending a photo. This method is only used for sending a photo to all types of chat except channels. To send a photo to a channel use "SendPhotoUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

func (*Bot) SendPhotoUN

func (bot *Bot) SendPhotoUN(chatId string, replyTo int, caption, parseMode string) *MediaSender

SendPhotoUN returns a MediaSender which has several methods for sending a photo. This method is only used for sending a photo to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

func (*Bot) SendSticker

func (bot *Bot) SendSticker(chatId, replyTo int) *MediaSender

SendSticker returns a MediaSender which has several methods for sending an sticker to all types of chats but channels. To send it to a channel use "SendStickerWithUN".

--------------------

Official telegram doc :

Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned

func (*Bot) SendStickerWithUn

func (bot *Bot) SendStickerWithUn(chatId string, replyTo int) *MediaSender

SendStickerWithUn returns a MediaSender which has several methods for sending an sticker to channels.

--------------------

Official telegram doc :

Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned

func (*Bot) SendVenue

func (bot *Bot) SendVenue(chatId, replyTo int, latitude, longitude float32, title, address string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendVenue sends a venue to all types of chat but channels. To send it to channels use "SendVenueUN" method.

---------------------------------

Official telegram doc :

Use this method to send information about a venue. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendVenueUN

func (bot *Bot) SendVenueUN(chatId string, replyTo int, latitude, longitude float32, title, address string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendVenueUN sends a venue to a channel.

---------------------------------

Official telegram doc :

Use this method to send information about a venue. On success, the sent Message is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Bot) SendVideo

func (bot *Bot) SendVideo(chatId int, replyTo int, caption, parseMode string) *MediaSender

SendVideo returns a MediaSender which has several methods for sending a video. This method is only used for sending a video to all types of chat except channels. To send a video to a channel use "SendVideoUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SendVideoNote

func (bot *Bot) SendVideoNote(chatId int, replyTo int, caption, parseMode string) *MediaSender

SendVideoNote returns a MediaSender which has several methods for sending a video note. This method is only used for sending a video note to all types of chat except channels. To send a video note to a channel use "SendVideoNoteUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.

func (*Bot) SendVideoNoteUN

func (bot *Bot) SendVideoNoteUN(chatId string, replyTo int, caption, parseMode string) *MediaSender

SendVideoNoteUN returns an MediaSender which has several methods for sending a video note. This method is only used for sending a video note to channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.

func (*Bot) SendVideoUN

func (bot *Bot) SendVideoUN(chatId string, replyTo int, caption, parseMode string) *MediaSender

SendVideoUN returns a MediaSender which has several methods for sending a video. This method is only used for sending a video to a channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SendVoice

func (bot *Bot) SendVoice(chatId int, replyTo int, caption, parseMode string) *MediaSender

SendVoice returns a MediaSender which has several methods for sending a voice. This method is only used for sending a voice to all types of chat except channels. To send a voice to a channel use "SendVoiceUN" method. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SendVoiceUN

func (bot *Bot) SendVoiceUN(chatId string, replyTo int, caption, parseMode string) *MediaSender

SendVoiceUN returns an MediaSender which has several methods for sending a voice. This method is only used for sending a voice to channels. To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")

---------------------------------

Official telegram doc :

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

func (*Bot) SetCommandChatMenuButton added in v1.8.0

func (bot *Bot) SetCommandChatMenuButton(chatId int64) (*objs.LogicalResult, error)

SetCommandChatMenuButton sets the current menu button of given chat to command meaning that it opens the bot's list of commands.

-------------------------

Official telegram doc :

Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.

func (*Bot) SetDefaultChatMenuButton added in v1.8.0

func (bot *Bot) SetDefaultChatMenuButton(chatId int64) (*objs.LogicalResult, error)

SetDefaultChatMenuButton sets the current menu button of given chat to command meaning that it describes that no specific value for the menu button was set.

-------------------------

Official telegram doc :

Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.

func (*Bot) SetGameScore

func (bot *Bot) SetGameScore(userId, score, chatId, messageId int) (*objs.DefaultResult, error)

SetGameScore sets the score of the given user.

**To access more option use "ASetGameScoe" in advanced mode. -----------------------

Official telegram doc :

Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.

"score" is new score, must be non-negative.

func (*Bot) SetWebAppChatMenuButton added in v1.8.0

func (bot *Bot) SetWebAppChatMenuButton(chatId int64, text, url string) (*objs.LogicalResult, error)

SetWebAppChatMenuButton sets the current menu button of given chat to web_app meaning that it launches a Web App.

-------------------------

Official telegram doc :

Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.

func (*Bot) Stop

func (bot *Bot) Stop()

Stop stops the bot

func (*Bot) UploadStickerFile

func (bot *Bot) UploadStickerFile(userId int, stickerFile *os.File) (*objs.GetFileResult, error)

UploadStickerFile can be used to upload a .PNG file with a sticker for later use in CreateNewStickerSet and AddStickerToSet methods (can be used multiple times). Returns the uploaded File on success.

func (*Bot) VerifyJoin added in v1.7.0

func (bot *Bot) VerifyJoin(userID int, UserName string) bool

VerifyJoin verifies if the user has joined the given channel or supergroup. Returns true if the user is present in the given chat, returns false if not or an error has occured.

type ChatManager

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

ChatManager is a tool for managing chats via the bot.

func (*ChatManager) ApproveJoinRequest

func (cm *ChatManager) ApproveJoinRequest(userId int) (*objs.LogicalResult, error)

ApproveJoinRequest approves a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

func (*ChatManager) BanChatSender

func (cm *ChatManager) BanChatSender(senderChatId int) (*objs.LogicalResult, error)

BanChatSender bans a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.

func (*ChatManager) BanMember

func (cm *ChatManager) BanMember(userId, untilDate int, revokeMessages bool) (*objs.LogicalResult, error)

BanMember bans a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

func (cm *ChatManager) CreateInviteLink(name string, expireDate, memberLimit int, createsJoinRequest bool) (*objs.ChatInviteLinkResult, error)

CreateInviteLink creates an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method RevokeInviteLink. Returns the new invite link as ChatInviteLink object.

func (*ChatManager) DeclineJoinRequest

func (cm *ChatManager) DeclineJoinRequest(userId int) (*objs.LogicalResult, error)

DeclineJoinRequest can be used to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

func (*ChatManager) DeletePhoto

func (cm *ChatManager) DeletePhoto() (*objs.LogicalResult, error)

DeletePhoto can be used to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

func (*ChatManager) DeleteStickerSet

func (cm *ChatManager) DeleteStickerSet() (*objs.LogicalResult, error)

DeleteStickerSet deletes a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in "GetChatInfo" to check if the bot can use this method. Returns True on success.

func (cm *ChatManager) EditInviteLink(inviteLink, name string, expireDate, memberLimit int, createsJoinRequest bool) (*objs.ChatInviteLinkResult, error)

EditInviteLink edits a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.

func (cm *ChatManager) ExportInviteLink() (*objs.StringResult, error)

ExportInviteLink generates a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.

Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using this method or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use this method again.

func (*ChatManager) GetAdmins

func (cm *ChatManager) GetAdmins() (*objs.ChatAdministratorsResult, error)

GetAdmins gets a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.

func (*ChatManager) GetChatInfo

func (cm *ChatManager) GetChatInfo() (*objs.ChatResult, error)

GetChatInfo gets up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.

func (*ChatManager) GetMember

func (cm *ChatManager) GetMember(userid int) (string, error)

GetMember gets information about a member of a chat. Returns a json serialized object of the member in string form on success.

func (*ChatManager) GetMembersCount

func (cm *ChatManager) GetMembersCount() (*objs.IntResult, error)

GetMembersCount gets the number of members in a chat. Returns Int on success.

func (*ChatManager) Leave

func (cm *ChatManager) Leave() (*objs.LogicalResult, error)

Leave can be used for your bot to leave a group, supergroup or channel. Returns True on success.

func (*ChatManager) PinMessage

func (cm *ChatManager) PinMessage(messageId int, disableNotif bool) (*objs.LogicalResult, error)

PinMessage adds a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.

func (*ChatManager) PromoteChatMember

func (cm *ChatManager) PromoteChatMember(userId int, isAnonymous, canManageChat, canPostmessages, canEditMessages, canDeleteMessages, canManageVideoChats, canRestrictMembers, canPromoteMembers, canChangeInfo, canInviteUsers, canPinMessages bool) (*objs.LogicalResult, error)

PromoteChatMember promotes or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.

func (*ChatManager) RestrictMember

func (cm *ChatManager) RestrictMember(userId int, untilDate int, canSendMessages, canSendMediaMessages, canSendPolls, canSendOtherMessages, canAddWebPagePreviews, canChangeInfo, canInviteUsers, canPinMessages bool) (*objs.LogicalResult, error)

Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.

func (cm *ChatManager) RevokeInviteLink(inviteLink string) (*objs.ChatInviteLinkResult, error)

RevokeInviteLink revokes an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.

func (*ChatManager) SetCustomTitle

func (cm *ChatManager) SetCustomTitle(userId int, customTitle string) (*objs.LogicalResult, error)

SetCustomTitle sets a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.

func (*ChatManager) SetDescription

func (cm *ChatManager) SetDescription(description string) (*objs.LogicalResult, error)

SetDescription changes the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

func (*ChatManager) SetGeneralPermissions

func (cm *ChatManager) SetGeneralPermissions(canSendMessages, canSendMediaMessages, canSendPolls, canSendOtherMessages, canAddWebPagePreviews, canChangeInfo, canInviteUsers, canPinMessages bool) (*objs.LogicalResult, error)

SetGeneralPermissions sets default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.

func (*ChatManager) SetPhoto

func (cm *ChatManager) SetPhoto(photoFile *os.File) (*objs.LogicalResult, error)

SetPhoto can be used to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

func (*ChatManager) SetStickerSet

func (cm *ChatManager) SetStickerSet(stickerSetName string) (*objs.LogicalResult, error)

SetStickerSet sets a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in "GetChatInfo" to check if the bot can use this method. Returns True on success.

func (*ChatManager) SetTitle

func (cm *ChatManager) SetTitle(title string) (*objs.LogicalResult, error)

SetTitle changes the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

func (*ChatManager) UnbanChatSender

func (cm *ChatManager) UnbanChatSender(senderChatId int) (*objs.LogicalResult, error)

UnbanChatSender unbans a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.

func (*ChatManager) UnbanMember

func (cm *ChatManager) UnbanMember(userId int, onlyIfBanned bool) (*objs.LogicalResult, error)

UnbanMember ubans a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.

func (*ChatManager) UnpinAllMessages

func (cm *ChatManager) UnpinAllMessages() (*objs.LogicalResult, error)

UnpinAllMessages clears the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.

func (*ChatManager) UnpinMessage

func (cm *ChatManager) UnpinMessage(messageId int) (*objs.LogicalResult, error)

UnpinMessage removes a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.

type CommandsManager

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

CommandsManager is a tool for managing bot commands

func (*CommandsManager) AddCommand

func (cm *CommandsManager) AddCommand(command, description string) error

AddCommand adds a new command to the commands list.

At most 100 commands can be added.

func (*CommandsManager) DeleteCommands

func (cm *CommandsManager) DeleteCommands(languageCode string) (*objs.LogicalResult, error)

DeleteCommands can be used to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.

func (*CommandsManager) GetCommands

func (cm *CommandsManager) GetCommands(languageCode string) ([]objs.BotCommand, error)

GetCommands returns the commands of this bot.

func (*CommandsManager) SetCommands

func (cm *CommandsManager) SetCommands(languageCode string) (*objs.LogicalResult, error)

SetCommands calls the realted method on the api server and sets the added commansd with their specified scopes.

"languageCode" is a two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands

-------------------------

Official telegram doc :

Use this method to change the list of the bot's commands. See https://core.telegram.org/bots#commands for more details about bot commands. Returns True on success.

func (*CommandsManager) SetScope

func (cm *CommandsManager) SetScope(scope string, chatId []byte, userId int) error

SetScope sets the scope of this command manager.

Scope can have these values : "defaut","all_group_chats","all_private_chats","all_chat_administrators","chat","chat_administrator","chat_member". If scope is not valid error is returned.

type DocumentEditor

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

DocumentEditor is a tool for editing documents.

func (*DocumentEditor) EditByFile

func (di *DocumentEditor) EditByFile(file *os.File) (*objs.DefaultResult, error)

EditByFile edits this document by file in the device

func (*DocumentEditor) EditByFileIdOrURL

func (di *DocumentEditor) EditByFileIdOrURL(fileIdOrUrl string) (*objs.DefaultResult, error)

EditByFileIdOrURL edits this file by file id or url

func (*DocumentEditor) EditThumbnail

func (di *DocumentEditor) EditThumbnail(fileIdOrURL string)

EditThumbnail edits the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*DocumentEditor) EditThumbnailFile

func (di *DocumentEditor) EditThumbnailFile(file *os.File) error

EditThumbnailFile edits the thumbnail of the file. It takes a file existing on the device

type DocumentInserter

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

DocumentInserter is a tool for inserting documents into the MediaGroup.

func (*DocumentInserter) AddByFile

func (di *DocumentInserter) AddByFile(file *os.File) error

AddByFile adds an existing file in the device

func (*DocumentInserter) AddByFileIdOrURL

func (di *DocumentInserter) AddByFileIdOrURL(fileIdOrUrl string)

AddByFileIdOrURL adds this file by file id or url

func (*DocumentInserter) SetThumbnail

func (di *DocumentInserter) SetThumbnail(fileIdOrURL string)

SetThumbnail sets the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*DocumentInserter) SetThumbnailFile

func (di *DocumentInserter) SetThumbnailFile(file *os.File) error

SetThumbnailFile sets the tumbnail of the file. It takes a file existing on the device

type InlineQueryResponder

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

func (*InlineQueryResponder) AddArticle

func (iqs *InlineQueryResponder) AddArticle(id, title, url, description, thumbUrl string, thumbWidth, thumbHeight int, hideUrl bool, message objs.InputMessageContent, keyboard *inlineKeyboard) error

Adds an article to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing".You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddAudio

func (iqs *InlineQueryResponder) AddAudio(id, title, audioURL, caption, parseMode, performer string, audioDuration int, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds an audio to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the audio.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing".You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedAudio

func (iqs *InlineQueryResponder) AddCachedAudio(id, title, audioFileId, caption, parseMode string, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds an audio to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the audio.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedDocument

func (iqs *InlineQueryResponder) AddCachedDocument(id, title, documentFileId, description, caption, parseMode string, messsage objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a cached document to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use message field to send a message with the specified content instead of the file.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedGif

func (iqs *InlineQueryResponder) AddCachedGif(id, title, gifFileId, caption, parseMode string, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a cached gif to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use message field to send a message with specified content instead of the animation.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedMpeg4Gif

func (iqs *InlineQueryResponder) AddCachedMpeg4Gif(id, title, mpeg4FileId, caption, parseMode string, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a cached mpeg4 to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use message field to send a message with the specified content instead of the animation.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedPhoto

func (iqs *InlineQueryResponder) AddCachedPhoto(id, title, photoFileId, description, caption, parseMode string, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a cached photo to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use message field to send a message with the specified content instead of the photo.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedSticker

func (iqs *InlineQueryResponder) AddCachedSticker(id, stickerFileId string, message objs.InputMessageContent, keyboard *inlineKeyboard) error

Adds a cached mpeg4 to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the sticker.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedVideo

func (iqs *InlineQueryResponder) AddCachedVideo(id, title, videoFileId, caption, description, parseMode string, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a cached video to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use message field to send a message with the specified content instead of the video.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddCachedVoice

func (iqs *InlineQueryResponder) AddCachedVoice(id, title, voiceFileId, caption, parseMode string, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a voice to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the voice message.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddContact

func (iqs *InlineQueryResponder) AddContact(id, title, thumbUrl, phoneNumber, firstName, lastName, vCard string, thumbWidth, thumbHeight int, message objs.InputMessageContent, keyboard *inlineKeyboard) error

Adds a contact to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the contact.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddDocument

func (iqs *InlineQueryResponder) AddDocument(id, title, documentURL, mimeType, description, thumbUrl, caption, parseMode string, thumbWidth, thumbHeight int, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a document to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use message field to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddGame

func (iqs *InlineQueryResponder) AddGame(id, gameShortName string, keyboard *inlineKeyboard) error

Adds a game to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a game

func (*InlineQueryResponder) AddGif

func (iqs *InlineQueryResponder) AddGif(id, title, gifURL, caption, parseMode, thumbUrl, thumbMIMEType string, gifWidth, gifHeight, gifDuration int, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a gif to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing".You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddLocation

func (iqs *InlineQueryResponder) AddLocation(id, title, thumbUrl string, latitude, longitude, horizontalAccuracy float32, livePeriod, heading, proximityAlertRadius, thumbWidth, thumbHeight int, message objs.InputMessageContent, keyboard *inlineKeyboard) error

Adds a location to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the location.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddMpeg4Gif

func (iqs *InlineQueryResponder) AddMpeg4Gif(id, title, mpeg4URL, caption, parseMode, thumbUrl, thumbMIMEType string, mpeg4Width, mpeg4Height, mpeg4Duration int, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a mpeg4 to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing".You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddPhoto

func (iqs *InlineQueryResponder) AddPhoto(id, title, photoURL, description, caption, parseMode, thumbUrl string, photoWidth, photoHeight int, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a photo to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing".You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddVenue

func (iqs *InlineQueryResponder) AddVenue(id, title, thumbUrl string, latitude, longitude float32, address, foursquareId, foursquareType, googlePlaceId, googlePlaceType string, thumbWidth, thumbHeight int, message objs.InputMessageContent, keyboard *inlineKeyboard) error

Adds a venue to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the venue.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing". You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddVideo

func (iqs *InlineQueryResponder) AddVideo(id, title, videoURL, mimeType, caption, description, parseMode, thumbUrl string, videoWidth, videoHeight, videoDuration int, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a video to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.

If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using message field.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing".You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) AddVoice

func (iqs *InlineQueryResponder) AddVoice(id, title, voiceURL, caption, parseMode string, voiceDuration int, message objs.InputMessageContent, keyboard *inlineKeyboard, captionEntities []objs.MessageEntity) error

Adds a voice to the result. No more than 50 results are allowed. Also only one result is allowed for web app response.

Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use message field to send a message with the specified content instead of the the voice message.

"message" argument is the message that will be sent if this result is pressed. It is necessary and if it's not passed the API server will return "400 bad request, message_text is missing".You can use "Create***Message" method to create this messages.

func (*InlineQueryResponder) CreateContactMessage added in v1.3.5

func (iqs *InlineQueryResponder) CreateContactMessage(phoneNumber, firstName, lastName, vCard string) objs.InputMessageContent

Use this function to create a contact message to be passed as "message" argument in "Add" methods.

func (*InlineQueryResponder) CreateInvoiceMessage added in v1.3.5

func (iqs *InlineQueryResponder) CreateInvoiceMessage(invoice *Invoice) objs.InputMessageContent

Use this function to create an invoice message to be passed as "message" argument in "Add" methods.

func (*InlineQueryResponder) CreateLocationMessage added in v1.3.5

func (iqs *InlineQueryResponder) CreateLocationMessage(latitude, longitude, accuracy float32, liveperiod, heading, proximityAlertRadius int) objs.InputMessageContent

Use this function to create a location message to be passed as "message" argument in "Add" methods.

func (*InlineQueryResponder) CreateTextMessage added in v1.3.5

func (iqs *InlineQueryResponder) CreateTextMessage(text, parseMode string, entities []objs.MessageEntity, disabelWebPagePreview bool) objs.InputMessageContent

Use this function to create a text message to be passed as "message" argument in "Add" methods.

func (*InlineQueryResponder) CreateVenueMessage added in v1.3.5

func (iqs *InlineQueryResponder) CreateVenueMessage(latitude, longitude float32, title, address, foursquareId, foursquareType, googlePlaceId, googlePlaceType string) objs.InputMessageContent

Use this function to create a venue message to be passed as "message" argument in "Add" methods.

func (*InlineQueryResponder) Send

func (iqs *InlineQueryResponder) Send() (interface{}, error)

Sends this answer to the user. The returned result can have two types : LogicalResult or SentWebAppMessage.

type Invoice added in v1.3.5

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

Invoice is an invoice that can be modified and sent to the user.

func (*Invoice) AddPrice added in v1.3.5

func (is *Invoice) AddPrice(label string, amount int)

AddPrice adds a new price label to this invoice.

"amount" is the price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145.

func (is *Invoice) CreateLink() (*objs.StringResult, error)

CreateLink creates a link for the invoice and returnes the link.

-------------------------------

Official telegram doc :

Use this method to create a link for an invoice. Returns the created invoice link as String on success.

func (*Invoice) Send added in v1.3.5

func (is *Invoice) Send(replyTo int, silent bool) (*objs.SendMethodsResult, error)

Send sends this invoice.

-------------------------------

Official telegram doc :

Use this method to send invoices. On success, the sent Message is returned.

type LiveLocation

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

LiveLocation is a live location that can be sent to a user.

func (*LiveLocation) Edit

func (ll *LiveLocation) Edit(latitude, langitude, horizontalAccuracy float32, heading, proximtyAlertRadius int, replyMarkUp *objs.InlineKeyboardMarkup) (*objs.DefaultResult, error)

Edit edits the live location.

------------------------

Official telegram doc :

Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

func (*LiveLocation) Send

func (ll *LiveLocation) Send(chatId int, silent, protectContent bool) (*objs.SendMethodsResult, error)

Send sends this live location to all types of chats but channels. To send it to a channel use "SendToChannelMethod".

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

------------------------

Official telegram doc :

Use this method to send point on the map. On success, the sent Message is returned.

func (*LiveLocation) SendToChannel

func (ll *LiveLocation) SendToChannel(chatId string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendToChannel sends this live location to a channel. Chat id should be the username of the channel.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

------------------------

Official telegram doc :

Use this method to send point on the map. On success, the sent Message is returned.

func (*LiveLocation) Stop

func (ll *LiveLocation) Stop(replyMarkrup objs.InlineKeyboardMarkup) (*objs.DefaultResult, error)

Stop stops the live location.

------------------------

Official telegram doc :

Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.

type MarkUps added in v1.3.3

type MarkUps interface {
	// contains filtered or unexported methods
}

MarkUps is the interface used for creating normal keyboards and inline keyboards.

type MediaGroup

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

MediaGroup is a media group that can be sent

func (*MediaGroup) AddAnimation

func (mg *MediaGroup) AddAnimation(caption, parseMode string, width, height, duration int, captionEntitie []objs.MessageEntity) (*AnimationInserter, error)

AddAnimation returns an AnimationInserter to add an animation to the album

func (*MediaGroup) AddAudio

func (mg *MediaGroup) AddAudio(caption, parseMode, performer, title string, duration int, captionEntitie []objs.MessageEntity) (*AudioInserter, error)

AddAudio returns an AudioInserter to add an audio to the album

func (*MediaGroup) AddDocument

func (mg *MediaGroup) AddDocument(caption, parseMode string, disableContentTypeDetection bool, captionEntitie []objs.MessageEntity) (*DocumentInserter, error)

AddDocument returns a DocumentInserter to add a document to the album

func (*MediaGroup) AddPhoto

func (mg *MediaGroup) AddPhoto(caption, parseMode string, captionEntitie []objs.MessageEntity) (*PhotoInserter, error)

AddPhoto returns a PhotoInserter to add a photo to the album

func (*MediaGroup) AddVideo

func (mg *MediaGroup) AddVideo(caption, parseMode string, width, height, duration int, supportsStreaming bool, captionEntitie []objs.MessageEntity) (*VideoInserter, error)

AddVideo returns a VideoInserter to add a video to the album

func (*MediaGroup) Send

func (mg *MediaGroup) Send(chatId int, silent, protectContent bool) (*objs.SendMediaGroupMethodResult, error)

Send sends this album (to all types of chat but channels, to send to channels use "SendToChannel" method)

--------------------

Official telegram doc :

Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*MediaGroup) SendToChannel

func (mg *MediaGroup) SendToChannel(chatId string, silent, protectContent bool) (*objs.SendMediaGroupMethodResult, error)

Send sends this album to a channel.

--------------------

Official telegram doc :

Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

type MediaSender

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

MediaSender is a tool for sending media messages.

func (*MediaSender) SendByFile

func (ms *MediaSender) SendByFile(file *os.File, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendByFile sends a file that is located in this device.

func (*MediaSender) SendByFileIdOrUrl

func (ms *MediaSender) SendByFileIdOrUrl(fileIdOrUrl string, silent, protectContent bool) (*objs.SendMethodsResult, error)

SendByFileIdOrUrl sends a file that already exists on telegram servers (file id) or a url on the web.

func (*MediaSender) SetThumbnail

func (ms *MediaSender) SetThumbnail(fileIdOrURL string)

SetThumbnail sets the tumbnail of the file. It takes a file id or a url. If you want to send a file use "setThumbnailFile" instead. If this media does not support thumbnail, the thumbnail will be ignored.

func (*MediaSender) SetThumbnailFile

func (ms *MediaSender) SetThumbnailFile(file *os.File) error

SetThumbnailFile sets the thumbnail of the file. It takes a file existing on the device. If this media does not support thumbnail, the thumbnail will be ignored.

type MediaType

type MediaType int
const (
	PHOTO     MediaType = 1
	VIDEO     MediaType = 2
	AUDIO     MediaType = 3
	ANIMATION MediaType = 4
	DOCUMENT  MediaType = 5
	VIDEONOTE MediaType = 6
	VOICE     MediaType = 7
	STICKER   MediaType = 8
)

type MessageCopier

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

MessageCopier is tool for copying messages.

func (*MessageCopier) CopyFromChannelToChannel

func (mf *MessageCopier) CopyFromChannelToChannel(chatId, fromChatId string) (*objs.SendMethodsResult, error)

CopyFromChannelToChannel copies the given message from a channel to another channel. chatId is the channel that message is being copied to and fromChatId is the channel that message is being copied to.

func (*MessageCopier) CopyFromChannelToUser

func (mf *MessageCopier) CopyFromChannelToUser(chatId int, fromChatId string) (*objs.SendMethodsResult, error)

CopyFromChannelToUser copies the given message from a channel to a user. chatId is the user that message is being copied to and fromChatId is the channel that message is being copied to.

func (*MessageCopier) CopyFromUserToChannel

func (mf *MessageCopier) CopyFromUserToChannel(chatId string, fromChatId int) (*objs.SendMethodsResult, error)

CopyFromUserToChannel copies the given message from a user to a channel. chatId is the channel that message is being copied to and fromChatId is the user that message is being copied to.

func (*MessageCopier) CopyFromUserToUser

func (mf *MessageCopier) CopyFromUserToUser(chatId, fromChatId int) (*objs.SendMethodsResult, error)

CopyFromUserToUser copies the given message from a user to another user. chatId is the user that message is being copied to and fromChatId is the user that message is being copied to.

type MessageEditor

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

MessageEditor is a tool for editing messsages.

func (*MessageEditor) DeleteMessage

func (me *MessageEditor) DeleteMessage(messageId int) (*objs.LogicalResult, error)

DeleteMessage can be 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.

- A dice message in a private chat can only be deleted if it was sent more than 24 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.

Returns True on success.

func (*MessageEditor) EditCaption

func (me *MessageEditor) EditCaption(messageId int, caption, inlineMessageId, parseMode string, captionEntities []objs.MessageEntity, keyboard *inlineKeyboard) (*objs.DefaultResult, error)

EditCaption can be used to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

func (*MessageEditor) EditMediaAnimation

func (mg *MessageEditor) EditMediaAnimation(messageId int, caption, parseMode string, width, height, duration int, captionEntitie []objs.MessageEntity, keyboard *inlineKeyboard) *AnimationEditor

EditMediaAnimation returns an AnimationEditor to edit an animation

func (*MessageEditor) EditMediaAudio

func (mg *MessageEditor) EditMediaAudio(messageId int, caption, parseMode, performer, title string, duration int, captionEntitie []objs.MessageEntity, keyboard *inlineKeyboard) *AudioEditor

EditMediaAudio returns an AudioEditor to edit an audio

func (*MessageEditor) EditMediaDocument

func (mg *MessageEditor) EditMediaDocument(messageId int, caption, parseMode string, disableContentTypeDetection bool, captionEntitie []objs.MessageEntity, keyboard *inlineKeyboard) *DocumentEditor

EditMediaDocument returns a DocumentEditor to edit a document

func (*MessageEditor) EditMediaPhoto

func (mg *MessageEditor) EditMediaPhoto(messageId int, caption, parseMode string, captionEntitie []objs.MessageEntity, keyboard *inlineKeyboard) *PhotoEditor

EditMediaPhoto returns a PhotoEditor to edit a photo

func (*MessageEditor) EditMediaVideo

func (mg *MessageEditor) EditMediaVideo(messageId int, caption, parseMode string, width, height, duration int, supportsStreaming bool, captionEntitie []objs.MessageEntity, keyboard *inlineKeyboard) *VideoEditor

EditMediaVideo returns a VideoEditor to edit a video

func (*MessageEditor) EditReplyMarkup

func (me *MessageEditor) EditReplyMarkup(messageId int, inlineMessageId string, keyboard *inlineKeyboard) (*objs.DefaultResult, error)

EditReplyMarkup can be used to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

func (*MessageEditor) EditText

func (me *MessageEditor) EditText(messageId int, text, inlineMessageId, parseMode string, entities []objs.MessageEntity, disableWebPagePreview bool, keyboard *inlineKeyboard) (*objs.DefaultResult, error)

EditText can be used to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

type MessageForwarder

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

MessageForwarder is a tool for forwarding messages.

func (*MessageForwarder) ForwardFromChannelToChannel

func (mf *MessageForwarder) ForwardFromChannelToChannel(chatId, fromChatId string) (*objs.SendMethodsResult, error)

ForwardFromChannelToChannel forwards the given message from a channel to another channel. chatId is the channel that message is being forwarded to and fromChatId is the channel that message is being forwarded to.

func (*MessageForwarder) ForwardFromChannelToUser

func (mf *MessageForwarder) ForwardFromChannelToUser(chatId int, fromChatId string) (*objs.SendMethodsResult, error)

ForwardFromChannelToUser forwards the given message from a channel to a user. chatId is the user that message is being forwarded to and fromChatId is the channel that message is being forwarded to.

func (*MessageForwarder) ForwardFromUserToChannel

func (mf *MessageForwarder) ForwardFromUserToChannel(chatId string, fromChatId int) (*objs.SendMethodsResult, error)

ForwardFromUserToChannel forwards the given message from a user to a channel. chatId is the channel that message is being forwarded to and fromChatId is the user that message is being forwarded to.

func (*MessageForwarder) ForwardFromUserToUser

func (mf *MessageForwarder) ForwardFromUserToUser(chatId, fromChatId int) (*objs.SendMethodsResult, error)

ForwardFromUserToUser forwards the given message from a user to another user. chatId is the user that message is being forwarded to and fromChatId is the user that message is being forwarded to.

type PhotoEditor

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

PhotoEditor is a tool for editing photos.

func (*PhotoEditor) EditByFile

func (pi *PhotoEditor) EditByFile(file *os.File) (*objs.DefaultResult, error)

EditByFile edits this photo with an existing file in the device

func (*PhotoEditor) EditByFileIdOrURL

func (pi *PhotoEditor) EditByFileIdOrURL(fileIdOrUrl string) (*objs.DefaultResult, error)

EditByFileIdOrURL edits this photo by file id or url

type PhotoInserter

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

PhotoInserter is a tool for inserting photos into the MediaGroup.

func (*PhotoInserter) AddByFile

func (pi *PhotoInserter) AddByFile(file *os.File) error

AddByFile adds an existing file in the device

func (*PhotoInserter) AddByFileIdOrURL

func (pi *PhotoInserter) AddByFileIdOrURL(fileIdOrUrl string)

AddByFileIdOrURL adds this file by file id or url

type Poll

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

Poll is an automatic poll.

func (*Poll) AddOption

func (p *Poll) AddOption(option string)

AddOption adds an option to poll.

-If the poll has been sent this method will do nothing.

func (*Poll) GetCorrectOption

func (p *Poll) GetCorrectOption() int

GetCorrectOption returns the correct option id. returnes 0 if type of the poll is "regular"

func (*Poll) GetExplanation

func (p *Poll) GetExplanation() string

GetExplanation returns the explanation of this poll

func (*Poll) GetId

func (p *Poll) GetId() string

GetId returns the id of this poll

func (*Poll) GetOptions

func (p *Poll) GetOptions() []string

GetOptions returns the options of this poll

func (*Poll) GetQuestion

func (p *Poll) GetQuestion() string

GetQuestion returns the question of this poll

func (*Poll) GetResult

func (p *Poll) GetResult() []objs.PollOption

GetResult returns the up to date result of the poll

func (*Poll) GetTotalVoters

func (p *Poll) GetTotalVoters() int

GetTotalVoters returns the up to date total number of voters for this poll

func (*Poll) GetType

func (p *Poll) GetType() string

GetType returns the poll type. Its either "regular" or "quiz".

func (*Poll) GetUpdateChannel

func (p *Poll) GetUpdateChannel() *chan bool

GetUpdateChannel returns the update channel for this poll. Everytime an update is received which contains update for this poll, true is passed into the channel.

func (*Poll) Send

func (p *Poll) Send(silent, protectContent bool, replyTo int) error

Send sends the poll. If you want more options foe sending the bot, use "SendAdvanced" method.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Poll) SendAdvanced

func (p *Poll) SendAdvanced(replyTo int, silent, allowSendingWithOutReply, protectContent bool, replyMarkup objs.ReplyMarkup) error

SendAdvanced sends the poll. This method has more options than "Send" method.

If "silent" argument is true, the message will be sent without notification.

If "protectContent" argument is true, the message can't be forwarded or saved.

func (*Poll) SetCloseDate

func (p *Poll) SetCloseDate(cd int)

SetCloseDate sets the close date of this poll.

-If open period has been specified, this method wont set close date for the poll.

-If the poll has been sent this method will do nothing.

func (*Poll) SetCorrectOption

func (p *Poll) SetCorrectOption(co int)

SetCorrectOption sets the correct option id for the poll. The correct option is the index of the the true option in the options array.(0 based)

-If the type of this bot is "regular" this method will do nothing.

-If the poll has been sent this method will do nothing.

func (*Poll) SetExplanation

func (p *Poll) SetExplanation(explanation, explanationParseMode string, explanationEntities []objs.MessageEntity)

SetExplanation sets explanation if this poll.

If the poll has been sent this method will do nothing.

func (*Poll) SetFlags

func (p *Poll) SetFlags(isClosed, isAnonymous, allowMA bool)

SetFlags sets the flags of this poll. Flags are "isClosed","isAnonymous" and "allowMultipleAnswers".

-If the poll has been sent this method will do nothing.

func (*Poll) SetOpenPeriod

func (p *Poll) SetOpenPeriod(op int)

SetOpenPeriod sets open period of this poll. According to official telegram doc, open period is amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date.

-If close date has been specified, this method wont set open period.

-If the poll has been sent this method will do nothing.

func (*Poll) Stop

func (p *Poll) Stop() error

Stop stops the poll

func (*Poll) Update

func (p *Poll) Update(poll *objs.Poll) error

Update takes an poll object and extracts the poll update from it.

May return error if the update does not contain any poll or the poll in the update is not this poll

type StickerSet

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

StickerSet is a set of stickers.

func (*StickerSet) AddAnimatedSticker added in v1.6.7

func (ss *StickerSet) AddAnimatedSticker(tgsFile *os.File, emojies string, maskPosition *objs.MaskPosition) (*objs.LogicalResult, error)

AddAnimatedSticker adds a new TGS sticker (animated sticker) to the sticker set.

func (*StickerSet) AddPngSticker added in v1.6.7

func (ss *StickerSet) AddPngSticker(pngPicFileIdOrUrl, emojies string, maskPosition *objs.MaskPosition) (*objs.LogicalResult, error)

AddPngSticker adds a new PNG picture to the sticker set. This method should be used when the PNG file in stored in telegram servers or it's an HTTP URL. If the file is stored in your computer, use "AddPngStickerByFile" method.

func (*StickerSet) AddPngStickerByFile added in v1.6.7

func (ss *StickerSet) AddPngStickerByFile(pngPicFile *os.File, emojies string, maskPosition *objs.MaskPosition) (*objs.LogicalResult, error)

AddPngStickerByFile adds a new PNG picture to the sticker set. This method should be used when the PNG file in stored in your computer.

func (*StickerSet) AddSticker deprecated

func (ss *StickerSet) AddSticker(pngStickerFileIdOrUrl string, pngStickerFile *os.File, tgsSticker *os.File, emojies string, maskPosition *objs.MaskPosition) (*objs.LogicalResult, error)

Deprecated: This function should no longer be used for adding stickers to a sticker set. It has been preserved for backward compatibility and will be removed in next versions. Use "AddPngSticker","AddAnimatedSticker" or "AddVideoSticker" methods instead.

Adds a sticker to the current set Use this method to add a new sticker to a set created by the bot. You must use exactly one of the fields png_sticker or tgs_sticker. Animated stickers can be added to animated sticker sets and only to them. Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success. png sticker can be passed as an file id or url (pngStickerFileIdOrUrl) or file(pngStickerFile).

func (*StickerSet) AddVideoSticker added in v1.6.7

func (ss *StickerSet) AddVideoSticker(webmFile *os.File, emojies string, maskPosition *objs.MaskPosition) (*objs.LogicalResult, error)

AddVideoSticker adds a new WEBM sticker (video sticker) to the sticker set.

func (*StickerSet) DeleteStickerFromSet

func (ss *StickerSet) DeleteStickerFromSet(sticker string) (*objs.LogicalResult, error)

DeleteStickerFromSet can be used to delete a sticker from a set created by the bot. Returns True on success.

"sticker" is file identifier of the sticker.

func (*StickerSet) GetName

func (ss *StickerSet) GetName() string

GetName returnes the name of this sticker set

func (*StickerSet) GetStickers

func (ss *StickerSet) GetStickers() []objs.Sticker

GetStickers returns the sticker in this sticker set.

func (*StickerSet) GetThumb

func (ss *StickerSet) GetThumb() *objs.PhotoSize

GetThumb returns the thumbnail of this sticker set

func (*StickerSet) GetTitle

func (ss *StickerSet) GetTitle() string

GetTitle returns the title of this sticker set

func (*StickerSet) SetStickerPosition

func (ss *StickerSet) SetStickerPosition(sticker string, position int) (*objs.LogicalResult, error)

SetStickerPosition can be used to move a sticker in a set created by the bot to a specific position. Returns True on success.

"sticker" is file identifier of the sticker and "position" is new sticker position in the set, zero-based

func (*StickerSet) SetThumb

func (ss *StickerSet) SetThumb(userId int, thumb string) (*objs.LogicalResult, error)

SetThumb can be used to set the thumbnail of a sticker set using url or file id. Animated thumbnails can be set for animated sticker sets only. Returns True on success.

func (*StickerSet) SetThumbByFile

func (ss *StickerSet) SetThumbByFile(userId int, thumb *os.File) (*objs.LogicalResult, error)

SetThumbByFile can be used to set the thumbnail of a sticker set using a file on the computer. Animated thumbnails can be set for animated sticker sets only. Returns True on success.

type TextFormatter added in v1.4.5

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

TextFormatter is tool for creating formatted texts.

func (*TextFormatter) AddBold added in v1.4.5

func (mf *TextFormatter) AddBold(text string)

AddBold adds a bold text to the original text.

func (*TextFormatter) AddBotCommand added in v1.4.5

func (mf *TextFormatter) AddBotCommand(text string)

AddBotCommand adds a bot command to the original text. example : /start@jobs_bot

func (*TextFormatter) AddCashtag added in v1.4.5

func (mf *TextFormatter) AddCashtag(text string)

AddCashtag adds a cashtag to the original text. exzmple : $USD

func (*TextFormatter) AddCode added in v1.4.5

func (mf *TextFormatter) AddCode(text, language string)

AddCode adds a piece of code (programming code) to the original text.

func (*TextFormatter) AddEmail added in v1.4.5

func (mf *TextFormatter) AddEmail(text string)

AddEmail adds an email to the original text. example : do-not-reply@telegram.org

func (*TextFormatter) AddHashtag added in v1.4.5

func (mf *TextFormatter) AddHashtag(text string)

AddHashtag adds a hashtag to the original text. example : #hashtag

func (*TextFormatter) AddItalic added in v1.4.5

func (mf *TextFormatter) AddItalic(text string)

AddItalic adds an italic text to the original text.

func (*TextFormatter) AddMention added in v1.4.5

func (mf *TextFormatter) AddMention(text string)

AddMention adds a mention to the original text. example : @username

func (*TextFormatter) AddNormal added in v1.4.5

func (mf *TextFormatter) AddNormal(text string)

AddNormal adds a normal text to the original text

func (*TextFormatter) AddPhoneNumber added in v1.4.5

func (mf *TextFormatter) AddPhoneNumber(text string)

AddPhoneNumber adds a phone number to the original text. example : +1-212-555-0123

func (*TextFormatter) AddSpoiler added in v1.4.5

func (mf *TextFormatter) AddSpoiler(text string)

AddSpoiler adds a spoiler text to the original text. This text is hidden until user clicks on it.

func (*TextFormatter) AddStrike added in v1.4.5

func (mf *TextFormatter) AddStrike(text string)

AddStrike adds a strikethrough text to the original text.

func (mf *TextFormatter) AddTextLink(text, url string)

AddTextLink adds a text link (clickable text which opens a URL) to the original text.

func (*TextFormatter) AddTextMention added in v1.4.5

func (mf *TextFormatter) AddTextMention(text string, user *objs.User)

AddTextMention adds a mention (for users without username) to the original text.

func (*TextFormatter) AddURL added in v1.4.5

func (mf *TextFormatter) AddURL(text string)

AddURL adds a url (not a clickable text url) to the original text. example : https://telegram.org

func (*TextFormatter) AddUnderline added in v1.4.5

func (mf *TextFormatter) AddUnderline(text string)

AddUnderline adds an underlined text to the original text.

func (*TextFormatter) GetEntities added in v1.4.5

func (mf *TextFormatter) GetEntities() []objs.MessageEntity

GetEntities returnss the entities array

func (*TextFormatter) GetText added in v1.4.5

func (mf *TextFormatter) GetText() string

GetText returns the original text

type VideoEditor

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

VideoEditor is a tool for editing videos.

func (*VideoEditor) EditByFile

func (vi *VideoEditor) EditByFile(file *os.File) (*objs.DefaultResult, error)

EditByFile edits this video by file in the device

func (*VideoEditor) EditByFileIdOrURL

func (vi *VideoEditor) EditByFileIdOrURL(fileIdOrUrl string) (*objs.DefaultResult, error)

EditByFileIdOrURL edits this video by file id or url

func (*VideoEditor) EditThumbnail

func (vi *VideoEditor) EditThumbnail(fileIdOrURL string)

EditThumbnail edits the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*VideoEditor) EditThumbnailFile

func (vi *VideoEditor) EditThumbnailFile(file *os.File) error

EditThumbnailFile edits the thumbnail of the file. It takes a file existing on the device

type VideoInserter

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

VideoInserter is a tool for inserting videos into the MediaGroup.

func (*VideoInserter) AddByFile

func (vi *VideoInserter) AddByFile(file *os.File) error

AddByFile adds an existing file in the device

func (*VideoInserter) AddByFileIdOrURL

func (vi *VideoInserter) AddByFileIdOrURL(fileIdOrUrl string)

AddByFileIdOrURL adds this file by file id or url

func (*VideoInserter) SetThumbnail

func (vi *VideoInserter) SetThumbnail(fileIdOrURL string)

SetThumbnail sets the tumbnail of the file. It takes a fileId or a url. If you want to send a file use "setThumbnailFile" instead.

func (*VideoInserter) SetThumbnailFile

func (vi *VideoInserter) SetThumbnailFile(file *os.File) error

SetThumbnailFile sets the tumbnail of the file. It takes a file existing on the device

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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