commit 3fdcb11dcd570196e1284dc2c625a27f5c645871 Author: Vladimir Hodakov Date: Tue Dec 4 08:32:11 2018 +0400 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6ca9b17 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +fw_zookeeper_helper.yaml \ No newline at end of file diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 0000000..98479aa --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,41 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + branch = "master" + digest = "1:cdfaade39c21052a144a32f944ce80030cbdce760d0c63c60ca8b9f59928a6f4" + name = "github.com/Arman92/go-tdlib" + packages = ["."] + pruneopts = "UT" + revision = "9577ff528640031a5c3a5f7386c896255f69c723" + +[[projects]] + digest = "1:6112a5eaec2ec65df289ccbb7a730aaf03e3c5cce6c906d367ccf9b7ac567604" + name = "github.com/rs/zerolog" + packages = [ + ".", + "internal/cbor", + "internal/json", + ] + pruneopts = "UT" + revision = "8747b7b3a51b5d08ee7ac50eaf4869edaf9f714a" + version = "v1.11.0" + +[[projects]] + digest = "1:4d2e5a73dc1500038e504a8d78b986630e3626dc027bc030ba5c75da257cdb96" + name = "gopkg.in/yaml.v2" + packages = ["."] + pruneopts = "UT" + revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" + version = "v2.2.2" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + input-imports = [ + "github.com/Arman92/go-tdlib", + "github.com/rs/zerolog", + "gopkg.in/yaml.v2", + ] + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 0000000..f8e072b --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,34 @@ +# Gopkg.toml example +# +# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" +# +# [prune] +# non-go = false +# go-tests = true +# unused-packages = true + + +[[constraint]] + branch = "master" + name = "github.com/Arman92/go-tdlib" + +[prune] + go-tests = true + unused-packages = true diff --git a/context/context.go b/context/context.go new file mode 100644 index 0000000..ae94627 --- /dev/null +++ b/context/context.go @@ -0,0 +1,64 @@ +// Fantasy World Zookeeper Bot +// Copyright (c) 2018 Vladimir "fat0troll" Hodakov + +package context + +import ( + "fmt" + "github.com/rs/zerolog" + "gopkg.in/yaml.v2" + "io/ioutil" + "lab.wtfteam.pro/fat0troll/fw_zookeeper_helper/internal/config" + "os" + "path/filepath" + "runtime" +) + +// getMemoryUsage returns memory usage for logger. +func (c *Context) getMemoryUsage(e *zerolog.Event, level zerolog.Level, message string) { + var m runtime.MemStats + runtime.ReadMemStats(&m) + + e.Str("memalloc", fmt.Sprintf("%dMB", m.Alloc/1024/1024)) + e.Str("memsys", fmt.Sprintf("%dMB", m.Sys/1024/1024)) + e.Str("numgc", fmt.Sprintf("%d", m.NumGC)) +} + +// Init is an initialization function for core context +// Without these parts of the application we can't start at all +func (c *Context) Init() { + c.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger() + c.Logger = c.Logger.Hook(zerolog.HookFunc(c.getMemoryUsage)) + + c.Logger.Info().Msgf("fw_zookeeper_helper v. %s is starting...", VERSION) +} + +// InitConfiguration reads configuration from YAML and parses it in +// config.Struct. +func (c *Context) InitConfiguration() bool { + c.Logger.Info().Msg("Loading configuration files...") + + configPath := os.Getenv("BOT_CONFIG") + if configPath == "" { + configPath = "./example/fw_zookeeper_helper.yaml" + } + normalizedConfigPath, _ := filepath.Abs(configPath) + c.Logger.Debug().Msgf("Configuration file path: %s", normalizedConfigPath) + + // Read configuration file into []byte. + fileData, err := ioutil.ReadFile(normalizedConfigPath) + if err != nil { + c.Logger.Error().Err(err).Msg("Failed to read configuration file") + return false + } + + c.Config = &config.Struct{} + err = yaml.Unmarshal(fileData, c.Config) + if err != nil { + c.Logger.Error().Err(err).Msg("Failed to parse configuration file") + return false + } + + c.Logger.Info().Msg("Configuration file parsed successfully") + return true +} diff --git a/context/exported.go b/context/exported.go new file mode 100644 index 0000000..0deac0e --- /dev/null +++ b/context/exported.go @@ -0,0 +1,24 @@ +// Fantasy World Zookeeper Helper Bot +// Copyright (c) 2018 Vladimir "fat0troll" Hodakov + +package context + +import ( + "github.com/rs/zerolog" + "lab.wtfteam.pro/fat0troll/fw_zookeeper_helper/internal/config" +) + +// VERSION is the current bot's version +const VERSION = "0.0.1" + +// Context is the main application context. +type Context struct { + Config *config.Struct + Logger zerolog.Logger +} + +// NewContext is an initialization function for Context +func NewContext() *Context { + c := &Context{} + return c +} diff --git a/example/fw_zookeeper_helper.yaml b/example/fw_zookeeper_helper.yaml new file mode 100644 index 0000000..a54ded9 --- /dev/null +++ b/example/fw_zookeeper_helper.yaml @@ -0,0 +1,6 @@ +tdlib: + api_id: "your-id" + api_hash: "your-hash" + database_directory: "/tmp/tdlib-db/" + files_directory: "/tmp/tdlib-files/" + errors_file: "/tmp/tdlib.txt" \ No newline at end of file diff --git a/golangci.yaml b/golangci.yaml new file mode 100644 index 0000000..b729915 --- /dev/null +++ b/golangci.yaml @@ -0,0 +1,4 @@ +run: + deadline: 5m +linters: + enable-all: true diff --git a/internal/config/struct.go b/internal/config/struct.go new file mode 100644 index 0000000..ad20bc1 --- /dev/null +++ b/internal/config/struct.go @@ -0,0 +1,10 @@ +// Fantasy World Zookeeper Helper Bot +// Copyright (c) 2018 Vladimir "fat0troll" Hodakov + +package config + +// Struct is a main configuration structure that holds all other +// structs within. +type Struct struct { + TDLib TDLib `yaml:"tdlib"` +} diff --git a/internal/config/tdlib.go b/internal/config/tdlib.go new file mode 100644 index 0000000..4824993 --- /dev/null +++ b/internal/config/tdlib.go @@ -0,0 +1,14 @@ +// Fantasy World Zookeeper Helper Bot +// Copyright (c) 2018 Vladimir "fat0troll" Hodakov + +package config + +// TDLib struct handles all configuration of tdlib +// tdlib is an official Telegram MTProto library +type TDLib struct { + APIID string `yaml:"api_id"` + APIHash string `yaml:"api_hash"` + DatabaseDirectory string `yaml:"database_directory"` + FilesDirectory string `yaml:"files_directory"` + ErrorsFile string `yaml:"errors_file"` +} diff --git a/internal/telegram/exported.go b/internal/telegram/exported.go new file mode 100644 index 0000000..6f1a66c --- /dev/null +++ b/internal/telegram/exported.go @@ -0,0 +1,31 @@ +// Fantasy World Zookeeper Helper Bot +// Copyright (c) 2018 Vladimir "fat0troll" Hodakov + +package telegram + +import ( + tdlib "github.com/Arman92/go-tdlib" + "github.com/rs/zerolog" + "lab.wtfteam.pro/fat0troll/fw_zookeeper_helper/context" +) + +var ( + c *context.Context + log zerolog.Logger + + client *tdlib.Client +) + +// New initializes package +func New(cc *context.Context) { + c = cc + log = c.Logger.With().Str("domain", "telegram").Int("version", 1).Logger() + + log.Info().Msg("Starting Telegram MTProto instance") + + Authenticate() + + go func() { + Connect() + }() +} diff --git a/internal/telegram/telegram.go b/internal/telegram/telegram.go new file mode 100644 index 0000000..4396efd --- /dev/null +++ b/internal/telegram/telegram.go @@ -0,0 +1,121 @@ +// Fantasy World Zookeeper Helper Bot +// Copyright (c) 2018 Vladimir "fat0troll" Hodakov + +package telegram + +import ( + "fmt" + tdlib "github.com/Arman92/go-tdlib" + "lab.wtfteam.pro/fat0troll/fw_zookeeper_helper/context" + "strings" +) + +// Authenticate connects instance to Telegram +// At first launch we need to login manually - there is no way to automate +// Telegram login +func Authenticate() { + tdlib.SetLogVerbosityLevel(1) + tdlib.SetFilePath(c.Config.TDLib.ErrorsFile) + + // Create new instance of client + client = tdlib.NewClient(tdlib.Config{ + APIID: c.Config.TDLib.APIID, + APIHash: c.Config.TDLib.APIHash, + SystemLanguageCode: "en", + DeviceModel: "fw_zookeeper_helper", + SystemVersion: context.VERSION, + ApplicationVersion: context.VERSION, + UseMessageDatabase: true, + UseFileDatabase: true, + UseChatInfoDatabase: true, + UseTestDataCenter: false, + DatabaseDirectory: c.Config.TDLib.DatabaseDirectory, + FileDirectory: c.Config.TDLib.FilesDirectory, + IgnoreFileNames: false, + }) + + for { + currentState, _ := client.Authorize() + log.Info().Msg("Starting Telegram authorization...") + if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPhoneNumberType { + fmt.Print("Enter phone: ") + var number string + fmt.Scanln(&number) + _, err := client.SendPhoneNumber(number) + if err != nil { + log.Error().Err(err).Msg("Error sending phone number") + } + } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitCodeType { + fmt.Print("Enter code: ") + var code string + fmt.Scanln(&code) + _, err := client.SendAuthCode(code) + if err != nil { + log.Error().Err(err).Msg("Error sending auth code") + } + } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPasswordType { + fmt.Print("Enter Password: ") + var password string + fmt.Scanln(&password) + _, err := client.SendAuthPassword(password) + if err != nil { + log.Error().Err(err).Msg("Error sending auth password") + } + } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateReadyType { + me, _ := client.GetMe() + log.Info().Msgf("Logged into Telegram as @%s", me.Username) + break + } + } +} + +// Connect connects into updates chain +// +func Connect() { + go func() { + // Create an filter function which will be used to filter out unwanted tdlib messages + eventFilter := func(msg *tdlib.TdMessage) bool { + updateMsg := (*msg).(*tdlib.UpdateNewMessage) + // We need only messages, created by @FWorldBot + return updateMsg.Message.ViaBotUserID == 6.74929718e+08 + } + + // Here we can add a receiver to retreive any message type we want + // We like to get UpdateNewMessage events and with a specific FilterFunc + receiver := client.AddEventReceiver(&tdlib.UpdateNewMessage{}, eventFilter, 5) + for newMsg := range receiver.Chan { + updateMsg := (newMsg).(*tdlib.UpdateNewMessage) + // Check if message text contains needed battle data + msgText := updateMsg.Message.Content.(*tdlib.MessageText) + if strings.HasPrefix(msgText.Text.Text, "Я встретил") { + battleType := "" + battleTag := "" + if strings.Contains(msgText.Text.Text, "Огров") { + battleType = "Огры!" + } + if strings.Contains(msgText.Text.Text, "Буйволов") { + battleType = "Буйволы!" + } + if strings.Contains(msgText.Text.Text, "Кабанов") { + battleType = "Кабаны!" + } + keyboard := updateMsg.Message.ReplyMarkup.(*tdlib.ReplyMarkupInlineKeyboard) + if len(keyboard.Rows) > 0 { + if len(keyboard.Rows[0]) > 0 { + button := keyboard.Rows[0][0] + buttonQuery := button.Type.(*tdlib.InlineKeyboardButtonTypeCallback) + battleTag = string(buttonQuery.Data) + } + } + log.Debug().Msgf("Battle type: %s", battleType) + log.Debug().Msgf("Battle type: %s", battleTag) + } + } + + }() + + rawUpdates := client.GetRawUpdatesChannel(100) + for update := range rawUpdates { + log.Debug().Msgf("Update of type %s received", update.Data["@type"]) + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..7cef82f --- /dev/null +++ b/main.go @@ -0,0 +1,43 @@ +// Fantasy World Zookeeper Helper Bot +// Copyright (c) 2018 Vladimir "fat0troll" Hodakov + +package main + +import ( + "lab.wtfteam.pro/fat0troll/fw_zookeeper_helper/context" + "lab.wtfteam.pro/fat0troll/fw_zookeeper_helper/internal/telegram" + "os" + "os/signal" + "runtime" + "syscall" +) + +func main() { + // Before any real work - lock to OS thread. We shouldn't leave it until + // shutdown + runtime.LockOSThread() + + // Initializing context + + c := context.NewContext() + c.Init() + c.InitConfiguration() + + telegram.New(c) + + // CTRL+C handler. + interrupt := make(chan os.Signal, 1) + signal.Notify(interrupt) + shutdownDone := make(chan bool, 1) + go func() { + signalThing := <-interrupt + if signalThing == syscall.SIGTERM || signalThing == syscall.SIGINT { + c.Logger.Info().Msg("Got " + signalThing.String() + " signal, shutting down...") + shutdownDone <- true + } + }() + + <-shutdownDone + os.Exit(0) + +} diff --git a/vendor/github.com/Arman92/go-tdlib/.gitignore b/vendor/github.com/Arman92/go-tdlib/.gitignore new file mode 100644 index 0000000..e56262f --- /dev/null +++ b/vendor/github.com/Arman92/go-tdlib/.gitignore @@ -0,0 +1,29 @@ + +# Any file without an extension +* +!*/ +!*.* + +/.vscode +/.git_old + + +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ + +tdlib-db +tdlib-files + +errors.txt \ No newline at end of file diff --git a/vendor/github.com/Arman92/go-tdlib/README.md b/vendor/github.com/Arman92/go-tdlib/README.md new file mode 100644 index 0000000..8cb4574 --- /dev/null +++ b/vendor/github.com/Arman92/go-tdlib/README.md @@ -0,0 +1,124 @@ +# go-tdlib +Golang Telegram TdLib JSON bindings + + +## Introduction +Telegram Tdlib is a complete library for creating telegram clients, it laso has a simple tdjson ready-to-use library to ease +the integration with different programming languages and platforms. + +**go-tdlib** is a complete tdlib-tdjson binding package to help you create your own Telegram clients. + +**NOTE:** basic tdjson-golang binding is inspired from this package: [go-tdjson](https://github.com/L11R/go-tdjson) + +All the classes and functions declared in [Tdlib TypeLanguage schema](https://github.com/tdlib/td/blob/master/td/generate/scheme/td_api.tl) +file have been exported using the autogenerate tool [tl-parser](https://github.com/Arman92/go-tl-parser). +So you can use every single type and method in Tdlib. + +## Key features: +* Autogenerated golang structs and methods of tdlib .tl schema +* Custom event receivers defined by user (e.g. get only text messages from a specific user) +* Supports all tdjson functions: Send(), Execute(), Receive(), Destroy(), SetFilePath(), SetLogVerbosityLevel() +* Supports all tdlib functions and types + +## Installation + +First of all you need to clone the Tdlib repo and build it: +```bash +git clone git@github.com:tdlib/td.git +cd td +mkdir build +cd build +cmake -DCMAKE_BUILD_TYPE=Release .. +cmake --build . -- -j5 +make install + +# -j5 refers to number of your cpu cores + 1 for multi-threaded build. +``` + +If hit any build errors, refer to [Tdlib build instructions](https://github.com/tdlib/td#building) +I'm using static linking against tdlib so it won't require to build the whole tdlib source files. + +## Docker +You can use prebuilt tdlib with following Docker image: + +***Windows:*** +``` shell +docker pull mihaildemidoff/tdlib-go +``` + +## Example +Here is a simple example for authorization and fetching updates: +```golang +package main + +import ( + "fmt" + + "github.com/Arman92/go-tdlib" +) + +func main() { + tdlib.SetLogVerbosityLevel(1) + tdlib.SetFilePath("./errors.txt") + + // Create new instance of client + client := tdlib.NewClient(tdlib.Config{ + APIID: "187786", + APIHash: "e782045df67ba48e441ccb105da8fc85", + SystemLanguageCode: "en", + DeviceModel: "Server", + SystemVersion: "1.0.0", + ApplicationVersion: "1.0.0", + UseMessageDatabase: true, + UseFileDatabase: true, + UseChatInfoDatabase: true, + UseTestDataCenter: false, + DatabaseDirectory: "./tdlib-db", + FileDirectory: "./tdlib-files", + IgnoreFileNames: false, + }) + + for { + currentState, _ := client.Authorize() + if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPhoneNumberType { + fmt.Print("Enter phone: ") + var number string + fmt.Scanln(&number) + _, err := client.SendPhoneNumber(number) + if err != nil { + fmt.Printf("Error sending phone number: %v", err) + } + } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitCodeType { + fmt.Print("Enter code: ") + var code string + fmt.Scanln(&code) + _, err := client.SendAuthCode(code) + if err != nil { + fmt.Printf("Error sending auth code : %v", err) + } + } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPasswordType { + fmt.Print("Enter Password: ") + var password string + fmt.Scanln(&password) + _, err := client.SendAuthPassword(password) + if err != nil { + fmt.Printf("Error sending auth password: %v", err) + } + } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateReadyType { + fmt.Println("Authorization Ready! Let's rock") + break + } + } + + // Main loop + for update := range client.RawUpdates { + // Show all updates + fmt.Println(update.Data) + fmt.Print("\n\n") + } + +} + +``` + +More examples can be found on [examples folder](https://github.com/Arman92/go-tdlib/tree/master/examples) diff --git a/vendor/github.com/Arman92/go-tdlib/methods.go b/vendor/github.com/Arman92/go-tdlib/methods.go new file mode 100755 index 0000000..66bb025 --- /dev/null +++ b/vendor/github.com/Arman92/go-tdlib/methods.go @@ -0,0 +1,7669 @@ +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// GetAuthorizationState Returns the current authorization state; this is an offline request. For informational purposes only. Use updateAuthorizationState instead to maintain the current authorization state +func (client *Client) GetAuthorizationState() (AuthorizationState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getAuthorizationState", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + switch AuthorizationStateEnum(result.Data["@type"].(string)) { + + case AuthorizationStateWaitTdlibParametersType: + var authorizationState AuthorizationStateWaitTdlibParameters + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateWaitEncryptionKeyType: + var authorizationState AuthorizationStateWaitEncryptionKey + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateWaitPhoneNumberType: + var authorizationState AuthorizationStateWaitPhoneNumber + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateWaitCodeType: + var authorizationState AuthorizationStateWaitCode + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateWaitPasswordType: + var authorizationState AuthorizationStateWaitPassword + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateReadyType: + var authorizationState AuthorizationStateReady + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateLoggingOutType: + var authorizationState AuthorizationStateLoggingOut + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateClosingType: + var authorizationState AuthorizationStateClosing + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case AuthorizationStateClosedType: + var authorizationState AuthorizationStateClosed + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// SetTdlibParameters Sets the parameters for TDLib initialization. Works only when the current authorization state is authorizationStateWaitTdlibParameters +// @param parameters Parameters +func (client *Client) SetTdlibParameters(parameters *TdlibParameters) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setTdlibParameters", + "parameters": parameters, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckDatabaseEncryptionKey Checks the database encryption key for correctness. Works only when the current authorization state is authorizationStateWaitEncryptionKey +// @param encryptionKey Encryption key to check or set up +func (client *Client) CheckDatabaseEncryptionKey(encryptionKey []byte) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkDatabaseEncryptionKey", + "encryption_key": encryptionKey, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetAuthenticationPhoneNumber Sets the phone number of the user and sends an authentication code to the user. Works only when the current authorization state is authorizationStateWaitPhoneNumber +// @param phoneNumber The phone number of the user, in international format +// @param allowFlashCall Pass true if the authentication code may be sent via flash call to the specified phone number +// @param isCurrentPhoneNumber Pass true if the phone number is used on the current device. Ignored if allow_flash_call is false +func (client *Client) SetAuthenticationPhoneNumber(phoneNumber string, allowFlashCall bool, isCurrentPhoneNumber bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setAuthenticationPhoneNumber", + "phone_number": phoneNumber, + "allow_flash_call": allowFlashCall, + "is_current_phone_number": isCurrentPhoneNumber, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ResendAuthenticationCode Re-sends an authentication code to the user. Works only when the current authorization state is authorizationStateWaitCode and the next_code_type of the result is not null +func (client *Client) ResendAuthenticationCode() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "resendAuthenticationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckAuthenticationCode Checks the authentication code. Works only when the current authorization state is authorizationStateWaitCode +// @param code The verification code received via SMS, Telegram message, phone call, or flash call +// @param firstName If the user is not yet registered, the first name of the user; 1-255 characters +// @param lastName If the user is not yet registered; the last name of the user; optional; 0-255 characters +func (client *Client) CheckAuthenticationCode(code string, firstName string, lastName string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkAuthenticationCode", + "code": code, + "first_name": firstName, + "last_name": lastName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckAuthenticationPassword Checks the authentication password for correctness. Works only when the current authorization state is authorizationStateWaitPassword +// @param password The password to check +func (client *Client) CheckAuthenticationPassword(password string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkAuthenticationPassword", + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RequestAuthenticationPasswordRecovery Requests to send a password recovery code to an email address that was previously set up. Works only when the current authorization state is authorizationStateWaitPassword +func (client *Client) RequestAuthenticationPasswordRecovery() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "requestAuthenticationPasswordRecovery", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RecoverAuthenticationPassword Recovers the password with a password recovery code sent to an email address that was previously set up. Works only when the current authorization state is authorizationStateWaitPassword +// @param recoveryCode Recovery code to check +func (client *Client) RecoverAuthenticationPassword(recoveryCode string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "recoverAuthenticationPassword", + "recovery_code": recoveryCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckAuthenticationBotToken Checks the authentication token of a bot; to log in as a bot. Works only when the current authorization state is authorizationStateWaitPhoneNumber. Can be used instead of setAuthenticationPhoneNumber and checkAuthenticationCode to log in +// @param token The bot token +func (client *Client) CheckAuthenticationBotToken(token string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkAuthenticationBotToken", + "token": token, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var okDummy Ok + err = json.Unmarshal(result.Raw, &okDummy) + return &okDummy, err + +} + +// LogOut Closes the TDLib instance after a proper logout. Requires an available network connection. All local data will be destroyed. After the logout completes, updateAuthorizationState with authorizationStateClosed will be sent +func (client *Client) LogOut() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "logOut", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// Close Closes the TDLib instance. All databases will be flushed to disk and properly closed. After the close completes, updateAuthorizationState with authorizationStateClosed will be sent +func (client *Client) Close() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "close", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// Destroy Closes the TDLib instance, destroying all local data without a proper logout. The current user session will remain in the list of all active sessions. All local data will be destroyed. After the destruction completes updateAuthorizationState with authorizationStateClosed will be sent +func (client *Client) Destroy() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "destroy", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetDatabaseEncryptionKey Changes the database encryption key. Usually the encryption key is never changed and is stored in some OS keychain +// @param newEncryptionKey New encryption key +func (client *Client) SetDatabaseEncryptionKey(newEncryptionKey []byte) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setDatabaseEncryptionKey", + "new_encryption_key": newEncryptionKey, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetPasswordState Returns the current state of 2-step verification +func (client *Client) GetPasswordState() (*PasswordState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getPasswordState", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var passwordState PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// SetPassword Changes the password for the user. If a new recovery email address is specified, then the error EMAIL_UNCONFIRMED is returned and the password change will not be applied until the new recovery email address has been confirmed. The application should periodically call getPasswordState to check whether the new email address has been confirmed +// @param oldPassword Previous password of the user +// @param newPassword New password of the user; may be empty to remove the password +// @param newHint New password hint; may be empty +// @param setRecoveryEmailAddress Pass true if the recovery email address should be changed +// @param newRecoveryEmailAddress New recovery email address; may be empty +func (client *Client) SetPassword(oldPassword string, newPassword string, newHint string, setRecoveryEmailAddress bool, newRecoveryEmailAddress string) (*PasswordState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setPassword", + "old_password": oldPassword, + "new_password": newPassword, + "new_hint": newHint, + "set_recovery_email_address": setRecoveryEmailAddress, + "new_recovery_email_address": newRecoveryEmailAddress, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var passwordState PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// GetRecoveryEmailAddress Returns a recovery email address that was previously set up. This method can be used to verify a password provided by the user +// @param password The password for the current user +func (client *Client) GetRecoveryEmailAddress(password string) (*RecoveryEmailAddress, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getRecoveryEmailAddress", + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var recoveryEmailAddress RecoveryEmailAddress + err = json.Unmarshal(result.Raw, &recoveryEmailAddress) + return &recoveryEmailAddress, err + +} + +// SetRecoveryEmailAddress Changes the recovery email address of the user. If a new recovery email address is specified, then the error EMAIL_UNCONFIRMED is returned and the email address will not be changed until the new email has been confirmed. The application should periodically call getPasswordState to check whether the email address has been confirmed. +// @param password +// @param newRecoveryEmailAddress +func (client *Client) SetRecoveryEmailAddress(password string, newRecoveryEmailAddress string) (*PasswordState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setRecoveryEmailAddress", + "password": password, + "new_recovery_email_address": newRecoveryEmailAddress, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var passwordState PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// RequestPasswordRecovery Requests to send a password recovery code to an email address that was previously set up +func (client *Client) RequestPasswordRecovery() (*EmailAddressAuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "requestPasswordRecovery", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var emailAddressAuthenticationCodeInfo EmailAddressAuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &emailAddressAuthenticationCodeInfo) + return &emailAddressAuthenticationCodeInfo, err + +} + +// RecoverPassword Recovers the password using a recovery code sent to an email address that was previously set up +// @param recoveryCode Recovery code to check +func (client *Client) RecoverPassword(recoveryCode string) (*PasswordState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "recoverPassword", + "recovery_code": recoveryCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var passwordState PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// CreateTemporaryPassword Creates a new temporary password for processing payments +// @param password Persistent user password +// @param validFor Time during which the temporary password will be valid, in seconds; should be between 60 and 86400 +func (client *Client) CreateTemporaryPassword(password string, validFor int32) (*TemporaryPasswordState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createTemporaryPassword", + "password": password, + "valid_for": validFor, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var temporaryPasswordState TemporaryPasswordState + err = json.Unmarshal(result.Raw, &temporaryPasswordState) + return &temporaryPasswordState, err + +} + +// GetTemporaryPasswordState Returns information about the current temporary password +func (client *Client) GetTemporaryPasswordState() (*TemporaryPasswordState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getTemporaryPasswordState", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var temporaryPasswordState TemporaryPasswordState + err = json.Unmarshal(result.Raw, &temporaryPasswordState) + return &temporaryPasswordState, err + +} + +// ProcessDcUpdate Handles a DC_UPDATE push service notification. Can be called before authorization +// @param dc Value of the "dc" parameter of the notification +// @param addr Value of the "addr" parameter of the notification +func (client *Client) ProcessDcUpdate(dc string, addr string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "processDcUpdate", + "dc": dc, + "addr": addr, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetMe Returns the current user +func (client *Client) GetMe() (*User, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getMe", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var user User + err = json.Unmarshal(result.Raw, &user) + return &user, err + +} + +// GetUser Returns information about a user by their identifier. This is an offline request if the current user is not a bot +// @param userID User identifier +func (client *Client) GetUser(userID int32) (*User, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getUser", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var userDummy User + err = json.Unmarshal(result.Raw, &userDummy) + return &userDummy, err + +} + +// GetUserFullInfo Returns full information about a user by their identifier +// @param userID User identifier +func (client *Client) GetUserFullInfo(userID int32) (*UserFullInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getUserFullInfo", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var userFullInfo UserFullInfo + err = json.Unmarshal(result.Raw, &userFullInfo) + return &userFullInfo, err + +} + +// GetBasicGroup Returns information about a basic group by its identifier. This is an offline request if the current user is not a bot +// @param basicGroupID Basic group identifier +func (client *Client) GetBasicGroup(basicGroupID int32) (*BasicGroup, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getBasicGroup", + "basic_group_id": basicGroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var basicGroupDummy BasicGroup + err = json.Unmarshal(result.Raw, &basicGroupDummy) + return &basicGroupDummy, err + +} + +// GetBasicGroupFullInfo Returns full information about a basic group by its identifier +// @param basicGroupID Basic group identifier +func (client *Client) GetBasicGroupFullInfo(basicGroupID int32) (*BasicGroupFullInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getBasicGroupFullInfo", + "basic_group_id": basicGroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var basicGroupFullInfo BasicGroupFullInfo + err = json.Unmarshal(result.Raw, &basicGroupFullInfo) + return &basicGroupFullInfo, err + +} + +// GetSupergroup Returns information about a supergroup or channel by its identifier. This is an offline request if the current user is not a bot +// @param supergroupID Supergroup or channel identifier +func (client *Client) GetSupergroup(supergroupID int32) (*Supergroup, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getSupergroup", + "supergroup_id": supergroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var supergroupDummy Supergroup + err = json.Unmarshal(result.Raw, &supergroupDummy) + return &supergroupDummy, err + +} + +// GetSupergroupFullInfo Returns full information about a supergroup or channel by its identifier, cached for up to 1 minute +// @param supergroupID Supergroup or channel identifier +func (client *Client) GetSupergroupFullInfo(supergroupID int32) (*SupergroupFullInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getSupergroupFullInfo", + "supergroup_id": supergroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var supergroupFullInfo SupergroupFullInfo + err = json.Unmarshal(result.Raw, &supergroupFullInfo) + return &supergroupFullInfo, err + +} + +// GetSecretChat Returns information about a secret chat by its identifier. This is an offline request +// @param secretChatID Secret chat identifier +func (client *Client) GetSecretChat(secretChatID int32) (*SecretChat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getSecretChat", + "secret_chat_id": secretChatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var secretChatDummy SecretChat + err = json.Unmarshal(result.Raw, &secretChatDummy) + return &secretChatDummy, err + +} + +// GetChat Returns information about a chat by its identifier, this is an offline request if the current user is not a bot +// @param chatID Chat identifier +func (client *Client) GetChat(chatID int64) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatDummy Chat + err = json.Unmarshal(result.Raw, &chatDummy) + return &chatDummy, err + +} + +// GetMessage Returns information about a message +// @param chatID Identifier of the chat the message belongs to +// @param messageID Identifier of the message to get +func (client *Client) GetMessage(chatID int64, messageID int64) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getMessage", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// GetRepliedMessage Returns information about a message that is replied by given message +// @param chatID Identifier of the chat the message belongs to +// @param messageID Identifier of the message reply to which get +func (client *Client) GetRepliedMessage(chatID int64, messageID int64) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getRepliedMessage", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// GetChatPinnedMessage Returns information about a pinned chat message +// @param chatID Identifier of the chat the message belongs to +func (client *Client) GetChatPinnedMessage(chatID int64) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatPinnedMessage", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var message Message + err = json.Unmarshal(result.Raw, &message) + return &message, err + +} + +// GetMessages Returns information about messages. If a message is not found, returns null on the corresponding position of the result +// @param chatID Identifier of the chat the messages belong to +// @param messageIDs Identifiers of the messages to get +func (client *Client) GetMessages(chatID int64, messageIDs []int64) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getMessages", + "chat_id": chatID, + "message_ids": messageIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// GetFile Returns information about a file; this is an offline request +// @param fileID Identifier of the file to get +func (client *Client) GetFile(fileID int32) (*File, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getFile", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var fileDummy File + err = json.Unmarshal(result.Raw, &fileDummy) + return &fileDummy, err + +} + +// GetRemoteFile Returns information about a file by its remote ID; this is an offline request. Can be used to register a URL as a file for further uploading, or sending as a message +// @param remoteFileID Remote identifier of the file to get +// @param fileType File type, if known +func (client *Client) GetRemoteFile(remoteFileID string, fileType FileType) (*File, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getRemoteFile", + "remote_file_id": remoteFileID, + "file_type": fileType, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var fileDummy File + err = json.Unmarshal(result.Raw, &fileDummy) + return &fileDummy, err + +} + +// GetChats Returns an ordered list of chats. Chats are sorted by the pair (order, chat_id) in decreasing order. (For example, to get a list of chats from the beginning, the offset_order should be equal to 2^63 - 1). +// @param offsetOrder +// @param offsetChatID +// @param limit The maximum number of chats to be returned. It is possible that fewer chats than the limit are returned even if the end of the list is not reached +func (client *Client) GetChats(offsetOrder JSONInt64, offsetChatID int64, limit int32) (*Chats, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChats", + "offset_order": offsetOrder, + "offset_chat_id": offsetChatID, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chats Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// SearchPublicChat Searches a public chat by its username. Currently only private chats, supergroups and channels can be public. Returns the chat if found; otherwise an error is returned +// @param username Username to be resolved +func (client *Client) SearchPublicChat(username string) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchPublicChat", + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// SearchPublicChats Searches public chats by looking for specified query in their username and title. Currently only private chats, supergroups and channels can be public. Returns a meaningful number of results. Returns nothing if the length of the searched username prefix is less than 5. Excludes private chats with contacts and chats from the chat list from the results +// @param query Query to search for +func (client *Client) SearchPublicChats(query string) (*Chats, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchPublicChats", + "query": query, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chats Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// SearchChats Searches for the specified query in the title and username of already known chats, this is an offline request. Returns chats in the order seen in the chat list +// @param query Query to search for. If the query is empty, returns up to 20 recently found chats +// @param limit Maximum number of chats to be returned +func (client *Client) SearchChats(query string, limit int32) (*Chats, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchChats", + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chats Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// SearchChatsOnServer Searches for the specified query in the title and username of already known chats via request to the server. Returns chats in the order seen in the chat list +// @param query Query to search for +// @param limit Maximum number of chats to be returned +func (client *Client) SearchChatsOnServer(query string, limit int32) (*Chats, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchChatsOnServer", + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chats Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetTopChats Returns a list of frequently used chats. Supported only if the chat info database is enabled +// @param category Category of chats to be returned +// @param limit Maximum number of chats to be returned; up to 30 +func (client *Client) GetTopChats(category TopChatCategory, limit int32) (*Chats, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getTopChats", + "category": category, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chats Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// RemoveTopChat Removes a chat from the list of frequently used chats. Supported only if the chat info database is enabled +// @param category Category of frequently used chats +// @param chatID Chat identifier +func (client *Client) RemoveTopChat(category TopChatCategory, chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeTopChat", + "category": category, + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddRecentlyFoundChat Adds a chat to the list of recently found chats. The chat is added to the beginning of the list. If the chat is already in the list, it will be removed from the list first +// @param chatID Identifier of the chat to add +func (client *Client) AddRecentlyFoundChat(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addRecentlyFoundChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveRecentlyFoundChat Removes a chat from the list of recently found chats +// @param chatID Identifier of the chat to be removed +func (client *Client) RemoveRecentlyFoundChat(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeRecentlyFoundChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ClearRecentlyFoundChats Clears the list of recently found chats +func (client *Client) ClearRecentlyFoundChats() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "clearRecentlyFoundChats", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckChatUsername Checks whether a username can be set for a chat +// @param chatID Chat identifier; should be identifier of a supergroup chat, or a channel chat, or a private chat with self, or zero if chat is being created +// @param username Username to be checked +func (client *Client) CheckChatUsername(chatID JSONInt64, username string) (CheckChatUsernameResult, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkChatUsername", + "chat_id": chatID, + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + switch CheckChatUsernameResultEnum(result.Data["@type"].(string)) { + + case CheckChatUsernameResultOkType: + var checkChatUsernameResult CheckChatUsernameResultOk + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case CheckChatUsernameResultUsernameInvalidType: + var checkChatUsernameResult CheckChatUsernameResultUsernameInvalid + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case CheckChatUsernameResultUsernameOccupiedType: + var checkChatUsernameResult CheckChatUsernameResultUsernameOccupied + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case CheckChatUsernameResultPublicChatsTooMuchType: + var checkChatUsernameResult CheckChatUsernameResultPublicChatsTooMuch + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case CheckChatUsernameResultPublicGroupsUnavailableType: + var checkChatUsernameResult CheckChatUsernameResultPublicGroupsUnavailable + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// GetCreatedPublicChats Returns a list of public chats created by the user +func (client *Client) GetCreatedPublicChats() (*Chats, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getCreatedPublicChats", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chats Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetGroupsInCommon Returns a list of common chats with a given user. Chats are sorted by their type and creation date +// @param userID User identifier +// @param offsetChatID Chat identifier starting from which to return chats; use 0 for the first request +// @param limit Maximum number of chats to be returned; up to 100 +func (client *Client) GetGroupsInCommon(userID int32, offsetChatID int64, limit int32) (*Chats, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getGroupsInCommon", + "user_id": userID, + "offset_chat_id": offsetChatID, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chats Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetChatHistory Returns messages in a chat. The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id). +// @param chatID Chat identifier +// @param fromMessageID Identifier of the message starting from which history must be fetched; use 0 to get results from the last message +// @param offset Specify 0 to get results from exactly the from_message_id or a negative offset to get the specified message and some newer messages +// @param limit The maximum number of messages to be returned; must be positive and can't be greater than 100. If the offset is negative, the limit must be greater than -offset. Fewer messages may be returned than specified by the limit, even if the end of the message history has not been reached +// @param onlyLocal If true, returns only messages that are available locally without sending network requests +func (client *Client) GetChatHistory(chatID int64, fromMessageID int64, offset int32, limit int32, onlyLocal bool) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatHistory", + "chat_id": chatID, + "from_message_id": fromMessageID, + "offset": offset, + "limit": limit, + "only_local": onlyLocal, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// DeleteChatHistory Deletes all messages in the chat only for the user. Cannot be used in channels and public supergroups +// @param chatID Chat identifier +// @param removeFromChatList Pass true if the chat should be removed from the chats list +func (client *Client) DeleteChatHistory(chatID int64, removeFromChatList bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteChatHistory", + "chat_id": chatID, + "remove_from_chat_list": removeFromChatList, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SearchChatMessages Searches for messages with given words in the chat. Returns the results in reverse chronological order, i.e. in order of decreasing message_id. Cannot be used in secret chats with a non-empty query +// @param chatID Identifier of the chat in which to search messages +// @param query Query to search for +// @param senderUserID If not 0, only messages sent by the specified user will be returned. Not supported in secret chats +// @param fromMessageID Identifier of the message starting from which history must be fetched; use 0 to get results from the last message +// @param offset Specify 0 to get results from exactly the from_message_id or a negative offset to get the specified message and some newer messages +// @param limit The maximum number of messages to be returned; must be positive and can't be greater than 100. If the offset is negative, the limit must be greater than -offset. Fewer messages may be returned than specified by the limit, even if the end of the message history has not been reached +// @param filter Filter for message content in the search results +func (client *Client) SearchChatMessages(chatID int64, query string, senderUserID int32, fromMessageID int64, offset int32, limit int32, filter SearchMessagesFilter) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchChatMessages", + "chat_id": chatID, + "query": query, + "sender_user_id": senderUserID, + "from_message_id": fromMessageID, + "offset": offset, + "limit": limit, + "filter": filter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// SearchMessages Searches for messages in all chats except secret chats. Returns the results in reverse chronological order (i.e., in order of decreasing (date, chat_id, message_id)). +// @param query Query to search for +// @param offsetDate The date of the message starting from which the results should be fetched. Use 0 or any date in the future to get results from the last message +// @param offsetChatID The chat identifier of the last found message, or 0 for the first request +// @param offsetMessageID The message identifier of the last found message, or 0 for the first request +// @param limit The maximum number of messages to be returned, up to 100. Fewer messages may be returned than specified by the limit, even if the end of the message history has not been reached +func (client *Client) SearchMessages(query string, offsetDate int32, offsetChatID int64, offsetMessageID int64, limit int32) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchMessages", + "query": query, + "offset_date": offsetDate, + "offset_chat_id": offsetChatID, + "offset_message_id": offsetMessageID, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// SearchSecretMessages Searches for messages in secret chats. Returns the results in reverse chronological order. For optimal performance the number of returned messages is chosen by the library +// @param chatID Identifier of the chat in which to search. Specify 0 to search in all secret chats +// @param query Query to search for. If empty, searchChatMessages should be used instead +// @param fromSearchID The identifier from the result of a previous request, use 0 to get results from the last message +// @param limit Maximum number of messages to be returned; up to 100. Fewer messages may be returned than specified by the limit, even if the end of the message history has not been reached +// @param filter A filter for the content of messages in the search results +func (client *Client) SearchSecretMessages(chatID int64, query string, fromSearchID JSONInt64, limit int32, filter SearchMessagesFilter) (*FoundMessages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchSecretMessages", + "chat_id": chatID, + "query": query, + "from_search_id": fromSearchID, + "limit": limit, + "filter": filter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var foundMessages FoundMessages + err = json.Unmarshal(result.Raw, &foundMessages) + return &foundMessages, err + +} + +// SearchCallMessages Searches for call messages. Returns the results in reverse chronological order (i. e., in order of decreasing message_id). For optimal performance the number of returned messages is chosen by the library +// @param fromMessageID Identifier of the message from which to search; use 0 to get results from the last message +// @param limit The maximum number of messages to be returned; up to 100. Fewer messages may be returned than specified by the limit, even if the end of the message history has not been reached +// @param onlyMissed If true, returns only messages with missed calls +func (client *Client) SearchCallMessages(fromMessageID int64, limit int32, onlyMissed bool) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchCallMessages", + "from_message_id": fromMessageID, + "limit": limit, + "only_missed": onlyMissed, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// SearchChatRecentLocationMessages Returns information about the recent locations of chat members that were sent to the chat. Returns up to 1 location message per user +// @param chatID Chat identifier +// @param limit Maximum number of messages to be returned +func (client *Client) SearchChatRecentLocationMessages(chatID int64, limit int32) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchChatRecentLocationMessages", + "chat_id": chatID, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// GetActiveLiveLocationMessages Returns all active live locations that should be updated by the client. The list is persistent across application restarts only if the message database is used +func (client *Client) GetActiveLiveLocationMessages() (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getActiveLiveLocationMessages", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// GetChatMessageByDate Returns the last message sent in a chat no later than the specified date +// @param chatID Chat identifier +// @param date Point in time (Unix timestamp) relative to which to search for messages +func (client *Client) GetChatMessageByDate(chatID int64, date int32) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatMessageByDate", + "chat_id": chatID, + "date": date, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var message Message + err = json.Unmarshal(result.Raw, &message) + return &message, err + +} + +// GetChatMessageCount Returns approximate number of messages of the specified type in the chat +// @param chatID Identifier of the chat in which to count messages +// @param filter Filter for message content; searchMessagesFilterEmpty is unsupported in this function +// @param returnLocal If true, returns count that is available locally without sending network requests, returning -1 if the number of messages is unknown +func (client *Client) GetChatMessageCount(chatID int64, filter SearchMessagesFilter, returnLocal bool) (*Count, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatMessageCount", + "chat_id": chatID, + "filter": filter, + "return_local": returnLocal, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var count Count + err = json.Unmarshal(result.Raw, &count) + return &count, err + +} + +// GetPublicMessageLink Returns a public HTTPS link to a message. Available only for messages in public supergroups and channels +// @param chatID Identifier of the chat to which the message belongs +// @param messageID Identifier of the message +// @param forAlbum Pass true if a link for a whole media album should be returned +func (client *Client) GetPublicMessageLink(chatID int64, messageID int64, forAlbum bool) (*PublicMessageLink, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getPublicMessageLink", + "chat_id": chatID, + "message_id": messageID, + "for_album": forAlbum, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var publicMessageLink PublicMessageLink + err = json.Unmarshal(result.Raw, &publicMessageLink) + return &publicMessageLink, err + +} + +// SendMessage Sends a message. Returns the sent message +// @param chatID Target chat +// @param replyToMessageID Identifier of the message to reply to or 0 +// @param disableNotification Pass true to disable notification for the message. Not supported in secret chats +// @param fromBackground Pass true if the message is sent from the background +// @param replyMarkup Markup for replying to the message; for bots only +// @param inputMessageContent The content of the message to be sent +func (client *Client) SendMessage(chatID int64, replyToMessageID int64, disableNotification bool, fromBackground bool, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendMessage", + "chat_id": chatID, + "reply_to_message_id": replyToMessageID, + "disable_notification": disableNotification, + "from_background": fromBackground, + "reply_markup": replyMarkup, + "input_message_content": inputMessageContent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// SendMessageAlbum Sends messages grouped together into an album. Currently only photo and video messages can be grouped into an album. Returns sent messages +// @param chatID Target chat +// @param replyToMessageID Identifier of a message to reply to or 0 +// @param disableNotification Pass true to disable notification for the messages. Not supported in secret chats +// @param fromBackground Pass true if the messages are sent from the background +// @param inputMessageContents Contents of messages to be sent +func (client *Client) SendMessageAlbum(chatID int64, replyToMessageID int64, disableNotification bool, fromBackground bool, inputMessageContents []InputMessageContent) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendMessageAlbum", + "chat_id": chatID, + "reply_to_message_id": replyToMessageID, + "disable_notification": disableNotification, + "from_background": fromBackground, + "input_message_contents": inputMessageContents, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// SendBotStartMessage Invites a bot to a chat (if it is not yet a member) and sends it the /start command. Bots can't be invited to a private chat other than the chat with the bot. Bots can't be invited to channels (although they can be added as admins) and secret chats. Returns the sent message +// @param botUserID Identifier of the bot +// @param chatID Identifier of the target chat +// @param parameter A hidden parameter sent to the bot for deep linking purposes (https://api.telegram.org/bots#deep-linking) +func (client *Client) SendBotStartMessage(botUserID int32, chatID int64, parameter string) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendBotStartMessage", + "bot_user_id": botUserID, + "chat_id": chatID, + "parameter": parameter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var message Message + err = json.Unmarshal(result.Raw, &message) + return &message, err + +} + +// SendInlineQueryResultMessage Sends the result of an inline query as a message. Returns the sent message. Always clears a chat draft message +// @param chatID Target chat +// @param replyToMessageID Identifier of a message to reply to or 0 +// @param disableNotification Pass true to disable notification for the message. Not supported in secret chats +// @param fromBackground Pass true if the message is sent from background +// @param queryID Identifier of the inline query +// @param resultID Identifier of the inline result +func (client *Client) SendInlineQueryResultMessage(chatID int64, replyToMessageID int64, disableNotification bool, fromBackground bool, queryID JSONInt64, resultID string) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendInlineQueryResultMessage", + "chat_id": chatID, + "reply_to_message_id": replyToMessageID, + "disable_notification": disableNotification, + "from_background": fromBackground, + "query_id": queryID, + "result_id": resultID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// ForwardMessages Forwards previously sent messages. Returns the forwarded messages in the same order as the message identifiers passed in message_ids. If a message can't be forwarded, null will be returned instead of the message +// @param chatID Identifier of the chat to which to forward messages +// @param fromChatID Identifier of the chat from which to forward messages +// @param messageIDs Identifiers of the messages to forward +// @param disableNotification Pass true to disable notification for the message, doesn't work if messages are forwarded to a secret chat +// @param fromBackground Pass true if the message is sent from the background +// @param asAlbum True, if the messages should be grouped into an album after forwarding. For this to work, no more than 10 messages may be forwarded, and all of them must be photo or video messages +func (client *Client) ForwardMessages(chatID int64, fromChatID int64, messageIDs []int64, disableNotification bool, fromBackground bool, asAlbum bool) (*Messages, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "forwardMessages", + "chat_id": chatID, + "from_chat_id": fromChatID, + "message_ids": messageIDs, + "disable_notification": disableNotification, + "from_background": fromBackground, + "as_album": asAlbum, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messages Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// SendChatSetTTLMessage Changes the current TTL setting (sets a new self-destruct timer) in a secret chat and sends the corresponding message +// @param chatID Chat identifier +// @param tTL New TTL value, in seconds +func (client *Client) SendChatSetTTLMessage(chatID int64, tTL int32) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendChatSetTtlMessage", + "chat_id": chatID, + "ttl": tTL, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var message Message + err = json.Unmarshal(result.Raw, &message) + return &message, err + +} + +// SendChatScreenshotTakenNotification Sends a notification about a screenshot taken in a chat. Supported only in private and secret chats +// @param chatID Chat identifier +func (client *Client) SendChatScreenshotTakenNotification(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendChatScreenshotTakenNotification", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddLocalMessage Adds a local message to a chat. The message is persistent across application restarts only if the message database is used. Returns the added message +// @param chatID Target chat +// @param senderUserID Identifier of the user who will be shown as the sender of the message; may be 0 for channel posts +// @param replyToMessageID Identifier of the message to reply to or 0 +// @param disableNotification Pass true to disable notification for the message +// @param inputMessageContent The content of the message to be added +func (client *Client) AddLocalMessage(chatID int64, senderUserID int32, replyToMessageID int64, disableNotification bool, inputMessageContent InputMessageContent) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addLocalMessage", + "chat_id": chatID, + "sender_user_id": senderUserID, + "reply_to_message_id": replyToMessageID, + "disable_notification": disableNotification, + "input_message_content": inputMessageContent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// DeleteMessages Deletes messages +// @param chatID Chat identifier +// @param messageIDs Identifiers of the messages to be deleted +// @param revoke Pass true to try to delete outgoing messages for all chat members (may fail if messages are too old). Always true for supergroups, channels and secret chats +func (client *Client) DeleteMessages(chatID int64, messageIDs []int64, revoke bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteMessages", + "chat_id": chatID, + "message_ids": messageIDs, + "revoke": revoke, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var okDummy Ok + err = json.Unmarshal(result.Raw, &okDummy) + return &okDummy, err + +} + +// DeleteChatMessagesFromUser Deletes all messages sent by the specified user to a chat. Supported only in supergroups; requires can_delete_messages administrator privileges +// @param chatID Chat identifier +// @param userID User identifier +func (client *Client) DeleteChatMessagesFromUser(chatID int64, userID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteChatMessagesFromUser", + "chat_id": chatID, + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditMessageText Edits the text of a message (or a text of a game message). Returns the edited message after the edit is completed on the server side +// @param chatID The chat the message belongs to +// @param messageID Identifier of the message +// @param replyMarkup The new message reply markup; for bots only +// @param inputMessageContent New text content of the message. Should be of type InputMessageText +func (client *Client) EditMessageText(chatID int64, messageID int64, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editMessageText", + "chat_id": chatID, + "message_id": messageID, + "reply_markup": replyMarkup, + "input_message_content": inputMessageContent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// EditMessageLiveLocation Edits the message content of a live location. Messages can be edited for a limited period of time specified in the live location. Returns the edited message after the edit is completed on the server side +// @param chatID The chat the message belongs to +// @param messageID Identifier of the message +// @param replyMarkup The new message reply markup; for bots only +// @param location New location content of the message; may be null. Pass null to stop sharing the live location +func (client *Client) EditMessageLiveLocation(chatID int64, messageID int64, replyMarkup ReplyMarkup, location *Location) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editMessageLiveLocation", + "chat_id": chatID, + "message_id": messageID, + "reply_markup": replyMarkup, + "location": location, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// EditMessageMedia Edits the content of a message with an animation, an audio, a document, a photo or a video. The media in the message can't be replaced if the message was set to self-destruct. Media can't be replaced by self-destructing media. Media in an album can be edited only to contain a photo or a video. Returns the edited message after the edit is completed on the server side +// @param chatID The chat the message belongs to +// @param messageID Identifier of the message +// @param replyMarkup The new message reply markup; for bots only +// @param inputMessageContent New content of the message. Must be one of the following types: InputMessageAnimation, InputMessageAudio, InputMessageDocument, InputMessagePhoto or InputMessageVideo +func (client *Client) EditMessageMedia(chatID int64, messageID int64, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editMessageMedia", + "chat_id": chatID, + "message_id": messageID, + "reply_markup": replyMarkup, + "input_message_content": inputMessageContent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// EditMessageCaption Edits the message content caption. Returns the edited message after the edit is completed on the server side +// @param chatID The chat the message belongs to +// @param messageID Identifier of the message +// @param replyMarkup The new message reply markup; for bots only +// @param caption New message content caption; 0-GetOption("message_caption_length_max") characters +func (client *Client) EditMessageCaption(chatID int64, messageID int64, replyMarkup ReplyMarkup, caption *FormattedText) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editMessageCaption", + "chat_id": chatID, + "message_id": messageID, + "reply_markup": replyMarkup, + "caption": caption, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// EditMessageReplyMarkup Edits the message reply markup; for bots only. Returns the edited message after the edit is completed on the server side +// @param chatID The chat the message belongs to +// @param messageID Identifier of the message +// @param replyMarkup The new message reply markup +func (client *Client) EditMessageReplyMarkup(chatID int64, messageID int64, replyMarkup ReplyMarkup) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editMessageReplyMarkup", + "chat_id": chatID, + "message_id": messageID, + "reply_markup": replyMarkup, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// EditInlineMessageText Edits the text of an inline text or game message sent via a bot; for bots only +// @param inlineMessageID Inline message identifier +// @param replyMarkup The new message reply markup +// @param inputMessageContent New text content of the message. Should be of type InputMessageText +func (client *Client) EditInlineMessageText(inlineMessageID string, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editInlineMessageText", + "inline_message_id": inlineMessageID, + "reply_markup": replyMarkup, + "input_message_content": inputMessageContent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditInlineMessageLiveLocation Edits the content of a live location in an inline message sent via a bot; for bots only +// @param inlineMessageID Inline message identifier +// @param replyMarkup The new message reply markup +// @param location New location content of the message; may be null. Pass null to stop sharing the live location +func (client *Client) EditInlineMessageLiveLocation(inlineMessageID string, replyMarkup ReplyMarkup, location *Location) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editInlineMessageLiveLocation", + "inline_message_id": inlineMessageID, + "reply_markup": replyMarkup, + "location": location, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditInlineMessageMedia Edits the content of a message with an animation, an audio, a document, a photo or a video in an inline message sent via a bot; for bots only +// @param inlineMessageID Inline message identifier +// @param replyMarkup The new message reply markup; for bots only +// @param inputMessageContent New content of the message. Must be one of the following types: InputMessageAnimation, InputMessageAudio, InputMessageDocument, InputMessagePhoto or InputMessageVideo +func (client *Client) EditInlineMessageMedia(inlineMessageID string, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editInlineMessageMedia", + "inline_message_id": inlineMessageID, + "reply_markup": replyMarkup, + "input_message_content": inputMessageContent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditInlineMessageCaption Edits the caption of an inline message sent via a bot; for bots only +// @param inlineMessageID Inline message identifier +// @param replyMarkup The new message reply markup +// @param caption New message content caption; 0-GetOption("message_caption_length_max") characters +func (client *Client) EditInlineMessageCaption(inlineMessageID string, replyMarkup ReplyMarkup, caption *FormattedText) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editInlineMessageCaption", + "inline_message_id": inlineMessageID, + "reply_markup": replyMarkup, + "caption": caption, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditInlineMessageReplyMarkup Edits the reply markup of an inline message sent via a bot; for bots only +// @param inlineMessageID Inline message identifier +// @param replyMarkup The new message reply markup +func (client *Client) EditInlineMessageReplyMarkup(inlineMessageID string, replyMarkup ReplyMarkup) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editInlineMessageReplyMarkup", + "inline_message_id": inlineMessageID, + "reply_markup": replyMarkup, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetTextEntities Returns all entities (mentions, hashtags, cashtags, bot commands, URLs, and email addresses) contained in the text. This is an offline method. Can be called before authorization. Can be called synchronously +// @param text The text in which to look for entites +func (client *Client) GetTextEntities(text string) (*TextEntities, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getTextEntities", + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var textEntities TextEntities + err = json.Unmarshal(result.Raw, &textEntities) + return &textEntities, err + +} + +// ParseTextEntities Parses Bold, Italic, Code, Pre, PreCode and TextUrl entities contained in the text. This is an offline method. Can be called before authorization. Can be called synchronously +// @param text The text which should be parsed +// @param parseMode Text parse mode +func (client *Client) ParseTextEntities(text string, parseMode TextParseMode) (*FormattedText, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "parseTextEntities", + "text": text, + "parse_mode": parseMode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var formattedText FormattedText + err = json.Unmarshal(result.Raw, &formattedText) + return &formattedText, err + +} + +// GetFileMimeType Returns the MIME type of a file, guessed by its extension. Returns an empty string on failure. This is an offline method. Can be called before authorization. Can be called synchronously +// @param fileName The name of the file or path to the file +func (client *Client) GetFileMimeType(fileName string) (*Text, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getFileMimeType", + "file_name": fileName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var text Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetFileExtension Returns the extension of a file, guessed by its MIME type. Returns an empty string on failure. This is an offline method. Can be called before authorization. Can be called synchronously +// @param mimeType The MIME type of the file +func (client *Client) GetFileExtension(mimeType string) (*Text, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getFileExtension", + "mime_type": mimeType, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var text Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// CleanFileName Removes potentially dangerous characters from the name of a file. The encoding of the file name is supposed to be UTF-8. Returns an empty string on failure. This is an offline method. Can be called before authorization. Can be called synchronously +// @param fileName File name or path to the file +func (client *Client) CleanFileName(fileName string) (*Text, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "cleanFileName", + "file_name": fileName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var text Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetLanguagePackString Returns a string stored in the local database from the specified localization target and language pack by its key. Returns a 404 error if the string is not found. This is an offline method. Can be called before authorization. Can be called synchronously +// @param languagePackDatabasePath Path to the language pack database in which strings are stored +// @param localizationTarget Localization target to which the language pack belongs +// @param languagePackID Language pack identifier +// @param key Language pack key of the string to be returned +func (client *Client) GetLanguagePackString(languagePackDatabasePath string, localizationTarget string, languagePackID string, key string) (LanguagePackStringValue, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getLanguagePackString", + "language_pack_database_path": languagePackDatabasePath, + "localization_target": localizationTarget, + "language_pack_id": languagePackID, + "key": key, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + switch LanguagePackStringValueEnum(result.Data["@type"].(string)) { + + case LanguagePackStringValueOrdinaryType: + var languagePackStringValue LanguagePackStringValueOrdinary + err = json.Unmarshal(result.Raw, &languagePackStringValue) + return &languagePackStringValue, err + + case LanguagePackStringValuePluralizedType: + var languagePackStringValue LanguagePackStringValuePluralized + err = json.Unmarshal(result.Raw, &languagePackStringValue) + return &languagePackStringValue, err + + case LanguagePackStringValueDeletedType: + var languagePackStringValue LanguagePackStringValueDeleted + err = json.Unmarshal(result.Raw, &languagePackStringValue) + return &languagePackStringValue, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// GetInlineQueryResults Sends an inline query to a bot and returns its results. Returns an error with code 502 if the bot fails to answer the query before the query timeout expires +// @param botUserID The identifier of the target bot +// @param chatID Identifier of the chat, where the query was sent +// @param userLocation Location of the user, only if needed +// @param query Text of the query +// @param offset Offset of the first entry to return +func (client *Client) GetInlineQueryResults(botUserID int32, chatID int64, userLocation *Location, query string, offset string) (*InlineQueryResults, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getInlineQueryResults", + "bot_user_id": botUserID, + "chat_id": chatID, + "user_location": userLocation, + "query": query, + "offset": offset, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var inlineQueryResults InlineQueryResults + err = json.Unmarshal(result.Raw, &inlineQueryResults) + return &inlineQueryResults, err + +} + +// AnswerInlineQuery Sets the result of an inline query; for bots only +// @param inlineQueryID Identifier of the inline query +// @param isPersonal True, if the result of the query can be cached for the specified user +// @param results The results of the query +// @param cacheTime Allowed time to cache the results of the query, in seconds +// @param nextOffset Offset for the next inline query; pass an empty string if there are no more results +// @param switchPmText If non-empty, this text should be shown on the button that opens a private chat with the bot and sends a start message to the bot with the parameter switch_pm_parameter +// @param switchPmParameter The parameter for the bot start message +func (client *Client) AnswerInlineQuery(inlineQueryID JSONInt64, isPersonal bool, results []InputInlineQueryResult, cacheTime int32, nextOffset string, switchPmText string, switchPmParameter string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "answerInlineQuery", + "inline_query_id": inlineQueryID, + "is_personal": isPersonal, + "results": results, + "cache_time": cacheTime, + "next_offset": nextOffset, + "switch_pm_text": switchPmText, + "switch_pm_parameter": switchPmParameter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetCallbackQueryAnswer Sends a callback query to a bot and returns an answer. Returns an error with code 502 if the bot fails to answer the query before the query timeout expires +// @param chatID Identifier of the chat with the message +// @param messageID Identifier of the message from which the query originated +// @param payload Query payload +func (client *Client) GetCallbackQueryAnswer(chatID int64, messageID int64, payload CallbackQueryPayload) (*CallbackQueryAnswer, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getCallbackQueryAnswer", + "chat_id": chatID, + "message_id": messageID, + "payload": payload, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var callbackQueryAnswer CallbackQueryAnswer + err = json.Unmarshal(result.Raw, &callbackQueryAnswer) + return &callbackQueryAnswer, err + +} + +// AnswerCallbackQuery Sets the result of a callback query; for bots only +// @param callbackQueryID Identifier of the callback query +// @param text Text of the answer +// @param showAlert If true, an alert should be shown to the user instead of a toast notification +// @param uRL URL to be opened +// @param cacheTime Time during which the result of the query can be cached, in seconds +func (client *Client) AnswerCallbackQuery(callbackQueryID JSONInt64, text string, showAlert bool, uRL string, cacheTime int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "answerCallbackQuery", + "callback_query_id": callbackQueryID, + "text": text, + "show_alert": showAlert, + "url": uRL, + "cache_time": cacheTime, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AnswerShippingQuery Sets the result of a shipping query; for bots only +// @param shippingQueryID Identifier of the shipping query +// @param shippingOptions Available shipping options +// @param errorMessage An error message, empty on success +func (client *Client) AnswerShippingQuery(shippingQueryID JSONInt64, shippingOptions []ShippingOption, errorMessage string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "answerShippingQuery", + "shipping_query_id": shippingQueryID, + "shipping_options": shippingOptions, + "error_message": errorMessage, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AnswerPreCheckoutQuery Sets the result of a pre-checkout query; for bots only +// @param preCheckoutQueryID Identifier of the pre-checkout query +// @param errorMessage An error message, empty on success +func (client *Client) AnswerPreCheckoutQuery(preCheckoutQueryID JSONInt64, errorMessage string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "answerPreCheckoutQuery", + "pre_checkout_query_id": preCheckoutQueryID, + "error_message": errorMessage, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetGameScore Updates the game score of the specified user in the game; for bots only +// @param chatID The chat to which the message with the game +// @param messageID Identifier of the message +// @param editMessage True, if the message should be edited +// @param userID User identifier +// @param score The new score +// @param force Pass true to update the score even if it decreases. If the score is 0, the user will be deleted from the high score table +func (client *Client) SetGameScore(chatID int64, messageID int64, editMessage bool, userID int32, score int32, force bool) (*Message, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setGameScore", + "chat_id": chatID, + "message_id": messageID, + "edit_message": editMessage, + "user_id": userID, + "score": score, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var messageDummy Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// SetInlineGameScore Updates the game score of the specified user in a game; for bots only +// @param inlineMessageID Inline message identifier +// @param editMessage True, if the message should be edited +// @param userID User identifier +// @param score The new score +// @param force Pass true to update the score even if it decreases. If the score is 0, the user will be deleted from the high score table +func (client *Client) SetInlineGameScore(inlineMessageID string, editMessage bool, userID int32, score int32, force bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setInlineGameScore", + "inline_message_id": inlineMessageID, + "edit_message": editMessage, + "user_id": userID, + "score": score, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetGameHighScores Returns the high scores for a game and some part of the high score table in the range of the specified user; for bots only +// @param chatID The chat that contains the message with the game +// @param messageID Identifier of the message +// @param userID User identifier +func (client *Client) GetGameHighScores(chatID int64, messageID int64, userID int32) (*GameHighScores, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getGameHighScores", + "chat_id": chatID, + "message_id": messageID, + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var gameHighScores GameHighScores + err = json.Unmarshal(result.Raw, &gameHighScores) + return &gameHighScores, err + +} + +// GetInlineGameHighScores Returns game high scores and some part of the high score table in the range of the specified user; for bots only +// @param inlineMessageID Inline message identifier +// @param userID User identifier +func (client *Client) GetInlineGameHighScores(inlineMessageID string, userID int32) (*GameHighScores, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getInlineGameHighScores", + "inline_message_id": inlineMessageID, + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var gameHighScores GameHighScores + err = json.Unmarshal(result.Raw, &gameHighScores) + return &gameHighScores, err + +} + +// DeleteChatReplyMarkup Deletes the default reply markup from a chat. Must be called after a one-time keyboard or a ForceReply reply markup has been used. UpdateChatReplyMarkup will be sent if the reply markup will be changed +// @param chatID Chat identifier +// @param messageID The message identifier of the used keyboard +func (client *Client) DeleteChatReplyMarkup(chatID int64, messageID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteChatReplyMarkup", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendChatAction Sends a notification about user activity in a chat +// @param chatID Chat identifier +// @param action The action description +func (client *Client) SendChatAction(chatID int64, action ChatAction) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendChatAction", + "chat_id": chatID, + "action": action, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// OpenChat This method should be called if the chat is opened by the user. Many useful activities depend on the chat being opened or closed (e.g., in supergroups and channels all updates are received only for opened chats) +// @param chatID Chat identifier +func (client *Client) OpenChat(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "openChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CloseChat This method should be called if the chat is closed by the user. Many useful activities depend on the chat being opened or closed +// @param chatID Chat identifier +func (client *Client) CloseChat(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "closeChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ViewMessages This method should be called if messages are being viewed by the user. Many useful activities depend on whether the messages are currently being viewed or not (e.g., marking messages as read, incrementing a view counter, updating a view counter, removing deleted messages in supergroups and channels) +// @param chatID Chat identifier +// @param messageIDs The identifiers of the messages being viewed +// @param forceRead True, if messages in closed chats should be marked as read +func (client *Client) ViewMessages(chatID int64, messageIDs []int64, forceRead bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "viewMessages", + "chat_id": chatID, + "message_ids": messageIDs, + "force_read": forceRead, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// OpenMessageContent This method should be called if the message content has been opened (e.g., the user has opened a photo, video, document, location or venue, or has listened to an audio file or voice note message). An updateMessageContentOpened update will be generated if something has changed +// @param chatID Chat identifier of the message +// @param messageID Identifier of the message with the opened content +func (client *Client) OpenMessageContent(chatID int64, messageID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "openMessageContent", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ReadAllChatMentions Marks all mentions in a chat as read +// @param chatID Chat identifier +func (client *Client) ReadAllChatMentions(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "readAllChatMentions", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CreatePrivateChat Returns an existing chat corresponding to a given user +// @param userID User identifier +// @param force If true, the chat will be created without network request. In this case all information about the chat except its type, title and photo can be incorrect +func (client *Client) CreatePrivateChat(userID int32, force bool) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createPrivateChat", + "user_id": userID, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// CreateBasicGroupChat Returns an existing chat corresponding to a known basic group +// @param basicGroupID Basic group identifier +// @param force If true, the chat will be created without network request. In this case all information about the chat except its type, title and photo can be incorrect +func (client *Client) CreateBasicGroupChat(basicGroupID int32, force bool) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createBasicGroupChat", + "basic_group_id": basicGroupID, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// CreateSupergroupChat Returns an existing chat corresponding to a known supergroup or channel +// @param supergroupID Supergroup or channel identifier +// @param force If true, the chat will be created without network request. In this case all information about the chat except its type, title and photo can be incorrect +func (client *Client) CreateSupergroupChat(supergroupID int32, force bool) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createSupergroupChat", + "supergroup_id": supergroupID, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// CreateSecretChat Returns an existing chat corresponding to a known secret chat +// @param secretChatID Secret chat identifier +func (client *Client) CreateSecretChat(secretChatID int32) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createSecretChat", + "secret_chat_id": secretChatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatDummy Chat + err = json.Unmarshal(result.Raw, &chatDummy) + return &chatDummy, err + +} + +// CreateNewBasicGroupChat Creates a new basic group and sends a corresponding messageBasicGroupChatCreate. Returns the newly created chat +// @param userIDs Identifiers of users to be added to the basic group +// @param title Title of the new basic group; 1-255 characters +func (client *Client) CreateNewBasicGroupChat(userIDs []int32, title string) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createNewBasicGroupChat", + "user_ids": userIDs, + "title": title, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// CreateNewSupergroupChat Creates a new supergroup or channel and sends a corresponding messageSupergroupChatCreate. Returns the newly created chat +// @param title Title of the new chat; 1-255 characters +// @param isChannel True, if a channel chat should be created +// @param description +func (client *Client) CreateNewSupergroupChat(title string, isChannel bool, description string) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createNewSupergroupChat", + "title": title, + "is_channel": isChannel, + "description": description, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// CreateNewSecretChat Creates a new secret chat. Returns the newly created chat +// @param userID Identifier of the target user +func (client *Client) CreateNewSecretChat(userID int32) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createNewSecretChat", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// UpgradeBasicGroupChatToSupergroupChat Creates a new supergroup from an existing basic group and sends a corresponding messageChatUpgradeTo and messageChatUpgradeFrom. Deactivates the original basic group +// @param chatID Identifier of the chat to upgrade +func (client *Client) UpgradeBasicGroupChatToSupergroupChat(chatID int64) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "upgradeBasicGroupChatToSupergroupChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatDummy Chat + err = json.Unmarshal(result.Raw, &chatDummy) + return &chatDummy, err + +} + +// SetChatTitle Changes the chat title. Supported only for basic groups, supergroups and channels. Requires administrator rights in basic groups and the appropriate administrator rights in supergroups and channels. The title will not be changed until the request to the server has been completed +// @param chatID Chat identifier +// @param title New title of the chat; 1-255 characters +func (client *Client) SetChatTitle(chatID int64, title string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setChatTitle", + "chat_id": chatID, + "title": title, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatPhoto Changes the photo of a chat. Supported only for basic groups, supergroups and channels. Requires administrator rights in basic groups and the appropriate administrator rights in supergroups and channels. The photo will not be changed before request to the server has been completed +// @param chatID Chat identifier +// @param photo New chat photo. You can use a zero InputFileId to delete the chat photo. Files that are accessible only by HTTP URL are not acceptable +func (client *Client) SetChatPhoto(chatID int64, photo InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setChatPhoto", + "chat_id": chatID, + "photo": photo, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatDraftMessage Changes the draft message in a chat +// @param chatID Chat identifier +// @param draftMessage New draft message; may be null +func (client *Client) SetChatDraftMessage(chatID int64, draftMessage *DraftMessage) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setChatDraftMessage", + "chat_id": chatID, + "draft_message": draftMessage, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatNotificationSettings Changes the notification settings of a chat +// @param chatID Chat identifier +// @param notificationSettings New notification settings for the chat +func (client *Client) SetChatNotificationSettings(chatID int64, notificationSettings *ChatNotificationSettings) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setChatNotificationSettings", + "chat_id": chatID, + "notification_settings": notificationSettings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleChatIsPinned Changes the pinned state of a chat. You can pin up to GetOption("pinned_chat_count_max") non-secret chats and the same number of secret chats +// @param chatID Chat identifier +// @param isPinned New value of is_pinned +func (client *Client) ToggleChatIsPinned(chatID int64, isPinned bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "toggleChatIsPinned", + "chat_id": chatID, + "is_pinned": isPinned, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleChatIsMarkedAsUnread Changes the marked as unread state of a chat +// @param chatID Chat identifier +// @param isMarkedAsUnread New value of is_marked_as_unread +func (client *Client) ToggleChatIsMarkedAsUnread(chatID int64, isMarkedAsUnread bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "toggleChatIsMarkedAsUnread", + "chat_id": chatID, + "is_marked_as_unread": isMarkedAsUnread, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleChatDefaultDisableNotification Changes the value of the default disable_notification parameter, used when a message is sent to a chat +// @param chatID Chat identifier +// @param defaultDisableNotification New value of default_disable_notification +func (client *Client) ToggleChatDefaultDisableNotification(chatID int64, defaultDisableNotification bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "toggleChatDefaultDisableNotification", + "chat_id": chatID, + "default_disable_notification": defaultDisableNotification, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatClientData Changes client data associated with a chat +// @param chatID Chat identifier +// @param clientData New value of client_data +func (client *Client) SetChatClientData(chatID int64, clientData string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setChatClientData", + "chat_id": chatID, + "client_data": clientData, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// JoinChat Adds current user as a new member to a chat. Private and secret chats can't be joined using this method +// @param chatID Chat identifier +func (client *Client) JoinChat(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "joinChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// LeaveChat Removes current user from chat members. Private and secret chats can't be left using this method +// @param chatID Chat identifier +func (client *Client) LeaveChat(chatID int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "leaveChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddChatMember Adds a new member to a chat. Members can't be added to private or secret chats. Members will not be added until the chat state has been synchronized with the server +// @param chatID Chat identifier +// @param userID Identifier of the user +// @param forwardLimit The number of earlier messages from the chat to be forwarded to the new member; up to 300. Ignored for supergroups and channels +func (client *Client) AddChatMember(chatID int64, userID int32, forwardLimit int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addChatMember", + "chat_id": chatID, + "user_id": userID, + "forward_limit": forwardLimit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddChatMembers Adds multiple new members to a chat. Currently this option is only available for supergroups and channels. This option can't be used to join a chat. Members can't be added to a channel if it has more than 200 members. Members will not be added until the chat state has been synchronized with the server +// @param chatID Chat identifier +// @param userIDs Identifiers of the users to be added to the chat +func (client *Client) AddChatMembers(chatID int64, userIDs []int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addChatMembers", + "chat_id": chatID, + "user_ids": userIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatMemberStatus Changes the status of a chat member, needs appropriate privileges. This function is currently not suitable for adding new members to the chat; instead, use addChatMember. The chat member status will not be changed until it has been synchronized with the server +// @param chatID Chat identifier +// @param userID User identifier +// @param status The new status of the member in the chat +func (client *Client) SetChatMemberStatus(chatID int64, userID int32, status ChatMemberStatus) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setChatMemberStatus", + "chat_id": chatID, + "user_id": userID, + "status": status, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetChatMember Returns information about a single member of a chat +// @param chatID Chat identifier +// @param userID User identifier +func (client *Client) GetChatMember(chatID int64, userID int32) (*ChatMember, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatMember", + "chat_id": chatID, + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatMember ChatMember + err = json.Unmarshal(result.Raw, &chatMember) + return &chatMember, err + +} + +// SearchChatMembers Searches for a specified query in the first name, last name and username of the members of a specified chat. Requires administrator rights in channels +// @param chatID Chat identifier +// @param query Query to search for +// @param limit The maximum number of users to be returned +// @param filter The type of users to return. By default, chatMembersFilterMembers +func (client *Client) SearchChatMembers(chatID int64, query string, limit int32, filter ChatMembersFilter) (*ChatMembers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchChatMembers", + "chat_id": chatID, + "query": query, + "limit": limit, + "filter": filter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatMembers ChatMembers + err = json.Unmarshal(result.Raw, &chatMembers) + return &chatMembers, err + +} + +// GetChatAdministrators Returns a list of users who are administrators of the chat +// @param chatID Chat identifier +func (client *Client) GetChatAdministrators(chatID int64) (*Users, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatAdministrators", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var users Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} + +// ClearAllDraftMessages Clears draft messages in all chats +// @param excludeSecretChats If true, local draft messages in secret chats will not be cleared +func (client *Client) ClearAllDraftMessages(excludeSecretChats bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "clearAllDraftMessages", + "exclude_secret_chats": excludeSecretChats, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetScopeNotificationSettings Returns the notification settings for chats of a given type +// @param scope Types of chats for which to return the notification settings information +func (client *Client) GetScopeNotificationSettings(scope NotificationSettingsScope) (*ScopeNotificationSettings, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getScopeNotificationSettings", + "scope": scope, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var scopeNotificationSettings ScopeNotificationSettings + err = json.Unmarshal(result.Raw, &scopeNotificationSettings) + return &scopeNotificationSettings, err + +} + +// SetScopeNotificationSettings Changes notification settings for chats of a given type +// @param scope Types of chats for which to change the notification settings +// @param notificationSettings The new notification settings for the given scope +func (client *Client) SetScopeNotificationSettings(scope NotificationSettingsScope, notificationSettings *ScopeNotificationSettings) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setScopeNotificationSettings", + "scope": scope, + "notification_settings": notificationSettings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ResetAllNotificationSettings Resets all notification settings to their default values. By default, all chats are unmuted, the sound is set to "default" and message previews are shown +func (client *Client) ResetAllNotificationSettings() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "resetAllNotificationSettings", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetPinnedChats Changes the order of pinned chats +// @param chatIDs The new list of pinned chats +func (client *Client) SetPinnedChats(chatIDs []int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setPinnedChats", + "chat_ids": chatIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DownloadFile Asynchronously downloads a file from the cloud. updateFile will be used to notify about the download progress and successful completion of the download. Returns file state just after the download has been started +// @param fileID Identifier of the file to download +// @param priority Priority of the download (1-32). The higher the priority, the earlier the file will be downloaded. If the priorities of two files are equal, then the last one for which downloadFile was called will be downloaded first +func (client *Client) DownloadFile(fileID int32, priority int32) (*File, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "downloadFile", + "file_id": fileID, + "priority": priority, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var fileDummy File + err = json.Unmarshal(result.Raw, &fileDummy) + return &fileDummy, err + +} + +// CancelDownloadFile Stops the downloading of a file. If a file has already been downloaded, does nothing +// @param fileID Identifier of a file to stop downloading +// @param onlyIfPending Pass true to stop downloading only if it hasn't been started, i.e. request hasn't been sent to server +func (client *Client) CancelDownloadFile(fileID int32, onlyIfPending bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "cancelDownloadFile", + "file_id": fileID, + "only_if_pending": onlyIfPending, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// UploadFile Asynchronously uploads a file to the cloud without sending it in a message. updateFile will be used to notify about upload progress and successful completion of the upload. The file will not have a persistent remote identifier until it will be sent in a message +// @param file File to upload +// @param fileType File type +// @param priority Priority of the upload (1-32). The higher the priority, the earlier the file will be uploaded. If the priorities of two files are equal, then the first one for which uploadFile was called will be uploaded first +func (client *Client) UploadFile(file InputFile, fileType FileType, priority int32) (*File, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "uploadFile", + "file": file, + "file_type": fileType, + "priority": priority, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var fileDummy File + err = json.Unmarshal(result.Raw, &fileDummy) + return &fileDummy, err + +} + +// CancelUploadFile Stops the uploading of a file. Supported only for files uploaded by using uploadFile. For other files the behavior is undefined +// @param fileID Identifier of the file to stop uploading +func (client *Client) CancelUploadFile(fileID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "cancelUploadFile", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetFileGenerationProgress The next part of a file was generated +// @param generationID The identifier of the generation process +// @param expectedSize Expected size of the generated file, in bytes; 0 if unknown +// @param localPrefixSize The number of bytes already generated +func (client *Client) SetFileGenerationProgress(generationID JSONInt64, expectedSize int32, localPrefixSize int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setFileGenerationProgress", + "generation_id": generationID, + "expected_size": expectedSize, + "local_prefix_size": localPrefixSize, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// FinishFileGeneration Finishes the file generation +// @param generationID The identifier of the generation process +// @param error If set, means that file generation has failed and should be terminated +func (client *Client) FinishFileGeneration(generationID JSONInt64, error *Error) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "finishFileGeneration", + "generation_id": generationID, + "error": error, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteFile Deletes a file from the TDLib file cache +// @param fileID Identifier of the file to delete +func (client *Client) DeleteFile(fileID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteFile", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GenerateChatInviteLink Generates a new invite link for a chat; the previously generated link is revoked. Available for basic groups, supergroups, and channels. In basic groups this can be called only by the group's creator; in supergroups and channels this requires appropriate administrator rights +// @param chatID Chat identifier +func (client *Client) GenerateChatInviteLink(chatID int64) (*ChatInviteLink, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "generateChatInviteLink", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatInviteLink ChatInviteLink + err = json.Unmarshal(result.Raw, &chatInviteLink) + return &chatInviteLink, err + +} + +// CheckChatInviteLink Checks the validity of an invite link for a chat and returns information about the corresponding chat +// @param inviteLink Invite link to be checked; should begin with "https://t.me/joinchat/", "https://telegram.me/joinchat/", or "https://telegram.dog/joinchat/" +func (client *Client) CheckChatInviteLink(inviteLink string) (*ChatInviteLinkInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkChatInviteLink", + "invite_link": inviteLink, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatInviteLinkInfo ChatInviteLinkInfo + err = json.Unmarshal(result.Raw, &chatInviteLinkInfo) + return &chatInviteLinkInfo, err + +} + +// JoinChatByInviteLink Uses an invite link to add the current user to the chat if possible. The new member will not be added until the chat state has been synchronized with the server +// @param inviteLink Invite link to import; should begin with "https://t.me/joinchat/", "https://telegram.me/joinchat/", or "https://telegram.dog/joinchat/" +func (client *Client) JoinChatByInviteLink(inviteLink string) (*Chat, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "joinChatByInviteLink", + "invite_link": inviteLink, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chat Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} + +// CreateCall Creates a new call +// @param userID Identifier of the user to be called +// @param protocol Description of the call protocols supported by the client +func (client *Client) CreateCall(userID int32, protocol *CallProtocol) (*CallID, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createCall", + "user_id": userID, + "protocol": protocol, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var callID CallID + err = json.Unmarshal(result.Raw, &callID) + return &callID, err + +} + +// AcceptCall Accepts an incoming call +// @param callID Call identifier +// @param protocol Description of the call protocols supported by the client +func (client *Client) AcceptCall(callID int32, protocol *CallProtocol) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "acceptCall", + "call_id": callID, + "protocol": protocol, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DiscardCall Discards a call +// @param callID Call identifier +// @param isDisconnected True, if the user was disconnected +// @param duration The call duration, in seconds +// @param connectionID Identifier of the connection used during the call +func (client *Client) DiscardCall(callID int32, isDisconnected bool, duration int32, connectionID JSONInt64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "discardCall", + "call_id": callID, + "is_disconnected": isDisconnected, + "duration": duration, + "connection_id": connectionID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendCallRating Sends a call rating +// @param callID Call identifier +// @param rating Call rating; 1-5 +// @param comment An optional user comment if the rating is less than 5 +func (client *Client) SendCallRating(callID int32, rating int32, comment string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendCallRating", + "call_id": callID, + "rating": rating, + "comment": comment, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendCallDebugInformation Sends debug information for a call +// @param callID Call identifier +// @param debugInformation Debug information in application-specific format +func (client *Client) SendCallDebugInformation(callID int32, debugInformation string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendCallDebugInformation", + "call_id": callID, + "debug_information": debugInformation, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// BlockUser Adds a user to the blacklist +// @param userID User identifier +func (client *Client) BlockUser(userID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "blockUser", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// UnblockUser Removes a user from the blacklist +// @param userID User identifier +func (client *Client) UnblockUser(userID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "unblockUser", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetBlockedUsers Returns users that were blocked by the current user +// @param offset Number of users to skip in the result; must be non-negative +// @param limit Maximum number of users to return; up to 100 +func (client *Client) GetBlockedUsers(offset int32, limit int32) (*Users, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getBlockedUsers", + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var users Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} + +// ImportContacts Adds new contacts or edits existing contacts; contacts' user identifiers are ignored +// @param contacts The list of contacts to import or edit, contact's vCard are ignored and are not imported +func (client *Client) ImportContacts(contacts []Contact) (*ImportedContacts, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "importContacts", + "contacts": contacts, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var importedContacts ImportedContacts + err = json.Unmarshal(result.Raw, &importedContacts) + return &importedContacts, err + +} + +// GetContacts Returns all user contacts +func (client *Client) GetContacts() (*Users, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getContacts", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var users Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} + +// SearchContacts Searches for the specified query in the first names, last names and usernames of the known user contacts +// @param query Query to search for; can be empty to return all contacts +// @param limit Maximum number of users to be returned +func (client *Client) SearchContacts(query string, limit int32) (*Users, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchContacts", + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var users Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} + +// RemoveContacts Removes users from the contacts list +// @param userIDs Identifiers of users to be deleted +func (client *Client) RemoveContacts(userIDs []int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeContacts", + "user_ids": userIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetImportedContactCount Returns the total number of imported contacts +func (client *Client) GetImportedContactCount() (*Count, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getImportedContactCount", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var count Count + err = json.Unmarshal(result.Raw, &count) + return &count, err + +} + +// ChangeImportedContacts Changes imported contacts using the list of current user contacts saved on the device. Imports newly added contacts and, if at least the file database is enabled, deletes recently deleted contacts. +// @param contacts +func (client *Client) ChangeImportedContacts(contacts []Contact) (*ImportedContacts, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "changeImportedContacts", + "contacts": contacts, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var importedContacts ImportedContacts + err = json.Unmarshal(result.Raw, &importedContacts) + return &importedContacts, err + +} + +// ClearImportedContacts Clears all imported contacts, contacts list remains unchanged +func (client *Client) ClearImportedContacts() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "clearImportedContacts", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetUserProfilePhotos Returns the profile photos of a user. The result of this query may be outdated: some photos might have been deleted already +// @param userID User identifier +// @param offset The number of photos to skip; must be non-negative +// @param limit Maximum number of photos to be returned; up to 100 +func (client *Client) GetUserProfilePhotos(userID int32, offset int32, limit int32) (*UserProfilePhotos, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getUserProfilePhotos", + "user_id": userID, + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var userProfilePhotos UserProfilePhotos + err = json.Unmarshal(result.Raw, &userProfilePhotos) + return &userProfilePhotos, err + +} + +// GetStickers Returns stickers from the installed sticker sets that correspond to a given emoji. If the emoji is not empty, favorite and recently used stickers may also be returned +// @param emoji String representation of emoji. If empty, returns all known installed stickers +// @param limit Maximum number of stickers to be returned +func (client *Client) GetStickers(emoji string, limit int32) (*Stickers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getStickers", + "emoji": emoji, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickers Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, err + +} + +// SearchStickers Searches for stickers from public sticker sets that correspond to a given emoji +// @param emoji String representation of emoji; must be non-empty +// @param limit Maximum number of stickers to be returned +func (client *Client) SearchStickers(emoji string, limit int32) (*Stickers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchStickers", + "emoji": emoji, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickers Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, err + +} + +// GetInstalledStickerSets Returns a list of installed sticker sets +// @param isMasks Pass true to return mask sticker sets; pass false to return ordinary sticker sets +func (client *Client) GetInstalledStickerSets(isMasks bool) (*StickerSets, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getInstalledStickerSets", + "is_masks": isMasks, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSets StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} + +// GetArchivedStickerSets Returns a list of archived sticker sets +// @param isMasks Pass true to return mask stickers sets; pass false to return ordinary sticker sets +// @param offsetStickerSetID Identifier of the sticker set from which to return the result +// @param limit Maximum number of sticker sets to return +func (client *Client) GetArchivedStickerSets(isMasks bool, offsetStickerSetID JSONInt64, limit int32) (*StickerSets, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getArchivedStickerSets", + "is_masks": isMasks, + "offset_sticker_set_id": offsetStickerSetID, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSets StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} + +// GetTrendingStickerSets Returns a list of trending sticker sets +func (client *Client) GetTrendingStickerSets() (*StickerSets, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getTrendingStickerSets", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSets StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} + +// GetAttachedStickerSets Returns a list of sticker sets attached to a file. Currently only photos and videos can have attached sticker sets +// @param fileID File identifier +func (client *Client) GetAttachedStickerSets(fileID int32) (*StickerSets, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getAttachedStickerSets", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSets StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} + +// GetStickerSet Returns information about a sticker set by its identifier +// @param setID Identifier of the sticker set +func (client *Client) GetStickerSet(setID JSONInt64) (*StickerSet, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getStickerSet", + "set_id": setID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSet StickerSet + err = json.Unmarshal(result.Raw, &stickerSet) + return &stickerSet, err + +} + +// SearchStickerSet Searches for a sticker set by its name +// @param name Name of the sticker set +func (client *Client) SearchStickerSet(name string) (*StickerSet, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchStickerSet", + "name": name, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSet StickerSet + err = json.Unmarshal(result.Raw, &stickerSet) + return &stickerSet, err + +} + +// SearchInstalledStickerSets Searches for installed sticker sets by looking for specified query in their title and name +// @param isMasks Pass true to return mask sticker sets; pass false to return ordinary sticker sets +// @param query Query to search for +// @param limit Maximum number of sticker sets to return +func (client *Client) SearchInstalledStickerSets(isMasks bool, query string, limit int32) (*StickerSets, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchInstalledStickerSets", + "is_masks": isMasks, + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSets StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} + +// SearchStickerSets Searches for ordinary sticker sets by looking for specified query in their title and name. Excludes installed sticker sets from the results +// @param query Query to search for +func (client *Client) SearchStickerSets(query string) (*StickerSets, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchStickerSets", + "query": query, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSets StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} + +// ChangeStickerSet Installs/uninstalls or activates/archives a sticker set +// @param setID Identifier of the sticker set +// @param isInstalled The new value of is_installed +// @param isArchived The new value of is_archived. A sticker set can't be installed and archived simultaneously +func (client *Client) ChangeStickerSet(setID JSONInt64, isInstalled bool, isArchived bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "changeStickerSet", + "set_id": setID, + "is_installed": isInstalled, + "is_archived": isArchived, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ViewTrendingStickerSets Informs the server that some trending sticker sets have been viewed by the user +// @param stickerSetIDs Identifiers of viewed trending sticker sets +func (client *Client) ViewTrendingStickerSets(stickerSetIDs []JSONInt64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "viewTrendingStickerSets", + "sticker_set_ids": stickerSetIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ReorderInstalledStickerSets Changes the order of installed sticker sets +// @param isMasks Pass true to change the order of mask sticker sets; pass false to change the order of ordinary sticker sets +// @param stickerSetIDs Identifiers of installed sticker sets in the new correct order +func (client *Client) ReorderInstalledStickerSets(isMasks bool, stickerSetIDs []JSONInt64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "reorderInstalledStickerSets", + "is_masks": isMasks, + "sticker_set_ids": stickerSetIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetRecentStickers Returns a list of recently used stickers +// @param isAttached Pass true to return stickers and masks that were recently attached to photos or video files; pass false to return recently sent stickers +func (client *Client) GetRecentStickers(isAttached bool) (*Stickers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getRecentStickers", + "is_attached": isAttached, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickers Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, err + +} + +// AddRecentSticker Manually adds a new sticker to the list of recently used stickers. The new sticker is added to the top of the list. If the sticker was already in the list, it is removed from the list first. Only stickers belonging to a sticker set can be added to this list +// @param isAttached Pass true to add the sticker to the list of stickers recently attached to photo or video files; pass false to add the sticker to the list of recently sent stickers +// @param sticker Sticker file to add +func (client *Client) AddRecentSticker(isAttached bool, sticker InputFile) (*Stickers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addRecentSticker", + "is_attached": isAttached, + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickers Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, err + +} + +// RemoveRecentSticker Removes a sticker from the list of recently used stickers +// @param isAttached Pass true to remove the sticker from the list of stickers recently attached to photo or video files; pass false to remove the sticker from the list of recently sent stickers +// @param sticker Sticker file to delete +func (client *Client) RemoveRecentSticker(isAttached bool, sticker InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeRecentSticker", + "is_attached": isAttached, + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ClearRecentStickers Clears the list of recently used stickers +// @param isAttached Pass true to clear the list of stickers recently attached to photo or video files; pass false to clear the list of recently sent stickers +func (client *Client) ClearRecentStickers(isAttached bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "clearRecentStickers", + "is_attached": isAttached, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetFavoriteStickers Returns favorite stickers +func (client *Client) GetFavoriteStickers() (*Stickers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getFavoriteStickers", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickers Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, err + +} + +// AddFavoriteSticker Adds a new sticker to the list of favorite stickers. The new sticker is added to the top of the list. If the sticker was already in the list, it is removed from the list first. Only stickers belonging to a sticker set can be added to this list +// @param sticker Sticker file to add +func (client *Client) AddFavoriteSticker(sticker InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addFavoriteSticker", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveFavoriteSticker Removes a sticker from the list of favorite stickers +// @param sticker Sticker file to delete from the list +func (client *Client) RemoveFavoriteSticker(sticker InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeFavoriteSticker", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetStickerEmojis Returns emoji corresponding to a sticker +// @param sticker Sticker file identifier +func (client *Client) GetStickerEmojis(sticker InputFile) (*StickerEmojis, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getStickerEmojis", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerEmojis StickerEmojis + err = json.Unmarshal(result.Raw, &stickerEmojis) + return &stickerEmojis, err + +} + +// GetSavedAnimations Returns saved animations +func (client *Client) GetSavedAnimations() (*Animations, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getSavedAnimations", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var animations Animations + err = json.Unmarshal(result.Raw, &animations) + return &animations, err + +} + +// AddSavedAnimation Manually adds a new animation to the list of saved animations. The new animation is added to the beginning of the list. If the animation was already in the list, it is removed first. Only non-secret video animations with MIME type "video/mp4" can be added to the list +// @param animation The animation file to be added. Only animations known to the server (i.e. successfully sent via a message) can be added to the list +func (client *Client) AddSavedAnimation(animation InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addSavedAnimation", + "animation": animation, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveSavedAnimation Removes an animation from the list of saved animations +// @param animation Animation file to be removed +func (client *Client) RemoveSavedAnimation(animation InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeSavedAnimation", + "animation": animation, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetRecentInlineBots Returns up to 20 recently used inline bots in the order of their last usage +func (client *Client) GetRecentInlineBots() (*Users, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getRecentInlineBots", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var users Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} + +// SearchHashtags Searches for recently used hashtags by their prefix +// @param prefix Hashtag prefix to search for +// @param limit Maximum number of hashtags to be returned +func (client *Client) SearchHashtags(prefix string, limit int32) (*Hashtags, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "searchHashtags", + "prefix": prefix, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var hashtags Hashtags + err = json.Unmarshal(result.Raw, &hashtags) + return &hashtags, err + +} + +// RemoveRecentHashtag Removes a hashtag from the list of recently used hashtags +// @param hashtag Hashtag to delete +func (client *Client) RemoveRecentHashtag(hashtag string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeRecentHashtag", + "hashtag": hashtag, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetWebPagePreview Returns a web page preview by the text of the message. Do not call this function too often. Returns a 404 error if the web page has no preview +// @param text Message text with formatting +func (client *Client) GetWebPagePreview(text *FormattedText) (*WebPage, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getWebPagePreview", + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var webPage WebPage + err = json.Unmarshal(result.Raw, &webPage) + return &webPage, err + +} + +// GetWebPageInstantView Returns an instant view version of a web page if available. Returns a 404 error if the web page has no instant view page +// @param uRL The web page URL +// @param forceFull If true, the full instant view for the web page will be returned +func (client *Client) GetWebPageInstantView(uRL string, forceFull bool) (*WebPageInstantView, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getWebPageInstantView", + "url": uRL, + "force_full": forceFull, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var webPageInstantView WebPageInstantView + err = json.Unmarshal(result.Raw, &webPageInstantView) + return &webPageInstantView, err + +} + +// SetProfilePhoto Uploads a new profile photo for the current user. If something changes, updateUser will be sent +// @param photo Profile photo to set. inputFileId and inputFileRemote may still be unsupported +func (client *Client) SetProfilePhoto(photo InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setProfilePhoto", + "photo": photo, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteProfilePhoto Deletes a profile photo. If something changes, updateUser will be sent +// @param profilePhotoID Identifier of the profile photo to delete +func (client *Client) DeleteProfilePhoto(profilePhotoID JSONInt64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteProfilePhoto", + "profile_photo_id": profilePhotoID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetName Changes the first and last name of the current user. If something changes, updateUser will be sent +// @param firstName The new value of the first name for the user; 1-255 characters +// @param lastName The new value of the optional last name for the user; 0-255 characters +func (client *Client) SetName(firstName string, lastName string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setName", + "first_name": firstName, + "last_name": lastName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetBio Changes the bio of the current user +// @param bio The new value of the user bio; 0-70 characters without line feeds +func (client *Client) SetBio(bio string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setBio", + "bio": bio, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetUsername Changes the username of the current user. If something changes, updateUser will be sent +// @param username The new value of the username. Use an empty string to remove the username +func (client *Client) SetUsername(username string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setUsername", + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ChangePhoneNumber Changes the phone number of the user and sends an authentication code to the user's new phone number. On success, returns information about the sent code +// @param phoneNumber The new phone number of the user in international format +// @param allowFlashCall Pass true if the code can be sent via flash call to the specified phone number +// @param isCurrentPhoneNumber Pass true if the phone number is used on the current device. Ignored if allow_flash_call is false +func (client *Client) ChangePhoneNumber(phoneNumber string, allowFlashCall bool, isCurrentPhoneNumber bool) (*AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "changePhoneNumber", + "phone_number": phoneNumber, + "allow_flash_call": allowFlashCall, + "is_current_phone_number": isCurrentPhoneNumber, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var authenticationCodeInfo AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// ResendChangePhoneNumberCode Re-sends the authentication code sent to confirm a new phone number for the user. Works only if the previously received authenticationCodeInfo next_code_type was not null +func (client *Client) ResendChangePhoneNumberCode() (*AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "resendChangePhoneNumberCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var authenticationCodeInfo AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// CheckChangePhoneNumberCode Checks the authentication code sent to confirm a new phone number of the user +// @param code Verification code received by SMS, phone call or flash call +func (client *Client) CheckChangePhoneNumberCode(code string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkChangePhoneNumberCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetActiveSessions Returns all active sessions of the current user +func (client *Client) GetActiveSessions() (*Sessions, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getActiveSessions", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var sessions Sessions + err = json.Unmarshal(result.Raw, &sessions) + return &sessions, err + +} + +// TerminateSession Terminates a session of the current user +// @param sessionID Session identifier +func (client *Client) TerminateSession(sessionID JSONInt64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "terminateSession", + "session_id": sessionID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TerminateAllOtherSessions Terminates all other sessions of the current user +func (client *Client) TerminateAllOtherSessions() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "terminateAllOtherSessions", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetConnectedWebsites Returns all website where the current user used Telegram to log in +func (client *Client) GetConnectedWebsites() (*ConnectedWebsites, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getConnectedWebsites", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var connectedWebsites ConnectedWebsites + err = json.Unmarshal(result.Raw, &connectedWebsites) + return &connectedWebsites, err + +} + +// DisconnectWebsite Disconnects website from the current user's Telegram account +// @param websiteID Website identifier +func (client *Client) DisconnectWebsite(websiteID JSONInt64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "disconnectWebsite", + "website_id": websiteID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DisconnectAllWebsites Disconnects all websites from the current user's Telegram account +func (client *Client) DisconnectAllWebsites() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "disconnectAllWebsites", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleBasicGroupAdministrators Toggles the "All members are admins" setting in basic groups; requires creator privileges in the group +// @param basicGroupID Identifier of the basic group +// @param everyoneIsAdministrator New value of everyone_is_administrator +func (client *Client) ToggleBasicGroupAdministrators(basicGroupID int32, everyoneIsAdministrator bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "toggleBasicGroupAdministrators", + "basic_group_id": basicGroupID, + "everyone_is_administrator": everyoneIsAdministrator, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetSupergroupUsername Changes the username of a supergroup or channel, requires creator privileges in the supergroup or channel +// @param supergroupID Identifier of the supergroup or channel +// @param username New value of the username. Use an empty string to remove the username +func (client *Client) SetSupergroupUsername(supergroupID int32, username string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setSupergroupUsername", + "supergroup_id": supergroupID, + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetSupergroupStickerSet Changes the sticker set of a supergroup; requires appropriate rights in the supergroup +// @param supergroupID Identifier of the supergroup +// @param stickerSetID New value of the supergroup sticker set identifier. Use 0 to remove the supergroup sticker set +func (client *Client) SetSupergroupStickerSet(supergroupID int32, stickerSetID JSONInt64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setSupergroupStickerSet", + "supergroup_id": supergroupID, + "sticker_set_id": stickerSetID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleSupergroupInvites Toggles whether all members of a supergroup can add new members; requires appropriate administrator rights in the supergroup. +// @param supergroupID Identifier of the supergroup +// @param anyoneCanInvite New value of anyone_can_invite +func (client *Client) ToggleSupergroupInvites(supergroupID int32, anyoneCanInvite bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "toggleSupergroupInvites", + "supergroup_id": supergroupID, + "anyone_can_invite": anyoneCanInvite, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleSupergroupSignMessages Toggles sender signatures messages sent in a channel; requires appropriate administrator rights in the channel. +// @param supergroupID Identifier of the channel +// @param signMessages New value of sign_messages +func (client *Client) ToggleSupergroupSignMessages(supergroupID int32, signMessages bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "toggleSupergroupSignMessages", + "supergroup_id": supergroupID, + "sign_messages": signMessages, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleSupergroupIsAllHistoryAvailable Toggles whether the message history of a supergroup is available to new members; requires appropriate administrator rights in the supergroup. +// @param supergroupID The identifier of the supergroup +// @param isAllHistoryAvailable The new value of is_all_history_available +func (client *Client) ToggleSupergroupIsAllHistoryAvailable(supergroupID int32, isAllHistoryAvailable bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "toggleSupergroupIsAllHistoryAvailable", + "supergroup_id": supergroupID, + "is_all_history_available": isAllHistoryAvailable, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetSupergroupDescription Changes information about a supergroup or channel; requires appropriate administrator rights +// @param supergroupID Identifier of the supergroup or channel +// @param description +func (client *Client) SetSupergroupDescription(supergroupID int32, description string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setSupergroupDescription", + "supergroup_id": supergroupID, + "description": description, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// PinSupergroupMessage Pins a message in a supergroup or channel; requires appropriate administrator rights in the supergroup or channel +// @param supergroupID Identifier of the supergroup or channel +// @param messageID Identifier of the new pinned message +// @param disableNotification True, if there should be no notification about the pinned message +func (client *Client) PinSupergroupMessage(supergroupID int32, messageID int64, disableNotification bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "pinSupergroupMessage", + "supergroup_id": supergroupID, + "message_id": messageID, + "disable_notification": disableNotification, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// UnpinSupergroupMessage Removes the pinned message from a supergroup or channel; requires appropriate administrator rights in the supergroup or channel +// @param supergroupID Identifier of the supergroup or channel +func (client *Client) UnpinSupergroupMessage(supergroupID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "unpinSupergroupMessage", + "supergroup_id": supergroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ReportSupergroupSpam Reports some messages from a user in a supergroup as spam; requires administrator rights in the supergroup +// @param supergroupID Supergroup identifier +// @param userID User identifier +// @param messageIDs Identifiers of messages sent in the supergroup by the user. This list must be non-empty +func (client *Client) ReportSupergroupSpam(supergroupID int32, userID int32, messageIDs []int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "reportSupergroupSpam", + "supergroup_id": supergroupID, + "user_id": userID, + "message_ids": messageIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetSupergroupMembers Returns information about members or banned users in a supergroup or channel. Can be used only if SupergroupFullInfo.can_get_members == true; additionally, administrator privileges may be required for some filters +// @param supergroupID Identifier of the supergroup or channel +// @param filter The type of users to return. By default, supergroupMembersRecent +// @param offset Number of users to skip +// @param limit The maximum number of users be returned; up to 200 +func (client *Client) GetSupergroupMembers(supergroupID int32, filter SupergroupMembersFilter, offset int32, limit int32) (*ChatMembers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getSupergroupMembers", + "supergroup_id": supergroupID, + "filter": filter, + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatMembers ChatMembers + err = json.Unmarshal(result.Raw, &chatMembers) + return &chatMembers, err + +} + +// DeleteSupergroup Deletes a supergroup or channel along with all messages in the corresponding chat. This will release the supergroup or channel username and remove all members; requires creator privileges in the supergroup or channel. Chats with more than 1000 members can't be deleted using this method +// @param supergroupID Identifier of the supergroup or channel +func (client *Client) DeleteSupergroup(supergroupID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteSupergroup", + "supergroup_id": supergroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CloseSecretChat Closes a secret chat, effectively transfering its state to secretChatStateClosed +// @param secretChatID Secret chat identifier +func (client *Client) CloseSecretChat(secretChatID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "closeSecretChat", + "secret_chat_id": secretChatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetChatEventLog Returns a list of service actions taken by chat members and administrators in the last 48 hours. Available only in supergroups and channels. Requires administrator rights. Returns results in reverse chronological order (i. e., in order of decreasing event_id) +// @param chatID Chat identifier +// @param query Search query by which to filter events +// @param fromEventID Identifier of an event from which to return results. Use 0 to get results from the latest events +// @param limit Maximum number of events to return; up to 100 +// @param filters The types of events to return. By default, all types will be returned +// @param userIDs User identifiers by which to filter events. By default, events relating to all users will be returned +func (client *Client) GetChatEventLog(chatID int64, query string, fromEventID JSONInt64, limit int32, filters *ChatEventLogFilters, userIDs []int32) (*ChatEvents, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatEventLog", + "chat_id": chatID, + "query": query, + "from_event_id": fromEventID, + "limit": limit, + "filters": filters, + "user_ids": userIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatEvents ChatEvents + err = json.Unmarshal(result.Raw, &chatEvents) + return &chatEvents, err + +} + +// GetPaymentForm Returns an invoice payment form. This method should be called when the user presses inlineKeyboardButtonBuy +// @param chatID Chat identifier of the Invoice message +// @param messageID Message identifier +func (client *Client) GetPaymentForm(chatID int64, messageID int64) (*PaymentForm, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getPaymentForm", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var paymentForm PaymentForm + err = json.Unmarshal(result.Raw, &paymentForm) + return &paymentForm, err + +} + +// ValidateOrderInfo Validates the order information provided by a user and returns the available shipping options for a flexible invoice +// @param chatID Chat identifier of the Invoice message +// @param messageID Message identifier +// @param orderInfo The order information, provided by the user +// @param allowSave True, if the order information can be saved +func (client *Client) ValidateOrderInfo(chatID int64, messageID int64, orderInfo *OrderInfo, allowSave bool) (*ValidatedOrderInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "validateOrderInfo", + "chat_id": chatID, + "message_id": messageID, + "order_info": orderInfo, + "allow_save": allowSave, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var validatedOrderInfo ValidatedOrderInfo + err = json.Unmarshal(result.Raw, &validatedOrderInfo) + return &validatedOrderInfo, err + +} + +// SendPaymentForm Sends a filled-out payment form to the bot for final verification +// @param chatID Chat identifier of the Invoice message +// @param messageID Message identifier +// @param orderInfoID Identifier returned by ValidateOrderInfo, or an empty string +// @param shippingOptionID Identifier of a chosen shipping option, if applicable +// @param credentials The credentials chosen by user for payment +func (client *Client) SendPaymentForm(chatID int64, messageID int64, orderInfoID string, shippingOptionID string, credentials InputCredentials) (*PaymentResult, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendPaymentForm", + "chat_id": chatID, + "message_id": messageID, + "order_info_id": orderInfoID, + "shipping_option_id": shippingOptionID, + "credentials": credentials, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var paymentResult PaymentResult + err = json.Unmarshal(result.Raw, &paymentResult) + return &paymentResult, err + +} + +// GetPaymentReceipt Returns information about a successful payment +// @param chatID Chat identifier of the PaymentSuccessful message +// @param messageID Message identifier +func (client *Client) GetPaymentReceipt(chatID int64, messageID int64) (*PaymentReceipt, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getPaymentReceipt", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var paymentReceipt PaymentReceipt + err = json.Unmarshal(result.Raw, &paymentReceipt) + return &paymentReceipt, err + +} + +// GetSavedOrderInfo Returns saved order info, if any +func (client *Client) GetSavedOrderInfo() (*OrderInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getSavedOrderInfo", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var orderInfo OrderInfo + err = json.Unmarshal(result.Raw, &orderInfo) + return &orderInfo, err + +} + +// DeleteSavedOrderInfo Deletes saved order info +func (client *Client) DeleteSavedOrderInfo() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteSavedOrderInfo", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteSavedCredentials Deletes saved credentials for all payment provider bots +func (client *Client) DeleteSavedCredentials() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteSavedCredentials", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetSupportUser Returns a user that can be contacted to get support +func (client *Client) GetSupportUser() (*User, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getSupportUser", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var user User + err = json.Unmarshal(result.Raw, &user) + return &user, err + +} + +// GetWallpapers Returns background wallpapers +func (client *Client) GetWallpapers() (*Wallpapers, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getWallpapers", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var wallpapers Wallpapers + err = json.Unmarshal(result.Raw, &wallpapers) + return &wallpapers, err + +} + +// GetLocalizationTargetInfo Returns information about the current localization target. This is an offline request if only_local is true +// @param onlyLocal If true, returns only locally available information without sending network requests +func (client *Client) GetLocalizationTargetInfo(onlyLocal bool) (*LocalizationTargetInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getLocalizationTargetInfo", + "only_local": onlyLocal, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var localizationTargetInfo LocalizationTargetInfo + err = json.Unmarshal(result.Raw, &localizationTargetInfo) + return &localizationTargetInfo, err + +} + +// GetLanguagePackStrings Returns strings from a language pack in the current localization target by their keys +// @param languagePackID Language pack identifier of the strings to be returned +// @param keys Language pack keys of the strings to be returned; leave empty to request all available strings +func (client *Client) GetLanguagePackStrings(languagePackID string, keys []string) (*LanguagePackStrings, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getLanguagePackStrings", + "language_pack_id": languagePackID, + "keys": keys, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var languagePackStrings LanguagePackStrings + err = json.Unmarshal(result.Raw, &languagePackStrings) + return &languagePackStrings, err + +} + +// SetCustomLanguagePack Adds or changes a custom language pack to the current localization target +// @param info Information about the language pack. Language pack ID must start with 'X', consist only of English letters, digits and hyphens, and must not exceed 64 characters +// @param strings Strings of the new language pack +func (client *Client) SetCustomLanguagePack(info *LanguagePackInfo, strings []LanguagePackString) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setCustomLanguagePack", + "info": info, + "strings": strings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditCustomLanguagePackInfo Edits information about a custom language pack in the current localization target +// @param info New information about the custom language pack +func (client *Client) EditCustomLanguagePackInfo(info *LanguagePackInfo) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editCustomLanguagePackInfo", + "info": info, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetCustomLanguagePackString Adds, edits or deletes a string in a custom language pack +// @param languagePackID Identifier of a previously added custom language pack in the current localization target +// @param newString New language pack string +func (client *Client) SetCustomLanguagePackString(languagePackID string, newString *LanguagePackString) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setCustomLanguagePackString", + "language_pack_id": languagePackID, + "new_string": newString, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteLanguagePack Deletes all information about a language pack in the current localization target. The language pack that is currently in use can't be deleted +// @param languagePackID Identifier of the language pack to delete +func (client *Client) DeleteLanguagePack(languagePackID string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteLanguagePack", + "language_pack_id": languagePackID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RegisterDevice Registers the currently used device for receiving push notifications +// @param deviceToken Device token +// @param otherUserIDs List of at most 100 user identifiers of other users currently using the client +func (client *Client) RegisterDevice(deviceToken DeviceToken, otherUserIDs []int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "registerDevice", + "device_token": deviceToken, + "other_user_ids": otherUserIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var okDummy Ok + err = json.Unmarshal(result.Raw, &okDummy) + return &okDummy, err + +} + +// GetRecentlyVisitedTMeURLs Returns t.me URLs recently visited by a newly registered user +// @param referrer Google Play referrer to identify the user +func (client *Client) GetRecentlyVisitedTMeURLs(referrer string) (*TMeURLs, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getRecentlyVisitedTMeUrls", + "referrer": referrer, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var tMeURLs TMeURLs + err = json.Unmarshal(result.Raw, &tMeURLs) + return &tMeURLs, err + +} + +// SetUserPrivacySettingRules Changes user privacy settings +// @param setting The privacy setting +// @param rules The new privacy rules +func (client *Client) SetUserPrivacySettingRules(setting UserPrivacySetting, rules *UserPrivacySettingRules) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setUserPrivacySettingRules", + "setting": setting, + "rules": rules, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetUserPrivacySettingRules Returns the current privacy settings +// @param setting The privacy setting +func (client *Client) GetUserPrivacySettingRules(setting UserPrivacySetting) (*UserPrivacySettingRules, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getUserPrivacySettingRules", + "setting": setting, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var userPrivacySettingRules UserPrivacySettingRules + err = json.Unmarshal(result.Raw, &userPrivacySettingRules) + return &userPrivacySettingRules, err + +} + +// GetOption Returns the value of an option by its name. (Check the list of available options on https://core.telegram.org/tdlib/options.) Can be called before authorization +// @param name The name of the option +func (client *Client) GetOption(name string) (OptionValue, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getOption", + "name": name, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + switch OptionValueEnum(result.Data["@type"].(string)) { + + case OptionValueBooleanType: + var optionValue OptionValueBoolean + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + case OptionValueEmptyType: + var optionValue OptionValueEmpty + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + case OptionValueIntegerType: + var optionValue OptionValueInteger + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + case OptionValueStringType: + var optionValue OptionValueString + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// SetOption Sets the value of an option. (Check the list of available options on https://core.telegram.org/tdlib/options.) Only writable options can be set. Can be called before authorization +// @param name The name of the option +// @param value The new value of the option +func (client *Client) SetOption(name string, value OptionValue) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setOption", + "name": name, + "value": value, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetAccountTTL Changes the period of inactivity after which the account of the current user will automatically be deleted +// @param tTL New account TTL +func (client *Client) SetAccountTTL(tTL *AccountTTL) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setAccountTtl", + "ttl": tTL, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetAccountTTL Returns the period of inactivity after which the account of the current user will automatically be deleted +func (client *Client) GetAccountTTL() (*AccountTTL, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getAccountTtl", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var accountTTL AccountTTL + err = json.Unmarshal(result.Raw, &accountTTL) + return &accountTTL, err + +} + +// DeleteAccount Deletes the account of the current user, deleting all information associated with the user from the server. The phone number of the account can be used to create a new account. Can be called before authorization when the current authorization state is authorizationStateWaitPassword +// @param reason The reason why the account was deleted; optional +func (client *Client) DeleteAccount(reason string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deleteAccount", + "reason": reason, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetChatReportSpamState Returns information on whether the current chat can be reported as spam +// @param chatID Chat identifier +func (client *Client) GetChatReportSpamState(chatID int64) (*ChatReportSpamState, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getChatReportSpamState", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var chatReportSpamState ChatReportSpamState + err = json.Unmarshal(result.Raw, &chatReportSpamState) + return &chatReportSpamState, err + +} + +// ChangeChatReportSpamState Used to let the server know whether a chat is spam or not. Can be used only if ChatReportSpamState.can_report_spam is true. After this request, ChatReportSpamState.can_report_spam becomes false forever +// @param chatID Chat identifier +// @param isSpamChat If true, the chat will be reported as spam; otherwise it will be marked as not spam +func (client *Client) ChangeChatReportSpamState(chatID int64, isSpamChat bool) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "changeChatReportSpamState", + "chat_id": chatID, + "is_spam_chat": isSpamChat, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ReportChat Reports a chat to the Telegram moderators. Supported only for supergroups, channels, or private chats with bots, since other chats can't be checked by moderators +// @param chatID Chat identifier +// @param reason The reason for reporting the chat +// @param messageIDs Identifiers of reported messages, if any +func (client *Client) ReportChat(chatID int64, reason ChatReportReason, messageIDs []int64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "reportChat", + "chat_id": chatID, + "reason": reason, + "message_ids": messageIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetStorageStatistics Returns storage usage statistics +// @param chatLimit Maximum number of chats with the largest storage usage for which separate statistics should be returned. All other chats will be grouped in entries with chat_id == 0. If the chat info database is not used, the chat_limit is ignored and is always set to 0 +func (client *Client) GetStorageStatistics(chatLimit int32) (*StorageStatistics, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getStorageStatistics", + "chat_limit": chatLimit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var storageStatistics StorageStatistics + err = json.Unmarshal(result.Raw, &storageStatistics) + return &storageStatistics, err + +} + +// GetStorageStatisticsFast Quickly returns approximate storage usage statistics +func (client *Client) GetStorageStatisticsFast() (*StorageStatisticsFast, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getStorageStatisticsFast", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var storageStatisticsFast StorageStatisticsFast + err = json.Unmarshal(result.Raw, &storageStatisticsFast) + return &storageStatisticsFast, err + +} + +// OptimizeStorage Optimizes storage usage, i.e. deletes some files and returns new storage usage statistics. Secret thumbnails can't be deleted +// @param size Limit on the total size of files after deletion. Pass -1 to use the default limit +// @param tTL Limit on the time that has passed since the last time a file was accessed (or creation time for some filesystems). Pass -1 to use the default limit +// @param count Limit on the total count of files after deletion. Pass -1 to use the default limit +// @param immunityDelay The amount of time after the creation of a file during which it can't be deleted, in seconds. Pass -1 to use the default value +// @param fileTypes If not empty, only files with the given type(s) are considered. By default, all types except thumbnails, profile photos, stickers and wallpapers are deleted +// @param chatIDs If not empty, only files from the given chats are considered. Use 0 as chat identifier to delete files not belonging to any chat (e.g., profile photos) +// @param excludeChatIDs If not empty, files from the given chats are excluded. Use 0 as chat identifier to exclude all files not belonging to any chat (e.g., profile photos) +// @param chatLimit Same as in getStorageStatistics. Affects only returned statistics +func (client *Client) OptimizeStorage(size int64, tTL int32, count int32, immunityDelay int32, fileTypes []FileType, chatIDs []int64, excludeChatIDs []int64, chatLimit int32) (*StorageStatistics, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "optimizeStorage", + "size": size, + "ttl": tTL, + "count": count, + "immunity_delay": immunityDelay, + "file_types": fileTypes, + "chat_ids": chatIDs, + "exclude_chat_ids": excludeChatIDs, + "chat_limit": chatLimit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var storageStatistics StorageStatistics + err = json.Unmarshal(result.Raw, &storageStatistics) + return &storageStatistics, err + +} + +// SetNetworkType Sets the current network type. Can be called before authorization. Calling this method forces all network connections to reopen, mitigating the delay in switching between different networks, so it should be called whenever the network is changed, even if the network type remains the same. +// @param typeParam +func (client *Client) SetNetworkType(typeParam NetworkType) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setNetworkType", + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetNetworkStatistics Returns network data usage statistics. Can be called before authorization +// @param onlyCurrent If true, returns only data for the current library launch +func (client *Client) GetNetworkStatistics(onlyCurrent bool) (*NetworkStatistics, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getNetworkStatistics", + "only_current": onlyCurrent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var networkStatistics NetworkStatistics + err = json.Unmarshal(result.Raw, &networkStatistics) + return &networkStatistics, err + +} + +// AddNetworkStatistics Adds the specified data to data usage statistics. Can be called before authorization +// @param entry The network statistics entry with the data to be added to statistics +func (client *Client) AddNetworkStatistics(entry NetworkStatisticsEntry) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addNetworkStatistics", + "entry": entry, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ResetNetworkStatistics Resets all network data usage statistics to zero. Can be called before authorization +func (client *Client) ResetNetworkStatistics() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "resetNetworkStatistics", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetPassportElement Returns one of the available Telegram Passport elements +// @param typeParam Telegram Passport element type +// @param password Password of the current user +func (client *Client) GetPassportElement(typeParam PassportElementType, password string) (PassportElement, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getPassportElement", + "type": typeParam, + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + switch PassportElementEnum(result.Data["@type"].(string)) { + + case PassportElementPersonalDetailsType: + var passportElement PassportElementPersonalDetails + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementPassportType: + var passportElement PassportElementPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementDriverLicenseType: + var passportElement PassportElementDriverLicense + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementIDentityCardType: + var passportElement PassportElementIDentityCard + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementInternalPassportType: + var passportElement PassportElementInternalPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementAddressType: + var passportElement PassportElementAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementUtilityBillType: + var passportElement PassportElementUtilityBill + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementBankStatementType: + var passportElement PassportElementBankStatement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementRentalAgreementType: + var passportElement PassportElementRentalAgreement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementPassportRegistrationType: + var passportElement PassportElementPassportRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementTemporaryRegistrationType: + var passportElement PassportElementTemporaryRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementPhoneNumberType: + var passportElement PassportElementPhoneNumber + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementEmailAddressType: + var passportElement PassportElementEmailAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// GetAllPassportElements Returns all available Telegram Passport elements +// @param password Password of the current user +func (client *Client) GetAllPassportElements(password string) (*PassportElements, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getAllPassportElements", + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var passportElements PassportElements + err = json.Unmarshal(result.Raw, &passportElements) + return &passportElements, err + +} + +// SetPassportElement Adds an element to the user's Telegram Passport. May return an error with a message "PHONE_VERIFICATION_NEEDED" or "EMAIL_VERIFICATION_NEEDED" if the chosen phone number or the chosen email address must be verified first +// @param element Input Telegram Passport element +// @param password Password of the current user +func (client *Client) SetPassportElement(element InputPassportElement, password string) (PassportElement, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setPassportElement", + "element": element, + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + switch PassportElementEnum(result.Data["@type"].(string)) { + + case PassportElementPersonalDetailsType: + var passportElement PassportElementPersonalDetails + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementPassportType: + var passportElement PassportElementPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementDriverLicenseType: + var passportElement PassportElementDriverLicense + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementIDentityCardType: + var passportElement PassportElementIDentityCard + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementInternalPassportType: + var passportElement PassportElementInternalPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementAddressType: + var passportElement PassportElementAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementUtilityBillType: + var passportElement PassportElementUtilityBill + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementBankStatementType: + var passportElement PassportElementBankStatement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementRentalAgreementType: + var passportElement PassportElementRentalAgreement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementPassportRegistrationType: + var passportElement PassportElementPassportRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementTemporaryRegistrationType: + var passportElement PassportElementTemporaryRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementPhoneNumberType: + var passportElement PassportElementPhoneNumber + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case PassportElementEmailAddressType: + var passportElement PassportElementEmailAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// DeletePassportElement Deletes a Telegram Passport element +// @param typeParam Element type +func (client *Client) DeletePassportElement(typeParam PassportElementType) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "deletePassportElement", + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetPassportElementErrors Informs the user that some of the elements in their Telegram Passport contain errors; for bots only. The user will not be able to resend the elements, until the errors are fixed +// @param userID User identifier +// @param errors The errors +func (client *Client) SetPassportElementErrors(userID int32, errors []InputPassportElementError) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setPassportElementErrors", + "user_id": userID, + "errors": errors, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetPreferredCountryLanguage Returns an IETF language tag of the language preferred in the country, which should be used to fill native fields in Telegram Passport personal details. Returns a 404 error if unknown +// @param countryCode A two-letter ISO 3166-1 alpha-2 country code +func (client *Client) GetPreferredCountryLanguage(countryCode string) (*Text, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getPreferredCountryLanguage", + "country_code": countryCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var text Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// SendPhoneNumberVerificationCode Sends a code to verify a phone number to be added to a user's Telegram Passport +// @param phoneNumber The phone number of the user, in international format +// @param allowFlashCall Pass true if the authentication code may be sent via flash call to the specified phone number +// @param isCurrentPhoneNumber Pass true if the phone number is used on the current device. Ignored if allow_flash_call is false +func (client *Client) SendPhoneNumberVerificationCode(phoneNumber string, allowFlashCall bool, isCurrentPhoneNumber bool) (*AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendPhoneNumberVerificationCode", + "phone_number": phoneNumber, + "allow_flash_call": allowFlashCall, + "is_current_phone_number": isCurrentPhoneNumber, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var authenticationCodeInfo AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// ResendPhoneNumberVerificationCode Re-sends the code to verify a phone number to be added to a user's Telegram Passport +func (client *Client) ResendPhoneNumberVerificationCode() (*AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "resendPhoneNumberVerificationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var authenticationCodeInfo AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// CheckPhoneNumberVerificationCode Checks the phone number verification code for Telegram Passport +// @param code Verification code +func (client *Client) CheckPhoneNumberVerificationCode(code string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkPhoneNumberVerificationCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendEmailAddressVerificationCode Sends a code to verify an email address to be added to a user's Telegram Passport +// @param emailAddress Email address +func (client *Client) SendEmailAddressVerificationCode(emailAddress string) (*EmailAddressAuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendEmailAddressVerificationCode", + "email_address": emailAddress, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var emailAddressAuthenticationCodeInfo EmailAddressAuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &emailAddressAuthenticationCodeInfo) + return &emailAddressAuthenticationCodeInfo, err + +} + +// ResendEmailAddressVerificationCode Re-sends the code to verify an email address to be added to a user's Telegram Passport +func (client *Client) ResendEmailAddressVerificationCode() (*EmailAddressAuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "resendEmailAddressVerificationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var emailAddressAuthenticationCodeInfo EmailAddressAuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &emailAddressAuthenticationCodeInfo) + return &emailAddressAuthenticationCodeInfo, err + +} + +// CheckEmailAddressVerificationCode Checks the email address verification code for Telegram Passport +// @param code Verification code +func (client *Client) CheckEmailAddressVerificationCode(code string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkEmailAddressVerificationCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetPassportAuthorizationForm Returns a Telegram Passport authorization form for sharing data with a service +// @param botUserID User identifier of the service's bot +// @param scope Telegram Passport element types requested by the service +// @param publicKey Service's public_key +// @param nonce Authorization form nonce provided by the service +// @param password Password of the current user +func (client *Client) GetPassportAuthorizationForm(botUserID int32, scope string, publicKey string, nonce string, password string) (*PassportAuthorizationForm, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getPassportAuthorizationForm", + "bot_user_id": botUserID, + "scope": scope, + "public_key": publicKey, + "nonce": nonce, + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var passportAuthorizationForm PassportAuthorizationForm + err = json.Unmarshal(result.Raw, &passportAuthorizationForm) + return &passportAuthorizationForm, err + +} + +// SendPassportAuthorizationForm Sends a Telegram Passport authorization form, effectively sharing data with the service +// @param autorizationFormID Authorization form identifier +// @param typeParams Types of Telegram Passport elements chosen by user to complete the authorization form +func (client *Client) SendPassportAuthorizationForm(autorizationFormID int32, typeParams []PassportElementType) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendPassportAuthorizationForm", + "autorization_form_id": autorizationFormID, + "types": typeParams, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendPhoneNumberConfirmationCode Sends phone number confirmation code. Should be called when user presses "https://t.me/confirmphone?phone=*******&hash=**********" or "tg://confirmphone?phone=*******&hash=**********" link +// @param hash Value of the "hash" parameter from the link +// @param phoneNumber Value of the "phone" parameter from the link +// @param allowFlashCall Pass true if the authentication code may be sent via flash call to the specified phone number +// @param isCurrentPhoneNumber Pass true if the phone number is used on the current device. Ignored if allow_flash_call is false +func (client *Client) SendPhoneNumberConfirmationCode(hash string, phoneNumber string, allowFlashCall bool, isCurrentPhoneNumber bool) (*AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendPhoneNumberConfirmationCode", + "hash": hash, + "phone_number": phoneNumber, + "allow_flash_call": allowFlashCall, + "is_current_phone_number": isCurrentPhoneNumber, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var authenticationCodeInfo AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// ResendPhoneNumberConfirmationCode Resends phone number confirmation code +func (client *Client) ResendPhoneNumberConfirmationCode() (*AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "resendPhoneNumberConfirmationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var authenticationCodeInfo AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// CheckPhoneNumberConfirmationCode Checks phone number confirmation code +// @param code The phone number confirmation code +func (client *Client) CheckPhoneNumberConfirmationCode(code string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "checkPhoneNumberConfirmationCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetBotUpdatesStatus Informs the server about the number of pending bot updates if they haven't been processed for a long time; for bots only +// @param pendingUpdateCount The number of pending updates +// @param errorMessage The last error message +func (client *Client) SetBotUpdatesStatus(pendingUpdateCount int32, errorMessage string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setBotUpdatesStatus", + "pending_update_count": pendingUpdateCount, + "error_message": errorMessage, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// UploadStickerFile Uploads a PNG image with a sticker; for bots only; returns the uploaded file +// @param userID Sticker file owner +// @param pngSticker PNG image with the sticker; must be up to 512 kB in size and fit in 512x512 square +func (client *Client) UploadStickerFile(userID int32, pngSticker InputFile) (*File, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "uploadStickerFile", + "user_id": userID, + "png_sticker": pngSticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var file File + err = json.Unmarshal(result.Raw, &file) + return &file, err + +} + +// CreateNewStickerSet Creates a new sticker set; for bots only. Returns the newly created sticker set +// @param userID Sticker set owner +// @param title Sticker set title; 1-64 characters +// @param name Sticker set name. Can contain only English letters, digits and underscores. Must end with *"_by_"* (** is case insensitive); 1-64 characters +// @param isMasks True, if stickers are masks +// @param stickers List of stickers to be added to the set +func (client *Client) CreateNewStickerSet(userID int32, title string, name string, isMasks bool, stickers []InputSticker) (*StickerSet, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "createNewStickerSet", + "user_id": userID, + "title": title, + "name": name, + "is_masks": isMasks, + "stickers": stickers, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSet StickerSet + err = json.Unmarshal(result.Raw, &stickerSet) + return &stickerSet, err + +} + +// AddStickerToSet Adds a new sticker to a set; for bots only. Returns the sticker set +// @param userID Sticker set owner +// @param name Sticker set name +// @param sticker Sticker to add to the set +func (client *Client) AddStickerToSet(userID int32, name string, sticker *InputSticker) (*StickerSet, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addStickerToSet", + "user_id": userID, + "name": name, + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var stickerSet StickerSet + err = json.Unmarshal(result.Raw, &stickerSet) + return &stickerSet, err + +} + +// SetStickerPositionInSet Changes the position of a sticker in the set to which it belongs; for bots only. The sticker set must have been created by the bot +// @param sticker Sticker +// @param position New position of the sticker in the set, zero-based +func (client *Client) SetStickerPositionInSet(sticker InputFile, position int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setStickerPositionInSet", + "sticker": sticker, + "position": position, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveStickerFromSet Removes a sticker from the set to which it belongs; for bots only. The sticker set must have been created by the bot +// @param sticker Sticker +func (client *Client) RemoveStickerFromSet(sticker InputFile) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeStickerFromSet", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetMapThumbnailFile Returns information about a file with a map thumbnail in PNG format. Only map thumbnail files with size less than 1MB can be downloaded +// @param location Location of the map center +// @param zoom Map zoom level; 13-20 +// @param width Map width in pixels before applying scale; 16-1024 +// @param height Map height in pixels before applying scale; 16-1024 +// @param scale Map scale; 1-3 +// @param chatID Identifier of a chat, in which the thumbnail will be shown. Use 0 if unknown +func (client *Client) GetMapThumbnailFile(location *Location, zoom int32, width int32, height int32, scale int32, chatID int64) (*File, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getMapThumbnailFile", + "location": location, + "zoom": zoom, + "width": width, + "height": height, + "scale": scale, + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var file File + err = json.Unmarshal(result.Raw, &file) + return &file, err + +} + +// AcceptTermsOfService Accepts Telegram terms of services +// @param termsOfServiceID Terms of service identifier +func (client *Client) AcceptTermsOfService(termsOfServiceID string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "acceptTermsOfService", + "terms_of_service_id": termsOfServiceID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendCustomRequest Sends a custom request; for bots only +// @param method The method name +// @param parameters JSON-serialized method parameters +func (client *Client) SendCustomRequest(method string, parameters string) (*CustomRequestResult, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "sendCustomRequest", + "method": method, + "parameters": parameters, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var customRequestResult CustomRequestResult + err = json.Unmarshal(result.Raw, &customRequestResult) + return &customRequestResult, err + +} + +// AnswerCustomQuery Answers a custom query; for bots only +// @param customQueryID Identifier of a custom query +// @param data JSON-serialized answer to the query +func (client *Client) AnswerCustomQuery(customQueryID JSONInt64, data string) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "answerCustomQuery", + "custom_query_id": customQueryID, + "data": data, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetAlarm Succeeds after a specified amount of time has passed. Can be called before authorization. Can be called before initialization +// @param seconds Number of seconds before the function returns +func (client *Client) SetAlarm(seconds float64) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "setAlarm", + "seconds": seconds, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetCountryCode Uses current user IP to found his country. Returns two-letter ISO 3166-1 alpha-2 country code. Can be called before authorization +func (client *Client) GetCountryCode() (*Text, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getCountryCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var text Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetInviteText Returns the default text for invitation messages to be used as a placeholder when the current user invites friends to Telegram +func (client *Client) GetInviteText() (*Text, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getInviteText", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var text Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetDeepLinkInfo Returns information about a tg:// deep link. Use "tg://need_update_for_some_feature" or "tg:some_unsupported_feature" for testing. Returns a 404 error for unknown links. Can be called before authorization +// @param link The link +func (client *Client) GetDeepLinkInfo(link string) (*DeepLinkInfo, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getDeepLinkInfo", + "link": link, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var deepLinkInfo DeepLinkInfo + err = json.Unmarshal(result.Raw, &deepLinkInfo) + return &deepLinkInfo, err + +} + +// AddProxy Adds a proxy server for network requests. Can be called before authorization +// @param server Proxy server IP address +// @param port Proxy server port +// @param enable True, if the proxy should be enabled +// @param typeParam Proxy type +func (client *Client) AddProxy(server string, port int32, enable bool, typeParam ProxyType) (*Proxy, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "addProxy", + "server": server, + "port": port, + "enable": enable, + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var proxy Proxy + err = json.Unmarshal(result.Raw, &proxy) + return &proxy, err + +} + +// EditProxy Edits an existing proxy server for network requests. Can be called before authorization +// @param proxyID Proxy identifier +// @param server Proxy server IP address +// @param port Proxy server port +// @param enable True, if the proxy should be enabled +// @param typeParam Proxy type +func (client *Client) EditProxy(proxyID int32, server string, port int32, enable bool, typeParam ProxyType) (*Proxy, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "editProxy", + "proxy_id": proxyID, + "server": server, + "port": port, + "enable": enable, + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var proxyDummy Proxy + err = json.Unmarshal(result.Raw, &proxyDummy) + return &proxyDummy, err + +} + +// EnableProxy Enables a proxy. Only one proxy can be enabled at a time. Can be called before authorization +// @param proxyID Proxy identifier +func (client *Client) EnableProxy(proxyID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "enableProxy", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DisableProxy Disables the currently enabled proxy. Can be called before authorization +func (client *Client) DisableProxy() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "disableProxy", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveProxy Removes a proxy server. Can be called before authorization +// @param proxyID Proxy identifier +func (client *Client) RemoveProxy(proxyID int32) (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "removeProxy", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// GetProxies Returns list of proxies that are currently set up. Can be called before authorization +func (client *Client) GetProxies() (*Proxies, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getProxies", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var proxies Proxies + err = json.Unmarshal(result.Raw, &proxies) + return &proxies, err + +} + +// GetProxyLink Returns an HTTPS link, which can be used to add a proxy. Available only for SOCKS5 and MTProto proxies. Can be called before authorization +// @param proxyID Proxy identifier +func (client *Client) GetProxyLink(proxyID int32) (*Text, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "getProxyLink", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var text Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// PingProxy Computes time needed to receive a response from a Telegram server through a proxy. Can be called before authorization +// @param proxyID Proxy identifier. Use 0 to ping a Telegram server without a proxy +func (client *Client) PingProxy(proxyID int32) (*Seconds, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "pingProxy", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var seconds Seconds + err = json.Unmarshal(result.Raw, &seconds) + return &seconds, err + +} + +// TestCallEmpty Does nothing; for testing only +func (client *Client) TestCallEmpty() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testCallEmpty", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TestCallString Returns the received string; for testing only +// @param x String to return +func (client *Client) TestCallString(x string) (*TestString, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testCallString", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var testString TestString + err = json.Unmarshal(result.Raw, &testString) + return &testString, err + +} + +// TestCallBytes Returns the received bytes; for testing only +// @param x Bytes to return +func (client *Client) TestCallBytes(x []byte) (*TestBytes, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testCallBytes", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var testBytes TestBytes + err = json.Unmarshal(result.Raw, &testBytes) + return &testBytes, err + +} + +// TestCallVectorInt Returns the received vector of numbers; for testing only +// @param x Vector of numbers to return +func (client *Client) TestCallVectorInt(x []int32) (*TestVectorInt, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testCallVectorInt", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var testVectorInt TestVectorInt + err = json.Unmarshal(result.Raw, &testVectorInt) + return &testVectorInt, err + +} + +// TestCallVectorIntObject Returns the received vector of objects containing a number; for testing only +// @param x Vector of objects to return +func (client *Client) TestCallVectorIntObject(x []TestInt) (*TestVectorIntObject, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testCallVectorIntObject", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var testVectorIntObject TestVectorIntObject + err = json.Unmarshal(result.Raw, &testVectorIntObject) + return &testVectorIntObject, err + +} + +// TestCallVectorString For testing only request. Returns the received vector of strings; for testing only +// @param x Vector of strings to return +func (client *Client) TestCallVectorString(x []string) (*TestVectorString, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testCallVectorString", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var testVectorString TestVectorString + err = json.Unmarshal(result.Raw, &testVectorString) + return &testVectorString, err + +} + +// TestCallVectorStringObject Returns the received vector of objects containing a string; for testing only +// @param x Vector of objects to return +func (client *Client) TestCallVectorStringObject(x []TestString) (*TestVectorStringObject, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testCallVectorStringObject", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var testVectorStringObject TestVectorStringObject + err = json.Unmarshal(result.Raw, &testVectorStringObject) + return &testVectorStringObject, err + +} + +// TestSquareInt Returns the squared received number; for testing only +// @param x Number to square +func (client *Client) TestSquareInt(x int32) (*TestInt, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testSquareInt", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var testInt TestInt + err = json.Unmarshal(result.Raw, &testInt) + return &testInt, err + +} + +// TestNetwork Sends a simple network request to the Telegram servers; for testing only +func (client *Client) TestNetwork() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testNetwork", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TestGetDifference Forces an updates.getDifference call to the Telegram servers; for testing only +func (client *Client) TestGetDifference() (*Ok, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testGetDifference", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var ok Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TestUseUpdate Does nothing and ensures that the Update object is used; for testing only +func (client *Client) TestUseUpdate() (Update, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testUseUpdate", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + switch UpdateEnum(result.Data["@type"].(string)) { + + case UpdateAuthorizationStateType: + var update UpdateAuthorizationState + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewMessageType: + var update UpdateNewMessage + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageSendAcknowledgedType: + var update UpdateMessageSendAcknowledged + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageSendSucceededType: + var update UpdateMessageSendSucceeded + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageSendFailedType: + var update UpdateMessageSendFailed + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageContentType: + var update UpdateMessageContent + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageEditedType: + var update UpdateMessageEdited + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageViewsType: + var update UpdateMessageViews + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageContentOpenedType: + var update UpdateMessageContentOpened + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateMessageMentionReadType: + var update UpdateMessageMentionRead + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewChatType: + var update UpdateNewChat + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatTitleType: + var update UpdateChatTitle + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatPhotoType: + var update UpdateChatPhoto + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatLastMessageType: + var update UpdateChatLastMessage + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatOrderType: + var update UpdateChatOrder + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatIsPinnedType: + var update UpdateChatIsPinned + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatIsMarkedAsUnreadType: + var update UpdateChatIsMarkedAsUnread + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatIsSponsoredType: + var update UpdateChatIsSponsored + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatDefaultDisableNotificationType: + var update UpdateChatDefaultDisableNotification + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatReadInboxType: + var update UpdateChatReadInbox + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatReadOutboxType: + var update UpdateChatReadOutbox + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatUnreadMentionCountType: + var update UpdateChatUnreadMentionCount + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatNotificationSettingsType: + var update UpdateChatNotificationSettings + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateScopeNotificationSettingsType: + var update UpdateScopeNotificationSettings + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatReplyMarkupType: + var update UpdateChatReplyMarkup + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateChatDraftMessageType: + var update UpdateChatDraftMessage + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateDeleteMessagesType: + var update UpdateDeleteMessages + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateUserChatActionType: + var update UpdateUserChatAction + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateUserStatusType: + var update UpdateUserStatus + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateUserType: + var update UpdateUser + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateBasicGroupType: + var update UpdateBasicGroup + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateSupergroupType: + var update UpdateSupergroup + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateSecretChatType: + var update UpdateSecretChat + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateUserFullInfoType: + var update UpdateUserFullInfo + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateBasicGroupFullInfoType: + var update UpdateBasicGroupFullInfo + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateSupergroupFullInfoType: + var update UpdateSupergroupFullInfo + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateServiceNotificationType: + var update UpdateServiceNotification + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateFileType: + var update UpdateFile + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateFileGenerationStartType: + var update UpdateFileGenerationStart + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateFileGenerationStopType: + var update UpdateFileGenerationStop + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateCallType: + var update UpdateCall + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateUserPrivacySettingRulesType: + var update UpdateUserPrivacySettingRules + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateUnreadMessageCountType: + var update UpdateUnreadMessageCount + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateUnreadChatCountType: + var update UpdateUnreadChatCount + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateOptionType: + var update UpdateOption + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateInstalledStickerSetsType: + var update UpdateInstalledStickerSets + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateTrendingStickerSetsType: + var update UpdateTrendingStickerSets + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateRecentStickersType: + var update UpdateRecentStickers + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateFavoriteStickersType: + var update UpdateFavoriteStickers + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateSavedAnimationsType: + var update UpdateSavedAnimations + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateLanguagePackStringsType: + var update UpdateLanguagePackStrings + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateConnectionStateType: + var update UpdateConnectionState + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateTermsOfServiceType: + var update UpdateTermsOfService + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewInlineQueryType: + var update UpdateNewInlineQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewChosenInlineResultType: + var update UpdateNewChosenInlineResult + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewCallbackQueryType: + var update UpdateNewCallbackQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewInlineCallbackQueryType: + var update UpdateNewInlineCallbackQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewShippingQueryType: + var update UpdateNewShippingQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewPreCheckoutQueryType: + var update UpdateNewPreCheckoutQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewCustomEventType: + var update UpdateNewCustomEvent + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case UpdateNewCustomQueryType: + var update UpdateNewCustomQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// TestUseError Does nothing and ensures that the Error object is used; for testing only +func (client *Client) TestUseError() (*Error, error) { + result, err := client.SendAndCatch(UpdateData{ + "@type": "testUseError", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, fmt.Errorf("error! code: %d msg: %s", result.Data["code"], result.Data["message"]) + } + + var error Error + err = json.Unmarshal(result.Raw, &error) + return &error, err + +} diff --git a/vendor/github.com/Arman92/go-tdlib/tdlib.go b/vendor/github.com/Arman92/go-tdlib/tdlib.go new file mode 100644 index 0000000..785372a --- /dev/null +++ b/vendor/github.com/Arman92/go-tdlib/tdlib.go @@ -0,0 +1,349 @@ +package tdlib + +//#cgo linux CFLAGS: -I/usr/local/include +//#cgo darwin CFLAGS: -I/usr/local/include +//#cgo windows CFLAGS: -IC:/src/td -IC:/src/td/build +//#cgo linux LDFLAGS: -L/usr/local/lib -ltdjson_static -ltdjson_private -ltdclient -ltdcore -ltdactor -ltddb -ltdsqlite -ltdnet -ltdutils -lstdc++ -lssl -lcrypto -ldl -lz -lm +//#cgo darwin LDFLAGS: -L/usr/local/lib -L/usr/local/opt/openssl/lib -ltdjson_static -ltdjson_private -ltdclient -ltdcore -ltdactor -ltddb -ltdsqlite -ltdnet -ltdutils -lstdc++ -lssl -lcrypto -ldl -lz -lm +//#cgo windows LDFLAGS: -LC:/src/td/build/Debug -ltdjson +//#include +//#include +//#include +import "C" + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "sync" + "time" + "unsafe" +) + +// UpdateData alias for use in UpdateMsg +type UpdateData map[string]interface{} + +// UpdateMsg is used to unmarshal recieved json strings into +type UpdateMsg struct { + Data UpdateData + Raw []byte +} + +// EventFilterFunc used to filter out unwanted messages in receiver channels +type EventFilterFunc func(msg *TdMessage) bool + +// EventReceiver used to retreive updates from tdlib to user +type EventReceiver struct { + Instance TdMessage + Chan chan TdMessage + FilterFunc EventFilterFunc +} + +// Client is the Telegram TdLib client +type Client struct { + Client unsafe.Pointer + Config Config + rawUpdates chan UpdateMsg + receivers []EventReceiver + waiters sync.Map + receiverLock *sync.Mutex +} + +// Config holds tdlibParameters +type Config struct { + APIID string // Application identifier for Telegram API access, which can be obtained at https://my.telegram.org --- must be non-empty.. + APIHash string // Application identifier hash for Telegram API access, which can be obtained at https://my.telegram.org --- must be non-empty.. + SystemLanguageCode string // IETF language tag of the user's operating system language; must be non-empty. + DeviceModel string // Model of the device the application is being run on; must be non-empty. + SystemVersion string // Version of the operating system the application is being run on; must be non-empty. + ApplicationVersion string // Application version; must be non-empty. + // Optional fields + UseTestDataCenter bool // if set to true, the Telegram test environment will be used instead of the production environment. + DatabaseDirectory string // The path to the directory for the persistent database; if empty, the current working directory will be used. + FileDirectory string // The path to the directory for storing files; if empty, database_directory will be used. + UseFileDatabase bool // If set to true, information about downloaded and uploaded files will be saved between application restarts. + UseChatInfoDatabase bool // If set to true, the library will maintain a cache of users, basic groups, supergroups, channels and secret chats. Implies use_file_database. + UseMessageDatabase bool // If set to true, the library will maintain a cache of chats and messages. Implies use_chat_info_database. + UseSecretChats bool // If set to true, support for secret chats will be enabled. + EnableStorageOptimizer bool // If set to true, old files will automatically be deleted. + IgnoreFileNames bool // If set to true, original file names will be ignored. Otherwise, downloaded files will be saved under names as close as possible to the original name. +} + +// NewClient Creates a new instance of TDLib. +// Has two public fields: +// Client itself and RawUpdates channel +func NewClient(config Config) *Client { + // Seed rand with time + rand.Seed(time.Now().UnixNano()) + + client := Client{Client: C.td_json_client_create()} + client.receivers = make([]EventReceiver, 0, 1) + client.receiverLock = &sync.Mutex{} + client.Config = config + + go func() { + for { + // get update + updateBytes := client.Receive(10) + var updateData UpdateData + json.Unmarshal(updateBytes, &updateData) + + // does new update has @extra field? + if extra, hasExtra := updateData["@extra"].(string); hasExtra { + + // trying to load update with this salt + if waiter, found := client.waiters.Load(extra); found { + // found? send it to waiter channel + waiter.(chan UpdateMsg) <- UpdateMsg{Data: updateData, Raw: updateBytes} + + // trying to prevent memory leak + close(waiter.(chan UpdateMsg)) + } + } else { + // does new updates has @type field? + if msgType, hasType := updateData["@type"]; hasType { + + if client.rawUpdates != nil { + // if rawUpdates is initialized, send the update in rawUpdates channel + client.rawUpdates <- UpdateMsg{Data: updateData, Raw: updateBytes} + } + + client.receiverLock.Lock() + for _, receiver := range client.receivers { + if msgType == receiver.Instance.MessageType() { + var newMsg TdMessage + newMsg = reflect.New(reflect.ValueOf(receiver.Instance).Elem().Type()).Interface().(TdMessage) + + err := json.Unmarshal(updateBytes, &newMsg) + if err != nil { + fmt.Printf("Error unmarhaling to type %v", err) + } + if receiver.FilterFunc(&newMsg) { + receiver.Chan <- newMsg + } + } + } + client.receiverLock.Unlock() + } + } + } + }() + + return &client +} + +// GetRawUpdatesChannel creates a general channel that fetches every update comming from tdlib +func (client *Client) GetRawUpdatesChannel(capacity int) chan UpdateMsg { + client.rawUpdates = make(chan UpdateMsg, capacity) + return client.rawUpdates +} + +// AddEventReceiver adds a new receiver to be subscribed in receiver channels +func (client *Client) AddEventReceiver(msgInstance TdMessage, filterFunc EventFilterFunc, channelCapacity int) EventReceiver { + receiver := EventReceiver{ + Instance: msgInstance, + Chan: make(chan TdMessage, channelCapacity), + FilterFunc: filterFunc, + } + + client.receiverLock.Lock() + defer client.receiverLock.Unlock() + client.receivers = append(client.receivers, receiver) + + return receiver +} + +// DestroyInstance Destroys the TDLib client instance. +// After this is called the client instance shouldn't be used anymore. +func (client *Client) DestroyInstance() { + C.td_json_client_destroy(client.Client) +} + +// Send Sends request to the TDLib client. +// You can provide string or UpdateData. +func (client *Client) Send(jsonQuery interface{}) { + var query *C.char + + switch jsonQuery.(type) { + case string: + query = C.CString(jsonQuery.(string)) + case UpdateData: + jsonBytes, _ := json.Marshal(jsonQuery.(UpdateData)) + query = C.CString(string(jsonBytes)) + } + + defer C.free(unsafe.Pointer(query)) + C.td_json_client_send(client.Client, query) +} + +// Receive Receives incoming updates and request responses from the TDLib client. +// You can provide string or UpdateData. +func (client *Client) Receive(timeout float64) []byte { + result := C.td_json_client_receive(client.Client, C.double(timeout)) + + return []byte(C.GoString(result)) +} + +// Execute Synchronously executes TDLib request. +// Only a few requests can be executed synchronously. +func (client *Client) Execute(jsonQuery interface{}) UpdateMsg { + var query *C.char + + switch jsonQuery.(type) { + case string: + query = C.CString(jsonQuery.(string)) + case UpdateData: + jsonBytes, _ := json.Marshal(jsonQuery.(UpdateData)) + query = C.CString(string(jsonBytes)) + } + + defer C.free(unsafe.Pointer(query)) + result := C.td_json_client_execute(client.Client, query) + + var update UpdateData + json.Unmarshal([]byte(C.GoString(result)), &update) + return UpdateMsg{Data: update, Raw: []byte(C.GoString(result))} +} + +// SetFilePath Sets the path to the file to where the internal TDLib log will be written. +// By default TDLib writes logs to stderr or an OS specific log. +// Use this method to write the log to a file instead. +func SetFilePath(path string) { + query := C.CString(path) + defer C.free(unsafe.Pointer(query)) + + C.td_set_log_file_path(query) +} + +// SetLogVerbosityLevel Sets the verbosity level of the internal logging of TDLib. +// By default the TDLib uses a verbosity level of 5 for logging. +func SetLogVerbosityLevel(level int) { + C.td_set_log_verbosity_level(C.int(level)) +} + +// SendAndCatch Sends request to the TDLib client and catches the result in updates channel. +// You can provide string or UpdateData. +func (client *Client) SendAndCatch(jsonQuery interface{}) (UpdateMsg, error) { + var update UpdateData + + switch jsonQuery.(type) { + case string: + // unmarshal JSON into map, we don't have @extra field, if user don't set it + json.Unmarshal([]byte(jsonQuery.(string)), &update) + case UpdateData: + update = jsonQuery.(UpdateData) + } + + // letters for generating random string + letterBytes := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + + // generate random string for @extra field + b := make([]byte, 32) + for i := range b { + b[i] = letterBytes[rand.Intn(len(letterBytes))] + } + randomString := string(b) + + // set @extra field + update["@extra"] = randomString + + // create waiter chan and save it in Waiters + waiter := make(chan UpdateMsg, 1) + client.waiters.Store(randomString, waiter) + + // send it through already implemented method + client.Send(update) + + select { + // wait response from main loop in NewClient() + case response := <-waiter: + return response, nil + // or timeout + case <-time.After(10 * time.Second): + client.waiters.Delete(randomString) + return UpdateMsg{}, errors.New("timeout") + } +} + +// Authorize is used to authorize the users +func (client *Client) Authorize() (AuthorizationState, error) { + state, err := client.GetAuthorizationState() + if err != nil { + return nil, err + } + + if state.GetAuthorizationStateEnum() == AuthorizationStateWaitEncryptionKeyType { + ok, err := client.CheckDatabaseEncryptionKey(nil) + + if ok == nil || err != nil { + return nil, err + } + } else if state.GetAuthorizationStateEnum() == AuthorizationStateWaitTdlibParametersType { + client.sendTdLibParams() + } + + authState, err := client.GetAuthorizationState() + return authState, err +} + +func (client *Client) sendTdLibParams() { + client.Send(UpdateData{ + "@type": "setTdlibParameters", + "parameters": UpdateData{ + "@type": "tdlibParameters", + "use_test_dc": client.Config.UseTestDataCenter, + "database_directory": client.Config.DatabaseDirectory, + "files_directory": client.Config.FileDirectory, + "use_file_database": client.Config.UseFileDatabase, + "use_chat_info_database": client.Config.UseChatInfoDatabase, + "use_message_database": client.Config.UseMessageDatabase, + "use_secret_chats": client.Config.UseSecretChats, + "api_id": client.Config.APIID, + "api_hash": client.Config.APIHash, + "system_language_code": client.Config.SystemLanguageCode, + "device_model": client.Config.DeviceModel, + "system_version": client.Config.SystemVersion, + "application_version": client.Config.ApplicationVersion, + "enable_storage_optimizer": client.Config.EnableStorageOptimizer, + "ignore_file_names": client.Config.IgnoreFileNames, + }, + }) +} + +// SendPhoneNumber sends phone number to tdlib +func (client *Client) SendPhoneNumber(phoneNumber string) (AuthorizationState, error) { + _, err := client.SetAuthenticationPhoneNumber(phoneNumber, false, false) + + if err != nil { + return nil, err + } + + authState, err := client.GetAuthorizationState() + return authState, err +} + +// SendAuthCode sends auth code to tdlib +func (client *Client) SendAuthCode(code string) (AuthorizationState, error) { + _, err := client.CheckAuthenticationCode(code, "", "") + + if err != nil { + return nil, err + } + + authState, err := client.GetAuthorizationState() + return authState, err +} + +// SendAuthPassword sends two-step verification password (user defined)to tdlib +func (client *Client) SendAuthPassword(password string) (AuthorizationState, error) { + _, err := client.CheckAuthenticationPassword(password) + + if err != nil { + return nil, err + } + + authState, err := client.GetAuthorizationState() + return authState, err +} diff --git a/vendor/github.com/Arman92/go-tdlib/types.go b/vendor/github.com/Arman92/go-tdlib/types.go new file mode 100755 index 0000000..6c32bdb --- /dev/null +++ b/vendor/github.com/Arman92/go-tdlib/types.go @@ -0,0 +1,25335 @@ +package tdlib + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" +) + +type tdCommon struct { + Type string `json:"@type"` + Extra string `json:"@extra"` +} + +// JSONInt64 alias for int64, in order to deal with json big number problem +type JSONInt64 int64 + +// MarshalJSON marshals to json +func (jsonInt *JSONInt64) MarshalJSON() ([]byte, error) { + intStr := strconv.FormatInt(int64(*jsonInt), 10) + return []byte(intStr), nil +} + +// UnmarshalJSON unmarshals from json +func (jsonInt *JSONInt64) UnmarshalJSON(b []byte) error { + intStr := string(b) + intStr = strings.Replace(intStr, "\"", "", 2) + jsonBigInt, err := strconv.ParseInt(intStr, 10, 64) + if err != nil { + return err + } + *jsonInt = JSONInt64(jsonBigInt) + return nil +} + +// TdMessage is the interface for all messages send and received to/from tdlib +type TdMessage interface { + MessageType() string +} + +// AuthenticationCodeTypeEnum Alias for abstract AuthenticationCodeType 'Sub-Classes', used as constant-enum here +type AuthenticationCodeTypeEnum string + +// AuthenticationCodeType enums +const ( + AuthenticationCodeTypeTelegramMessageType AuthenticationCodeTypeEnum = "authenticationCodeTypeTelegramMessage" + AuthenticationCodeTypeSmsType AuthenticationCodeTypeEnum = "authenticationCodeTypeSms" + AuthenticationCodeTypeCallType AuthenticationCodeTypeEnum = "authenticationCodeTypeCall" + AuthenticationCodeTypeFlashCallType AuthenticationCodeTypeEnum = "authenticationCodeTypeFlashCall" +) + +// AuthorizationStateEnum Alias for abstract AuthorizationState 'Sub-Classes', used as constant-enum here +type AuthorizationStateEnum string + +// AuthorizationState enums +const ( + AuthorizationStateWaitTdlibParametersType AuthorizationStateEnum = "authorizationStateWaitTdlibParameters" + AuthorizationStateWaitEncryptionKeyType AuthorizationStateEnum = "authorizationStateWaitEncryptionKey" + AuthorizationStateWaitPhoneNumberType AuthorizationStateEnum = "authorizationStateWaitPhoneNumber" + AuthorizationStateWaitCodeType AuthorizationStateEnum = "authorizationStateWaitCode" + AuthorizationStateWaitPasswordType AuthorizationStateEnum = "authorizationStateWaitPassword" + AuthorizationStateReadyType AuthorizationStateEnum = "authorizationStateReady" + AuthorizationStateLoggingOutType AuthorizationStateEnum = "authorizationStateLoggingOut" + AuthorizationStateClosingType AuthorizationStateEnum = "authorizationStateClosing" + AuthorizationStateClosedType AuthorizationStateEnum = "authorizationStateClosed" +) + +// InputFileEnum Alias for abstract InputFile 'Sub-Classes', used as constant-enum here +type InputFileEnum string + +// InputFile enums +const ( + InputFileIDType InputFileEnum = "inputFileID" + InputFileRemoteType InputFileEnum = "inputFileRemote" + InputFileLocalType InputFileEnum = "inputFileLocal" + InputFileGeneratedType InputFileEnum = "inputFileGenerated" +) + +// MaskPointEnum Alias for abstract MaskPoint 'Sub-Classes', used as constant-enum here +type MaskPointEnum string + +// MaskPoint enums +const ( + MaskPointForeheadType MaskPointEnum = "maskPointForehead" + MaskPointEyesType MaskPointEnum = "maskPointEyes" + MaskPointMouthType MaskPointEnum = "maskPointMouth" + MaskPointChinType MaskPointEnum = "maskPointChin" +) + +// LinkStateEnum Alias for abstract LinkState 'Sub-Classes', used as constant-enum here +type LinkStateEnum string + +// LinkState enums +const ( + LinkStateNoneType LinkStateEnum = "linkStateNone" + LinkStateKnowsPhoneNumberType LinkStateEnum = "linkStateKnowsPhoneNumber" + LinkStateIsContactType LinkStateEnum = "linkStateIsContact" +) + +// UserTypeEnum Alias for abstract UserType 'Sub-Classes', used as constant-enum here +type UserTypeEnum string + +// UserType enums +const ( + UserTypeRegularType UserTypeEnum = "userTypeRegular" + UserTypeDeletedType UserTypeEnum = "userTypeDeleted" + UserTypeBotType UserTypeEnum = "userTypeBot" + UserTypeUnknownType UserTypeEnum = "userTypeUnknown" +) + +// ChatMemberStatusEnum Alias for abstract ChatMemberStatus 'Sub-Classes', used as constant-enum here +type ChatMemberStatusEnum string + +// ChatMemberStatus enums +const ( + ChatMemberStatusCreatorType ChatMemberStatusEnum = "chatMemberStatusCreator" + ChatMemberStatusAdministratorType ChatMemberStatusEnum = "chatMemberStatusAdministrator" + ChatMemberStatusMemberType ChatMemberStatusEnum = "chatMemberStatusMember" + ChatMemberStatusRestrictedType ChatMemberStatusEnum = "chatMemberStatusRestricted" + ChatMemberStatusLeftType ChatMemberStatusEnum = "chatMemberStatusLeft" + ChatMemberStatusBannedType ChatMemberStatusEnum = "chatMemberStatusBanned" +) + +// ChatMembersFilterEnum Alias for abstract ChatMembersFilter 'Sub-Classes', used as constant-enum here +type ChatMembersFilterEnum string + +// ChatMembersFilter enums +const ( + ChatMembersFilterAdministratorsType ChatMembersFilterEnum = "chatMembersFilterAdministrators" + ChatMembersFilterMembersType ChatMembersFilterEnum = "chatMembersFilterMembers" + ChatMembersFilterRestrictedType ChatMembersFilterEnum = "chatMembersFilterRestricted" + ChatMembersFilterBannedType ChatMembersFilterEnum = "chatMembersFilterBanned" + ChatMembersFilterBotsType ChatMembersFilterEnum = "chatMembersFilterBots" +) + +// SupergroupMembersFilterEnum Alias for abstract SupergroupMembersFilter 'Sub-Classes', used as constant-enum here +type SupergroupMembersFilterEnum string + +// SupergroupMembersFilter enums +const ( + SupergroupMembersFilterRecentType SupergroupMembersFilterEnum = "supergroupMembersFilterRecent" + SupergroupMembersFilterAdministratorsType SupergroupMembersFilterEnum = "supergroupMembersFilterAdministrators" + SupergroupMembersFilterSearchType SupergroupMembersFilterEnum = "supergroupMembersFilterSearch" + SupergroupMembersFilterRestrictedType SupergroupMembersFilterEnum = "supergroupMembersFilterRestricted" + SupergroupMembersFilterBannedType SupergroupMembersFilterEnum = "supergroupMembersFilterBanned" + SupergroupMembersFilterBotsType SupergroupMembersFilterEnum = "supergroupMembersFilterBots" +) + +// SecretChatStateEnum Alias for abstract SecretChatState 'Sub-Classes', used as constant-enum here +type SecretChatStateEnum string + +// SecretChatState enums +const ( + SecretChatStatePendingType SecretChatStateEnum = "secretChatStatePending" + SecretChatStateReadyType SecretChatStateEnum = "secretChatStateReady" + SecretChatStateClosedType SecretChatStateEnum = "secretChatStateClosed" +) + +// MessageForwardInfoEnum Alias for abstract MessageForwardInfo 'Sub-Classes', used as constant-enum here +type MessageForwardInfoEnum string + +// MessageForwardInfo enums +const ( + MessageForwardedFromUserType MessageForwardInfoEnum = "messageForwardedFromUser" + MessageForwardedPostType MessageForwardInfoEnum = "messageForwardedPost" +) + +// MessageSendingStateEnum Alias for abstract MessageSendingState 'Sub-Classes', used as constant-enum here +type MessageSendingStateEnum string + +// MessageSendingState enums +const ( + MessageSendingStatePendingType MessageSendingStateEnum = "messageSendingStatePending" + MessageSendingStateFailedType MessageSendingStateEnum = "messageSendingStateFailed" +) + +// NotificationSettingsScopeEnum Alias for abstract NotificationSettingsScope 'Sub-Classes', used as constant-enum here +type NotificationSettingsScopeEnum string + +// NotificationSettingsScope enums +const ( + NotificationSettingsScopePrivateChatsType NotificationSettingsScopeEnum = "notificationSettingsScopePrivateChats" + NotificationSettingsScopeGroupChatsType NotificationSettingsScopeEnum = "notificationSettingsScopeGroupChats" +) + +// ChatTypeEnum Alias for abstract ChatType 'Sub-Classes', used as constant-enum here +type ChatTypeEnum string + +// ChatType enums +const ( + ChatTypePrivateType ChatTypeEnum = "chatTypePrivate" + ChatTypeBasicGroupType ChatTypeEnum = "chatTypeBasicGroup" + ChatTypeSupergroupType ChatTypeEnum = "chatTypeSupergroup" + ChatTypeSecretType ChatTypeEnum = "chatTypeSecret" +) + +// KeyboardButtonTypeEnum Alias for abstract KeyboardButtonType 'Sub-Classes', used as constant-enum here +type KeyboardButtonTypeEnum string + +// KeyboardButtonType enums +const ( + KeyboardButtonTypeTextType KeyboardButtonTypeEnum = "keyboardButtonTypeText" + KeyboardButtonTypeRequestPhoneNumberType KeyboardButtonTypeEnum = "keyboardButtonTypeRequestPhoneNumber" + KeyboardButtonTypeRequestLocationType KeyboardButtonTypeEnum = "keyboardButtonTypeRequestLocation" +) + +// InlineKeyboardButtonTypeEnum Alias for abstract InlineKeyboardButtonType 'Sub-Classes', used as constant-enum here +type InlineKeyboardButtonTypeEnum string + +// InlineKeyboardButtonType enums +const ( + InlineKeyboardButtonTypeURLType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeURL" + InlineKeyboardButtonTypeCallbackType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeCallback" + InlineKeyboardButtonTypeCallbackGameType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeCallbackGame" + InlineKeyboardButtonTypeSwitchInlineType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeSwitchInline" + InlineKeyboardButtonTypeBuyType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeBuy" +) + +// ReplyMarkupEnum Alias for abstract ReplyMarkup 'Sub-Classes', used as constant-enum here +type ReplyMarkupEnum string + +// ReplyMarkup enums +const ( + ReplyMarkupRemoveKeyboardType ReplyMarkupEnum = "replyMarkupRemoveKeyboard" + ReplyMarkupForceReplyType ReplyMarkupEnum = "replyMarkupForceReply" + ReplyMarkupShowKeyboardType ReplyMarkupEnum = "replyMarkupShowKeyboard" + ReplyMarkupInlineKeyboardType ReplyMarkupEnum = "replyMarkupInlineKeyboard" +) + +// RichTextEnum Alias for abstract RichText 'Sub-Classes', used as constant-enum here +type RichTextEnum string + +// RichText enums +const ( + RichTextPlainType RichTextEnum = "richTextPlain" + RichTextBoldType RichTextEnum = "richTextBold" + RichTextItalicType RichTextEnum = "richTextItalic" + RichTextUnderlineType RichTextEnum = "richTextUnderline" + RichTextStrikethroughType RichTextEnum = "richTextStrikethrough" + RichTextFixedType RichTextEnum = "richTextFixed" + RichTextURLType RichTextEnum = "richTextURL" + RichTextEmailAddressType RichTextEnum = "richTextEmailAddress" + RichTextsType RichTextEnum = "richTexts" +) + +// PageBlockEnum Alias for abstract PageBlock 'Sub-Classes', used as constant-enum here +type PageBlockEnum string + +// PageBlock enums +const ( + PageBlockTitleType PageBlockEnum = "pageBlockTitle" + PageBlockSubtitleType PageBlockEnum = "pageBlockSubtitle" + PageBlockAuthorDateType PageBlockEnum = "pageBlockAuthorDate" + PageBlockHeaderType PageBlockEnum = "pageBlockHeader" + PageBlockSubheaderType PageBlockEnum = "pageBlockSubheader" + PageBlockParagraphType PageBlockEnum = "pageBlockParagraph" + PageBlockPreformattedType PageBlockEnum = "pageBlockPreformatted" + PageBlockFooterType PageBlockEnum = "pageBlockFooter" + PageBlockDividerType PageBlockEnum = "pageBlockDivider" + PageBlockAnchorType PageBlockEnum = "pageBlockAnchor" + PageBlockListType PageBlockEnum = "pageBlockList" + PageBlockBlockQuoteType PageBlockEnum = "pageBlockBlockQuote" + PageBlockPullQuoteType PageBlockEnum = "pageBlockPullQuote" + PageBlockAnimationType PageBlockEnum = "pageBlockAnimation" + PageBlockAudioType PageBlockEnum = "pageBlockAudio" + PageBlockPhotoType PageBlockEnum = "pageBlockPhoto" + PageBlockVideoType PageBlockEnum = "pageBlockVideo" + PageBlockCoverType PageBlockEnum = "pageBlockCover" + PageBlockEmbeddedType PageBlockEnum = "pageBlockEmbedded" + PageBlockEmbeddedPostType PageBlockEnum = "pageBlockEmbeddedPost" + PageBlockCollageType PageBlockEnum = "pageBlockCollage" + PageBlockSlideshowType PageBlockEnum = "pageBlockSlideshow" + PageBlockChatLinkType PageBlockEnum = "pageBlockChatLink" +) + +// InputCredentialsEnum Alias for abstract InputCredentials 'Sub-Classes', used as constant-enum here +type InputCredentialsEnum string + +// InputCredentials enums +const ( + InputCredentialsSavedType InputCredentialsEnum = "inputCredentialsSaved" + InputCredentialsNewType InputCredentialsEnum = "inputCredentialsNew" + InputCredentialsAndroidPayType InputCredentialsEnum = "inputCredentialsAndroidPay" + InputCredentialsApplePayType InputCredentialsEnum = "inputCredentialsApplePay" +) + +// PassportElementTypeEnum Alias for abstract PassportElementType 'Sub-Classes', used as constant-enum here +type PassportElementTypeEnum string + +// PassportElementType enums +const ( + PassportElementTypePersonalDetailsType PassportElementTypeEnum = "passportElementTypePersonalDetails" + PassportElementTypePassportType PassportElementTypeEnum = "passportElementTypePassport" + PassportElementTypeDriverLicenseType PassportElementTypeEnum = "passportElementTypeDriverLicense" + PassportElementTypeIDentityCardType PassportElementTypeEnum = "passportElementTypeIDentityCard" + PassportElementTypeInternalPassportType PassportElementTypeEnum = "passportElementTypeInternalPassport" + PassportElementTypeAddressType PassportElementTypeEnum = "passportElementTypeAddress" + PassportElementTypeUtilityBillType PassportElementTypeEnum = "passportElementTypeUtilityBill" + PassportElementTypeBankStatementType PassportElementTypeEnum = "passportElementTypeBankStatement" + PassportElementTypeRentalAgreementType PassportElementTypeEnum = "passportElementTypeRentalAgreement" + PassportElementTypePassportRegistrationType PassportElementTypeEnum = "passportElementTypePassportRegistration" + PassportElementTypeTemporaryRegistrationType PassportElementTypeEnum = "passportElementTypeTemporaryRegistration" + PassportElementTypePhoneNumberType PassportElementTypeEnum = "passportElementTypePhoneNumber" + PassportElementTypeEmailAddressType PassportElementTypeEnum = "passportElementTypeEmailAddress" +) + +// PassportElementEnum Alias for abstract PassportElement 'Sub-Classes', used as constant-enum here +type PassportElementEnum string + +// PassportElement enums +const ( + PassportElementPersonalDetailsType PassportElementEnum = "passportElementPersonalDetails" + PassportElementPassportType PassportElementEnum = "passportElementPassport" + PassportElementDriverLicenseType PassportElementEnum = "passportElementDriverLicense" + PassportElementIDentityCardType PassportElementEnum = "passportElementIDentityCard" + PassportElementInternalPassportType PassportElementEnum = "passportElementInternalPassport" + PassportElementAddressType PassportElementEnum = "passportElementAddress" + PassportElementUtilityBillType PassportElementEnum = "passportElementUtilityBill" + PassportElementBankStatementType PassportElementEnum = "passportElementBankStatement" + PassportElementRentalAgreementType PassportElementEnum = "passportElementRentalAgreement" + PassportElementPassportRegistrationType PassportElementEnum = "passportElementPassportRegistration" + PassportElementTemporaryRegistrationType PassportElementEnum = "passportElementTemporaryRegistration" + PassportElementPhoneNumberType PassportElementEnum = "passportElementPhoneNumber" + PassportElementEmailAddressType PassportElementEnum = "passportElementEmailAddress" +) + +// InputPassportElementEnum Alias for abstract InputPassportElement 'Sub-Classes', used as constant-enum here +type InputPassportElementEnum string + +// InputPassportElement enums +const ( + InputPassportElementPersonalDetailsType InputPassportElementEnum = "inputPassportElementPersonalDetails" + InputPassportElementPassportType InputPassportElementEnum = "inputPassportElementPassport" + InputPassportElementDriverLicenseType InputPassportElementEnum = "inputPassportElementDriverLicense" + InputPassportElementIDentityCardType InputPassportElementEnum = "inputPassportElementIDentityCard" + InputPassportElementInternalPassportType InputPassportElementEnum = "inputPassportElementInternalPassport" + InputPassportElementAddressType InputPassportElementEnum = "inputPassportElementAddress" + InputPassportElementUtilityBillType InputPassportElementEnum = "inputPassportElementUtilityBill" + InputPassportElementBankStatementType InputPassportElementEnum = "inputPassportElementBankStatement" + InputPassportElementRentalAgreementType InputPassportElementEnum = "inputPassportElementRentalAgreement" + InputPassportElementPassportRegistrationType InputPassportElementEnum = "inputPassportElementPassportRegistration" + InputPassportElementTemporaryRegistrationType InputPassportElementEnum = "inputPassportElementTemporaryRegistration" + InputPassportElementPhoneNumberType InputPassportElementEnum = "inputPassportElementPhoneNumber" + InputPassportElementEmailAddressType InputPassportElementEnum = "inputPassportElementEmailAddress" +) + +// PassportElementErrorSourceEnum Alias for abstract PassportElementErrorSource 'Sub-Classes', used as constant-enum here +type PassportElementErrorSourceEnum string + +// PassportElementErrorSource enums +const ( + PassportElementErrorSourceUnspecifiedType PassportElementErrorSourceEnum = "passportElementErrorSourceUnspecified" + PassportElementErrorSourceDataFieldType PassportElementErrorSourceEnum = "passportElementErrorSourceDataField" + PassportElementErrorSourceFrontSideType PassportElementErrorSourceEnum = "passportElementErrorSourceFrontSide" + PassportElementErrorSourceReverseSideType PassportElementErrorSourceEnum = "passportElementErrorSourceReverseSide" + PassportElementErrorSourceSelfieType PassportElementErrorSourceEnum = "passportElementErrorSourceSelfie" + PassportElementErrorSourceTranslationFileType PassportElementErrorSourceEnum = "passportElementErrorSourceTranslationFile" + PassportElementErrorSourceTranslationFilesType PassportElementErrorSourceEnum = "passportElementErrorSourceTranslationFiles" + PassportElementErrorSourceFileType PassportElementErrorSourceEnum = "passportElementErrorSourceFile" + PassportElementErrorSourceFilesType PassportElementErrorSourceEnum = "passportElementErrorSourceFiles" +) + +// InputPassportElementErrorSourceEnum Alias for abstract InputPassportElementErrorSource 'Sub-Classes', used as constant-enum here +type InputPassportElementErrorSourceEnum string + +// InputPassportElementErrorSource enums +const ( + InputPassportElementErrorSourceUnspecifiedType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceUnspecified" + InputPassportElementErrorSourceDataFieldType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceDataField" + InputPassportElementErrorSourceFrontSideType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceFrontSide" + InputPassportElementErrorSourceReverseSideType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceReverseSide" + InputPassportElementErrorSourceSelfieType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceSelfie" + InputPassportElementErrorSourceTranslationFileType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceTranslationFile" + InputPassportElementErrorSourceTranslationFilesType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceTranslationFiles" + InputPassportElementErrorSourceFileType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceFile" + InputPassportElementErrorSourceFilesType InputPassportElementErrorSourceEnum = "inputPassportElementErrorSourceFiles" +) + +// MessageContentEnum Alias for abstract MessageContent 'Sub-Classes', used as constant-enum here +type MessageContentEnum string + +// MessageContent enums +const ( + MessageTextType MessageContentEnum = "messageText" + MessageAnimationType MessageContentEnum = "messageAnimation" + MessageAudioType MessageContentEnum = "messageAudio" + MessageDocumentType MessageContentEnum = "messageDocument" + MessagePhotoType MessageContentEnum = "messagePhoto" + MessageExpiredPhotoType MessageContentEnum = "messageExpiredPhoto" + MessageStickerType MessageContentEnum = "messageSticker" + MessageVideoType MessageContentEnum = "messageVideo" + MessageExpiredVideoType MessageContentEnum = "messageExpiredVideo" + MessageVideoNoteType MessageContentEnum = "messageVideoNote" + MessageVoiceNoteType MessageContentEnum = "messageVoiceNote" + MessageLocationType MessageContentEnum = "messageLocation" + MessageVenueType MessageContentEnum = "messageVenue" + MessageContactType MessageContentEnum = "messageContact" + MessageGameType MessageContentEnum = "messageGame" + MessageInvoiceType MessageContentEnum = "messageInvoice" + MessageCallType MessageContentEnum = "messageCall" + MessageBasicGroupChatCreateType MessageContentEnum = "messageBasicGroupChatCreate" + MessageSupergroupChatCreateType MessageContentEnum = "messageSupergroupChatCreate" + MessageChatChangeTitleType MessageContentEnum = "messageChatChangeTitle" + MessageChatChangePhotoType MessageContentEnum = "messageChatChangePhoto" + MessageChatDeletePhotoType MessageContentEnum = "messageChatDeletePhoto" + MessageChatAddMembersType MessageContentEnum = "messageChatAddMembers" + MessageChatJoinByLinkType MessageContentEnum = "messageChatJoinByLink" + MessageChatDeleteMemberType MessageContentEnum = "messageChatDeleteMember" + MessageChatUpgradeToType MessageContentEnum = "messageChatUpgradeTo" + MessageChatUpgradeFromType MessageContentEnum = "messageChatUpgradeFrom" + MessagePinMessageType MessageContentEnum = "messagePinMessage" + MessageScreenshotTakenType MessageContentEnum = "messageScreenshotTaken" + MessageChatSetTTLType MessageContentEnum = "messageChatSetTTL" + MessageCustomServiceActionType MessageContentEnum = "messageCustomServiceAction" + MessageGameScoreType MessageContentEnum = "messageGameScore" + MessagePaymentSuccessfulType MessageContentEnum = "messagePaymentSuccessful" + MessagePaymentSuccessfulBotType MessageContentEnum = "messagePaymentSuccessfulBot" + MessageContactRegisteredType MessageContentEnum = "messageContactRegistered" + MessageWebsiteConnectedType MessageContentEnum = "messageWebsiteConnected" + MessagePassportDataSentType MessageContentEnum = "messagePassportDataSent" + MessagePassportDataReceivedType MessageContentEnum = "messagePassportDataReceived" + MessageUnsupportedType MessageContentEnum = "messageUnsupported" +) + +// TextEntityTypeEnum Alias for abstract TextEntityType 'Sub-Classes', used as constant-enum here +type TextEntityTypeEnum string + +// TextEntityType enums +const ( + TextEntityTypeMentionType TextEntityTypeEnum = "textEntityTypeMention" + TextEntityTypeHashtagType TextEntityTypeEnum = "textEntityTypeHashtag" + TextEntityTypeCashtagType TextEntityTypeEnum = "textEntityTypeCashtag" + TextEntityTypeBotCommandType TextEntityTypeEnum = "textEntityTypeBotCommand" + TextEntityTypeURLType TextEntityTypeEnum = "textEntityTypeURL" + TextEntityTypeEmailAddressType TextEntityTypeEnum = "textEntityTypeEmailAddress" + TextEntityTypeBoldType TextEntityTypeEnum = "textEntityTypeBold" + TextEntityTypeItalicType TextEntityTypeEnum = "textEntityTypeItalic" + TextEntityTypeCodeType TextEntityTypeEnum = "textEntityTypeCode" + TextEntityTypePreType TextEntityTypeEnum = "textEntityTypePre" + TextEntityTypePreCodeType TextEntityTypeEnum = "textEntityTypePreCode" + TextEntityTypeTextURLType TextEntityTypeEnum = "textEntityTypeTextURL" + TextEntityTypeMentionNameType TextEntityTypeEnum = "textEntityTypeMentionName" + TextEntityTypePhoneNumberType TextEntityTypeEnum = "textEntityTypePhoneNumber" +) + +// InputMessageContentEnum Alias for abstract InputMessageContent 'Sub-Classes', used as constant-enum here +type InputMessageContentEnum string + +// InputMessageContent enums +const ( + InputMessageTextType InputMessageContentEnum = "inputMessageText" + InputMessageAnimationType InputMessageContentEnum = "inputMessageAnimation" + InputMessageAudioType InputMessageContentEnum = "inputMessageAudio" + InputMessageDocumentType InputMessageContentEnum = "inputMessageDocument" + InputMessagePhotoType InputMessageContentEnum = "inputMessagePhoto" + InputMessageStickerType InputMessageContentEnum = "inputMessageSticker" + InputMessageVideoType InputMessageContentEnum = "inputMessageVideo" + InputMessageVideoNoteType InputMessageContentEnum = "inputMessageVideoNote" + InputMessageVoiceNoteType InputMessageContentEnum = "inputMessageVoiceNote" + InputMessageLocationType InputMessageContentEnum = "inputMessageLocation" + InputMessageVenueType InputMessageContentEnum = "inputMessageVenue" + InputMessageContactType InputMessageContentEnum = "inputMessageContact" + InputMessageGameType InputMessageContentEnum = "inputMessageGame" + InputMessageInvoiceType InputMessageContentEnum = "inputMessageInvoice" + InputMessageForwardedType InputMessageContentEnum = "inputMessageForwarded" +) + +// SearchMessagesFilterEnum Alias for abstract SearchMessagesFilter 'Sub-Classes', used as constant-enum here +type SearchMessagesFilterEnum string + +// SearchMessagesFilter enums +const ( + SearchMessagesFilterEmptyType SearchMessagesFilterEnum = "searchMessagesFilterEmpty" + SearchMessagesFilterAnimationType SearchMessagesFilterEnum = "searchMessagesFilterAnimation" + SearchMessagesFilterAudioType SearchMessagesFilterEnum = "searchMessagesFilterAudio" + SearchMessagesFilterDocumentType SearchMessagesFilterEnum = "searchMessagesFilterDocument" + SearchMessagesFilterPhotoType SearchMessagesFilterEnum = "searchMessagesFilterPhoto" + SearchMessagesFilterVideoType SearchMessagesFilterEnum = "searchMessagesFilterVideo" + SearchMessagesFilterVoiceNoteType SearchMessagesFilterEnum = "searchMessagesFilterVoiceNote" + SearchMessagesFilterPhotoAndVideoType SearchMessagesFilterEnum = "searchMessagesFilterPhotoAndVideo" + SearchMessagesFilterURLType SearchMessagesFilterEnum = "searchMessagesFilterURL" + SearchMessagesFilterChatPhotoType SearchMessagesFilterEnum = "searchMessagesFilterChatPhoto" + SearchMessagesFilterCallType SearchMessagesFilterEnum = "searchMessagesFilterCall" + SearchMessagesFilterMissedCallType SearchMessagesFilterEnum = "searchMessagesFilterMissedCall" + SearchMessagesFilterVideoNoteType SearchMessagesFilterEnum = "searchMessagesFilterVideoNote" + SearchMessagesFilterVoiceAndVideoNoteType SearchMessagesFilterEnum = "searchMessagesFilterVoiceAndVideoNote" + SearchMessagesFilterMentionType SearchMessagesFilterEnum = "searchMessagesFilterMention" + SearchMessagesFilterUnreadMentionType SearchMessagesFilterEnum = "searchMessagesFilterUnreadMention" +) + +// ChatActionEnum Alias for abstract ChatAction 'Sub-Classes', used as constant-enum here +type ChatActionEnum string + +// ChatAction enums +const ( + ChatActionTypingType ChatActionEnum = "chatActionTyping" + ChatActionRecordingVideoType ChatActionEnum = "chatActionRecordingVideo" + ChatActionUploadingVideoType ChatActionEnum = "chatActionUploadingVideo" + ChatActionRecordingVoiceNoteType ChatActionEnum = "chatActionRecordingVoiceNote" + ChatActionUploadingVoiceNoteType ChatActionEnum = "chatActionUploadingVoiceNote" + ChatActionUploadingPhotoType ChatActionEnum = "chatActionUploadingPhoto" + ChatActionUploadingDocumentType ChatActionEnum = "chatActionUploadingDocument" + ChatActionChoosingLocationType ChatActionEnum = "chatActionChoosingLocation" + ChatActionChoosingContactType ChatActionEnum = "chatActionChoosingContact" + ChatActionStartPlayingGameType ChatActionEnum = "chatActionStartPlayingGame" + ChatActionRecordingVideoNoteType ChatActionEnum = "chatActionRecordingVideoNote" + ChatActionUploadingVideoNoteType ChatActionEnum = "chatActionUploadingVideoNote" + ChatActionCancelType ChatActionEnum = "chatActionCancel" +) + +// UserStatusEnum Alias for abstract UserStatus 'Sub-Classes', used as constant-enum here +type UserStatusEnum string + +// UserStatus enums +const ( + UserStatusEmptyType UserStatusEnum = "userStatusEmpty" + UserStatusOnlineType UserStatusEnum = "userStatusOnline" + UserStatusOfflineType UserStatusEnum = "userStatusOffline" + UserStatusRecentlyType UserStatusEnum = "userStatusRecently" + UserStatusLastWeekType UserStatusEnum = "userStatusLastWeek" + UserStatusLastMonthType UserStatusEnum = "userStatusLastMonth" +) + +// CallDiscardReasonEnum Alias for abstract CallDiscardReason 'Sub-Classes', used as constant-enum here +type CallDiscardReasonEnum string + +// CallDiscardReason enums +const ( + CallDiscardReasonEmptyType CallDiscardReasonEnum = "callDiscardReasonEmpty" + CallDiscardReasonMissedType CallDiscardReasonEnum = "callDiscardReasonMissed" + CallDiscardReasonDeclinedType CallDiscardReasonEnum = "callDiscardReasonDeclined" + CallDiscardReasonDisconnectedType CallDiscardReasonEnum = "callDiscardReasonDisconnected" + CallDiscardReasonHungUpType CallDiscardReasonEnum = "callDiscardReasonHungUp" +) + +// CallStateEnum Alias for abstract CallState 'Sub-Classes', used as constant-enum here +type CallStateEnum string + +// CallState enums +const ( + CallStatePendingType CallStateEnum = "callStatePending" + CallStateExchangingKeysType CallStateEnum = "callStateExchangingKeys" + CallStateReadyType CallStateEnum = "callStateReady" + CallStateHangingUpType CallStateEnum = "callStateHangingUp" + CallStateDiscardedType CallStateEnum = "callStateDiscarded" + CallStateErrorType CallStateEnum = "callStateError" +) + +// InputInlineQueryResultEnum Alias for abstract InputInlineQueryResult 'Sub-Classes', used as constant-enum here +type InputInlineQueryResultEnum string + +// InputInlineQueryResult enums +const ( + InputInlineQueryResultAnimatedGifType InputInlineQueryResultEnum = "inputInlineQueryResultAnimatedGif" + InputInlineQueryResultAnimatedMpeg4Type InputInlineQueryResultEnum = "inputInlineQueryResultAnimatedMpeg4" + InputInlineQueryResultArticleType InputInlineQueryResultEnum = "inputInlineQueryResultArticle" + InputInlineQueryResultAudioType InputInlineQueryResultEnum = "inputInlineQueryResultAudio" + InputInlineQueryResultContactType InputInlineQueryResultEnum = "inputInlineQueryResultContact" + InputInlineQueryResultDocumentType InputInlineQueryResultEnum = "inputInlineQueryResultDocument" + InputInlineQueryResultGameType InputInlineQueryResultEnum = "inputInlineQueryResultGame" + InputInlineQueryResultLocationType InputInlineQueryResultEnum = "inputInlineQueryResultLocation" + InputInlineQueryResultPhotoType InputInlineQueryResultEnum = "inputInlineQueryResultPhoto" + InputInlineQueryResultStickerType InputInlineQueryResultEnum = "inputInlineQueryResultSticker" + InputInlineQueryResultVenueType InputInlineQueryResultEnum = "inputInlineQueryResultVenue" + InputInlineQueryResultVideoType InputInlineQueryResultEnum = "inputInlineQueryResultVideo" + InputInlineQueryResultVoiceNoteType InputInlineQueryResultEnum = "inputInlineQueryResultVoiceNote" +) + +// InlineQueryResultEnum Alias for abstract InlineQueryResult 'Sub-Classes', used as constant-enum here +type InlineQueryResultEnum string + +// InlineQueryResult enums +const ( + InlineQueryResultArticleType InlineQueryResultEnum = "inlineQueryResultArticle" + InlineQueryResultContactType InlineQueryResultEnum = "inlineQueryResultContact" + InlineQueryResultLocationType InlineQueryResultEnum = "inlineQueryResultLocation" + InlineQueryResultVenueType InlineQueryResultEnum = "inlineQueryResultVenue" + InlineQueryResultGameType InlineQueryResultEnum = "inlineQueryResultGame" + InlineQueryResultAnimationType InlineQueryResultEnum = "inlineQueryResultAnimation" + InlineQueryResultAudioType InlineQueryResultEnum = "inlineQueryResultAudio" + InlineQueryResultDocumentType InlineQueryResultEnum = "inlineQueryResultDocument" + InlineQueryResultPhotoType InlineQueryResultEnum = "inlineQueryResultPhoto" + InlineQueryResultStickerType InlineQueryResultEnum = "inlineQueryResultSticker" + InlineQueryResultVideoType InlineQueryResultEnum = "inlineQueryResultVideo" + InlineQueryResultVoiceNoteType InlineQueryResultEnum = "inlineQueryResultVoiceNote" +) + +// CallbackQueryPayloadEnum Alias for abstract CallbackQueryPayload 'Sub-Classes', used as constant-enum here +type CallbackQueryPayloadEnum string + +// CallbackQueryPayload enums +const ( + CallbackQueryPayloadDataType CallbackQueryPayloadEnum = "callbackQueryPayloadData" + CallbackQueryPayloadGameType CallbackQueryPayloadEnum = "callbackQueryPayloadGame" +) + +// ChatEventActionEnum Alias for abstract ChatEventAction 'Sub-Classes', used as constant-enum here +type ChatEventActionEnum string + +// ChatEventAction enums +const ( + ChatEventMessageEditedType ChatEventActionEnum = "chatEventMessageEdited" + ChatEventMessageDeletedType ChatEventActionEnum = "chatEventMessageDeleted" + ChatEventMessagePinnedType ChatEventActionEnum = "chatEventMessagePinned" + ChatEventMessageUnpinnedType ChatEventActionEnum = "chatEventMessageUnpinned" + ChatEventMemberJoinedType ChatEventActionEnum = "chatEventMemberJoined" + ChatEventMemberLeftType ChatEventActionEnum = "chatEventMemberLeft" + ChatEventMemberInvitedType ChatEventActionEnum = "chatEventMemberInvited" + ChatEventMemberPromotedType ChatEventActionEnum = "chatEventMemberPromoted" + ChatEventMemberRestrictedType ChatEventActionEnum = "chatEventMemberRestricted" + ChatEventTitleChangedType ChatEventActionEnum = "chatEventTitleChanged" + ChatEventDescriptionChangedType ChatEventActionEnum = "chatEventDescriptionChanged" + ChatEventUsernameChangedType ChatEventActionEnum = "chatEventUsernameChanged" + ChatEventPhotoChangedType ChatEventActionEnum = "chatEventPhotoChanged" + ChatEventInvitesToggledType ChatEventActionEnum = "chatEventInvitesToggled" + ChatEventSignMessagesToggledType ChatEventActionEnum = "chatEventSignMessagesToggled" + ChatEventStickerSetChangedType ChatEventActionEnum = "chatEventStickerSetChanged" + ChatEventIsAllHistoryAvailableToggledType ChatEventActionEnum = "chatEventIsAllHistoryAvailableToggled" +) + +// LanguagePackStringValueEnum Alias for abstract LanguagePackStringValue 'Sub-Classes', used as constant-enum here +type LanguagePackStringValueEnum string + +// LanguagePackStringValue enums +const ( + LanguagePackStringValueOrdinaryType LanguagePackStringValueEnum = "languagePackStringValueOrdinary" + LanguagePackStringValuePluralizedType LanguagePackStringValueEnum = "languagePackStringValuePluralized" + LanguagePackStringValueDeletedType LanguagePackStringValueEnum = "languagePackStringValueDeleted" +) + +// DeviceTokenEnum Alias for abstract DeviceToken 'Sub-Classes', used as constant-enum here +type DeviceTokenEnum string + +// DeviceToken enums +const ( + DeviceTokenGoogleCloudMessagingType DeviceTokenEnum = "deviceTokenGoogleCloudMessaging" + DeviceTokenApplePushType DeviceTokenEnum = "deviceTokenApplePush" + DeviceTokenApplePushVoIPType DeviceTokenEnum = "deviceTokenApplePushVoIP" + DeviceTokenWindowsPushType DeviceTokenEnum = "deviceTokenWindowsPush" + DeviceTokenMicrosoftPushType DeviceTokenEnum = "deviceTokenMicrosoftPush" + DeviceTokenMicrosoftPushVoIPType DeviceTokenEnum = "deviceTokenMicrosoftPushVoIP" + DeviceTokenWebPushType DeviceTokenEnum = "deviceTokenWebPush" + DeviceTokenSimplePushType DeviceTokenEnum = "deviceTokenSimplePush" + DeviceTokenUbuntuPushType DeviceTokenEnum = "deviceTokenUbuntuPush" + DeviceTokenBlackBerryPushType DeviceTokenEnum = "deviceTokenBlackBerryPush" + DeviceTokenTizenPushType DeviceTokenEnum = "deviceTokenTizenPush" +) + +// CheckChatUsernameResultEnum Alias for abstract CheckChatUsernameResult 'Sub-Classes', used as constant-enum here +type CheckChatUsernameResultEnum string + +// CheckChatUsernameResult enums +const ( + CheckChatUsernameResultOkType CheckChatUsernameResultEnum = "checkChatUsernameResultOk" + CheckChatUsernameResultUsernameInvalidType CheckChatUsernameResultEnum = "checkChatUsernameResultUsernameInvalid" + CheckChatUsernameResultUsernameOccupiedType CheckChatUsernameResultEnum = "checkChatUsernameResultUsernameOccupied" + CheckChatUsernameResultPublicChatsTooMuchType CheckChatUsernameResultEnum = "checkChatUsernameResultPublicChatsTooMuch" + CheckChatUsernameResultPublicGroupsUnavailableType CheckChatUsernameResultEnum = "checkChatUsernameResultPublicGroupsUnavailable" +) + +// OptionValueEnum Alias for abstract OptionValue 'Sub-Classes', used as constant-enum here +type OptionValueEnum string + +// OptionValue enums +const ( + OptionValueBooleanType OptionValueEnum = "optionValueBoolean" + OptionValueEmptyType OptionValueEnum = "optionValueEmpty" + OptionValueIntegerType OptionValueEnum = "optionValueInteger" + OptionValueStringType OptionValueEnum = "optionValueString" +) + +// UserPrivacySettingRuleEnum Alias for abstract UserPrivacySettingRule 'Sub-Classes', used as constant-enum here +type UserPrivacySettingRuleEnum string + +// UserPrivacySettingRule enums +const ( + UserPrivacySettingRuleAllowAllType UserPrivacySettingRuleEnum = "userPrivacySettingRuleAllowAll" + UserPrivacySettingRuleAllowContactsType UserPrivacySettingRuleEnum = "userPrivacySettingRuleAllowContacts" + UserPrivacySettingRuleAllowUsersType UserPrivacySettingRuleEnum = "userPrivacySettingRuleAllowUsers" + UserPrivacySettingRuleRestrictAllType UserPrivacySettingRuleEnum = "userPrivacySettingRuleRestrictAll" + UserPrivacySettingRuleRestrictContactsType UserPrivacySettingRuleEnum = "userPrivacySettingRuleRestrictContacts" + UserPrivacySettingRuleRestrictUsersType UserPrivacySettingRuleEnum = "userPrivacySettingRuleRestrictUsers" +) + +// UserPrivacySettingEnum Alias for abstract UserPrivacySetting 'Sub-Classes', used as constant-enum here +type UserPrivacySettingEnum string + +// UserPrivacySetting enums +const ( + UserPrivacySettingShowStatusType UserPrivacySettingEnum = "userPrivacySettingShowStatus" + UserPrivacySettingAllowChatInvitesType UserPrivacySettingEnum = "userPrivacySettingAllowChatInvites" + UserPrivacySettingAllowCallsType UserPrivacySettingEnum = "userPrivacySettingAllowCalls" +) + +// ChatReportReasonEnum Alias for abstract ChatReportReason 'Sub-Classes', used as constant-enum here +type ChatReportReasonEnum string + +// ChatReportReason enums +const ( + ChatReportReasonSpamType ChatReportReasonEnum = "chatReportReasonSpam" + ChatReportReasonViolenceType ChatReportReasonEnum = "chatReportReasonViolence" + ChatReportReasonPornographyType ChatReportReasonEnum = "chatReportReasonPornography" + ChatReportReasonCopyrightType ChatReportReasonEnum = "chatReportReasonCopyright" + ChatReportReasonCustomType ChatReportReasonEnum = "chatReportReasonCustom" +) + +// FileTypeEnum Alias for abstract FileType 'Sub-Classes', used as constant-enum here +type FileTypeEnum string + +// FileType enums +const ( + FileTypeNoneType FileTypeEnum = "fileTypeNone" + FileTypeAnimationType FileTypeEnum = "fileTypeAnimation" + FileTypeAudioType FileTypeEnum = "fileTypeAudio" + FileTypeDocumentType FileTypeEnum = "fileTypeDocument" + FileTypePhotoType FileTypeEnum = "fileTypePhoto" + FileTypeProfilePhotoType FileTypeEnum = "fileTypeProfilePhoto" + FileTypeSecretType FileTypeEnum = "fileTypeSecret" + FileTypeSecretThumbnailType FileTypeEnum = "fileTypeSecretThumbnail" + FileTypeSecureType FileTypeEnum = "fileTypeSecure" + FileTypeStickerType FileTypeEnum = "fileTypeSticker" + FileTypeThumbnailType FileTypeEnum = "fileTypeThumbnail" + FileTypeUnknownType FileTypeEnum = "fileTypeUnknown" + FileTypeVideoType FileTypeEnum = "fileTypeVideo" + FileTypeVideoNoteType FileTypeEnum = "fileTypeVideoNote" + FileTypeVoiceNoteType FileTypeEnum = "fileTypeVoiceNote" + FileTypeWallpaperType FileTypeEnum = "fileTypeWallpaper" +) + +// NetworkTypeEnum Alias for abstract NetworkType 'Sub-Classes', used as constant-enum here +type NetworkTypeEnum string + +// NetworkType enums +const ( + NetworkTypeNoneType NetworkTypeEnum = "networkTypeNone" + NetworkTypeMobileType NetworkTypeEnum = "networkTypeMobile" + NetworkTypeMobileRoamingType NetworkTypeEnum = "networkTypeMobileRoaming" + NetworkTypeWiFiType NetworkTypeEnum = "networkTypeWiFi" + NetworkTypeOtherType NetworkTypeEnum = "networkTypeOther" +) + +// NetworkStatisticsEntryEnum Alias for abstract NetworkStatisticsEntry 'Sub-Classes', used as constant-enum here +type NetworkStatisticsEntryEnum string + +// NetworkStatisticsEntry enums +const ( + NetworkStatisticsEntryFileType NetworkStatisticsEntryEnum = "networkStatisticsEntryFile" + NetworkStatisticsEntryCallType NetworkStatisticsEntryEnum = "networkStatisticsEntryCall" +) + +// ConnectionStateEnum Alias for abstract ConnectionState 'Sub-Classes', used as constant-enum here +type ConnectionStateEnum string + +// ConnectionState enums +const ( + ConnectionStateWaitingForNetworkType ConnectionStateEnum = "connectionStateWaitingForNetwork" + ConnectionStateConnectingToProxyType ConnectionStateEnum = "connectionStateConnectingToProxy" + ConnectionStateConnectingType ConnectionStateEnum = "connectionStateConnecting" + ConnectionStateUpdatingType ConnectionStateEnum = "connectionStateUpdating" + ConnectionStateReadyType ConnectionStateEnum = "connectionStateReady" +) + +// TopChatCategoryEnum Alias for abstract TopChatCategory 'Sub-Classes', used as constant-enum here +type TopChatCategoryEnum string + +// TopChatCategory enums +const ( + TopChatCategoryUsersType TopChatCategoryEnum = "topChatCategoryUsers" + TopChatCategoryBotsType TopChatCategoryEnum = "topChatCategoryBots" + TopChatCategoryGroupsType TopChatCategoryEnum = "topChatCategoryGroups" + TopChatCategoryChannelsType TopChatCategoryEnum = "topChatCategoryChannels" + TopChatCategoryInlineBotsType TopChatCategoryEnum = "topChatCategoryInlineBots" + TopChatCategoryCallsType TopChatCategoryEnum = "topChatCategoryCalls" +) + +// TMeURLTypeEnum Alias for abstract TMeURLType 'Sub-Classes', used as constant-enum here +type TMeURLTypeEnum string + +// TMeURLType enums +const ( + TMeURLTypeUserType TMeURLTypeEnum = "tMeURLTypeUser" + TMeURLTypeSupergroupType TMeURLTypeEnum = "tMeURLTypeSupergroup" + TMeURLTypeChatInviteType TMeURLTypeEnum = "tMeURLTypeChatInvite" + TMeURLTypeStickerSetType TMeURLTypeEnum = "tMeURLTypeStickerSet" +) + +// TextParseModeEnum Alias for abstract TextParseMode 'Sub-Classes', used as constant-enum here +type TextParseModeEnum string + +// TextParseMode enums +const ( + TextParseModeMarkdownType TextParseModeEnum = "textParseModeMarkdown" + TextParseModeHTMLType TextParseModeEnum = "textParseModeHTML" +) + +// ProxyTypeEnum Alias for abstract ProxyType 'Sub-Classes', used as constant-enum here +type ProxyTypeEnum string + +// ProxyType enums +const ( + ProxyTypeSocks5Type ProxyTypeEnum = "proxyTypeSocks5" + ProxyTypeHttpType ProxyTypeEnum = "proxyTypeHttp" + ProxyTypeMtprotoType ProxyTypeEnum = "proxyTypeMtproto" +) + +// UpdateEnum Alias for abstract Update 'Sub-Classes', used as constant-enum here +type UpdateEnum string + +// Update enums +const ( + UpdateAuthorizationStateType UpdateEnum = "updateAuthorizationState" + UpdateNewMessageType UpdateEnum = "updateNewMessage" + UpdateMessageSendAcknowledgedType UpdateEnum = "updateMessageSendAcknowledged" + UpdateMessageSendSucceededType UpdateEnum = "updateMessageSendSucceeded" + UpdateMessageSendFailedType UpdateEnum = "updateMessageSendFailed" + UpdateMessageContentType UpdateEnum = "updateMessageContent" + UpdateMessageEditedType UpdateEnum = "updateMessageEdited" + UpdateMessageViewsType UpdateEnum = "updateMessageViews" + UpdateMessageContentOpenedType UpdateEnum = "updateMessageContentOpened" + UpdateMessageMentionReadType UpdateEnum = "updateMessageMentionRead" + UpdateNewChatType UpdateEnum = "updateNewChat" + UpdateChatTitleType UpdateEnum = "updateChatTitle" + UpdateChatPhotoType UpdateEnum = "updateChatPhoto" + UpdateChatLastMessageType UpdateEnum = "updateChatLastMessage" + UpdateChatOrderType UpdateEnum = "updateChatOrder" + UpdateChatIsPinnedType UpdateEnum = "updateChatIsPinned" + UpdateChatIsMarkedAsUnreadType UpdateEnum = "updateChatIsMarkedAsUnread" + UpdateChatIsSponsoredType UpdateEnum = "updateChatIsSponsored" + UpdateChatDefaultDisableNotificationType UpdateEnum = "updateChatDefaultDisableNotification" + UpdateChatReadInboxType UpdateEnum = "updateChatReadInbox" + UpdateChatReadOutboxType UpdateEnum = "updateChatReadOutbox" + UpdateChatUnreadMentionCountType UpdateEnum = "updateChatUnreadMentionCount" + UpdateChatNotificationSettingsType UpdateEnum = "updateChatNotificationSettings" + UpdateScopeNotificationSettingsType UpdateEnum = "updateScopeNotificationSettings" + UpdateChatReplyMarkupType UpdateEnum = "updateChatReplyMarkup" + UpdateChatDraftMessageType UpdateEnum = "updateChatDraftMessage" + UpdateDeleteMessagesType UpdateEnum = "updateDeleteMessages" + UpdateUserChatActionType UpdateEnum = "updateUserChatAction" + UpdateUserStatusType UpdateEnum = "updateUserStatus" + UpdateUserType UpdateEnum = "updateUser" + UpdateBasicGroupType UpdateEnum = "updateBasicGroup" + UpdateSupergroupType UpdateEnum = "updateSupergroup" + UpdateSecretChatType UpdateEnum = "updateSecretChat" + UpdateUserFullInfoType UpdateEnum = "updateUserFullInfo" + UpdateBasicGroupFullInfoType UpdateEnum = "updateBasicGroupFullInfo" + UpdateSupergroupFullInfoType UpdateEnum = "updateSupergroupFullInfo" + UpdateServiceNotificationType UpdateEnum = "updateServiceNotification" + UpdateFileType UpdateEnum = "updateFile" + UpdateFileGenerationStartType UpdateEnum = "updateFileGenerationStart" + UpdateFileGenerationStopType UpdateEnum = "updateFileGenerationStop" + UpdateCallType UpdateEnum = "updateCall" + UpdateUserPrivacySettingRulesType UpdateEnum = "updateUserPrivacySettingRules" + UpdateUnreadMessageCountType UpdateEnum = "updateUnreadMessageCount" + UpdateUnreadChatCountType UpdateEnum = "updateUnreadChatCount" + UpdateOptionType UpdateEnum = "updateOption" + UpdateInstalledStickerSetsType UpdateEnum = "updateInstalledStickerSets" + UpdateTrendingStickerSetsType UpdateEnum = "updateTrendingStickerSets" + UpdateRecentStickersType UpdateEnum = "updateRecentStickers" + UpdateFavoriteStickersType UpdateEnum = "updateFavoriteStickers" + UpdateSavedAnimationsType UpdateEnum = "updateSavedAnimations" + UpdateLanguagePackStringsType UpdateEnum = "updateLanguagePackStrings" + UpdateConnectionStateType UpdateEnum = "updateConnectionState" + UpdateTermsOfServiceType UpdateEnum = "updateTermsOfService" + UpdateNewInlineQueryType UpdateEnum = "updateNewInlineQuery" + UpdateNewChosenInlineResultType UpdateEnum = "updateNewChosenInlineResult" + UpdateNewCallbackQueryType UpdateEnum = "updateNewCallbackQuery" + UpdateNewInlineCallbackQueryType UpdateEnum = "updateNewInlineCallbackQuery" + UpdateNewShippingQueryType UpdateEnum = "updateNewShippingQuery" + UpdateNewPreCheckoutQueryType UpdateEnum = "updateNewPreCheckoutQuery" + UpdateNewCustomEventType UpdateEnum = "updateNewCustomEvent" + UpdateNewCustomQueryType UpdateEnum = "updateNewCustomQuery" +) // AuthenticationCodeType Provides information about the method by which an authentication code is delivered to the user +type AuthenticationCodeType interface { + GetAuthenticationCodeTypeEnum() AuthenticationCodeTypeEnum +} + +// AuthorizationState Represents the current authorization state of the client +type AuthorizationState interface { + GetAuthorizationStateEnum() AuthorizationStateEnum +} + +// InputFile Points to a file +type InputFile interface { + GetInputFileEnum() InputFileEnum +} + +// MaskPoint Part of the face, relative to which a mask should be placed +type MaskPoint interface { + GetMaskPointEnum() MaskPointEnum +} + +// LinkState Represents the relationship between user A and user B. For incoming_link, user A is the current user; for outgoing_link, user B is the current user +type LinkState interface { + GetLinkStateEnum() LinkStateEnum +} + +// UserType Represents the type of the user. The following types are possible: regular users, deleted users and bots +type UserType interface { + GetUserTypeEnum() UserTypeEnum +} + +// ChatMemberStatus Provides information about the status of a member in a chat +type ChatMemberStatus interface { + GetChatMemberStatusEnum() ChatMemberStatusEnum +} + +// ChatMembersFilter Specifies the kind of chat members to return in searchChatMembers +type ChatMembersFilter interface { + GetChatMembersFilterEnum() ChatMembersFilterEnum +} + +// SupergroupMembersFilter Specifies the kind of chat members to return in getSupergroupMembers +type SupergroupMembersFilter interface { + GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum +} + +// SecretChatState Describes the current secret chat state +type SecretChatState interface { + GetSecretChatStateEnum() SecretChatStateEnum +} + +// MessageForwardInfo Contains information about the initial sender of a forwarded message +type MessageForwardInfo interface { + GetMessageForwardInfoEnum() MessageForwardInfoEnum +} + +// MessageSendingState Contains information about the sending state of the message +type MessageSendingState interface { + GetMessageSendingStateEnum() MessageSendingStateEnum +} + +// NotificationSettingsScope Describes the types of chats to which notification settings are applied +type NotificationSettingsScope interface { + GetNotificationSettingsScopeEnum() NotificationSettingsScopeEnum +} + +// ChatType Describes the type of a chat +type ChatType interface { + GetChatTypeEnum() ChatTypeEnum +} + +// KeyboardButtonType Describes a keyboard button type +type KeyboardButtonType interface { + GetKeyboardButtonTypeEnum() KeyboardButtonTypeEnum +} + +// InlineKeyboardButtonType Describes the type of an inline keyboard button +type InlineKeyboardButtonType interface { + GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum +} + +// ReplyMarkup Contains a description of a custom keyboard and actions that can be done with it to quickly reply to bots +type ReplyMarkup interface { + GetReplyMarkupEnum() ReplyMarkupEnum +} + +// RichText Describes a text object inside an instant-view web page +type RichText interface { + GetRichTextEnum() RichTextEnum +} + +// PageBlock Describes a block of an instant view web page +type PageBlock interface { + GetPageBlockEnum() PageBlockEnum +} + +// InputCredentials Contains information about the payment method chosen by the user +type InputCredentials interface { + GetInputCredentialsEnum() InputCredentialsEnum +} + +// PassportElementType Contains the type of a Telegram Passport element +type PassportElementType interface { + GetPassportElementTypeEnum() PassportElementTypeEnum +} + +// PassportElement Contains information about a Telegram Passport element +type PassportElement interface { + GetPassportElementEnum() PassportElementEnum +} + +// InputPassportElement Contains information about a Telegram Passport element to be saved +type InputPassportElement interface { + GetInputPassportElementEnum() InputPassportElementEnum +} + +// PassportElementErrorSource Contains the description of an error in a Telegram Passport element +type PassportElementErrorSource interface { + GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum +} + +// InputPassportElementErrorSource Contains the description of an error in a Telegram Passport element; for bots only +type InputPassportElementErrorSource interface { + GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum +} + +// MessageContent Contains the content of a message +type MessageContent interface { + GetMessageContentEnum() MessageContentEnum +} + +// TextEntityType Represents a part of the text which must be formatted differently +type TextEntityType interface { + GetTextEntityTypeEnum() TextEntityTypeEnum +} + +// InputMessageContent The content of a message to send +type InputMessageContent interface { + GetInputMessageContentEnum() InputMessageContentEnum +} + +// SearchMessagesFilter Represents a filter for message search results +type SearchMessagesFilter interface { + GetSearchMessagesFilterEnum() SearchMessagesFilterEnum +} + +// ChatAction Describes the different types of activity in a chat +type ChatAction interface { + GetChatActionEnum() ChatActionEnum +} + +// UserStatus Describes the last time the user was online +type UserStatus interface { + GetUserStatusEnum() UserStatusEnum +} + +// CallDiscardReason Describes the reason why a call was discarded +type CallDiscardReason interface { + GetCallDiscardReasonEnum() CallDiscardReasonEnum +} + +// CallState Describes the current call state +type CallState interface { + GetCallStateEnum() CallStateEnum +} + +// InputInlineQueryResult Represents a single result of an inline query; for bots only +type InputInlineQueryResult interface { + GetInputInlineQueryResultEnum() InputInlineQueryResultEnum +} + +// InlineQueryResult Represents a single result of an inline query +type InlineQueryResult interface { + GetInlineQueryResultEnum() InlineQueryResultEnum +} + +// CallbackQueryPayload Represents a payload of a callback query +type CallbackQueryPayload interface { + GetCallbackQueryPayloadEnum() CallbackQueryPayloadEnum +} + +// ChatEventAction Represents a chat event +type ChatEventAction interface { + GetChatEventActionEnum() ChatEventActionEnum +} + +// LanguagePackStringValue Represents the value of a string in a language pack +type LanguagePackStringValue interface { + GetLanguagePackStringValueEnum() LanguagePackStringValueEnum +} + +// DeviceToken Represents a data needed to subscribe for push notifications. To use specific push notification service, you must specify the correct application platform and upload valid server authentication data at https://my.telegram.org +type DeviceToken interface { + GetDeviceTokenEnum() DeviceTokenEnum +} + +// CheckChatUsernameResult Represents result of checking whether a username can be set for a chat +type CheckChatUsernameResult interface { + GetCheckChatUsernameResultEnum() CheckChatUsernameResultEnum +} + +// OptionValue Represents the value of an option +type OptionValue interface { + GetOptionValueEnum() OptionValueEnum +} + +// UserPrivacySettingRule Represents a single rule for managing privacy settings +type UserPrivacySettingRule interface { + GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum +} + +// UserPrivacySetting Describes available user privacy settings +type UserPrivacySetting interface { + GetUserPrivacySettingEnum() UserPrivacySettingEnum +} + +// ChatReportReason Describes the reason why a chat is reported +type ChatReportReason interface { + GetChatReportReasonEnum() ChatReportReasonEnum +} + +// FileType Represents the type of a file +type FileType interface { + GetFileTypeEnum() FileTypeEnum +} + +// NetworkType Represents the type of a network +type NetworkType interface { + GetNetworkTypeEnum() NetworkTypeEnum +} + +// NetworkStatisticsEntry Contains statistics about network usage +type NetworkStatisticsEntry interface { + GetNetworkStatisticsEntryEnum() NetworkStatisticsEntryEnum +} + +// ConnectionState Describes the current state of the connection to Telegram servers +type ConnectionState interface { + GetConnectionStateEnum() ConnectionStateEnum +} + +// TopChatCategory Represents the categories of chats for which a list of frequently used chats can be retrieved +type TopChatCategory interface { + GetTopChatCategoryEnum() TopChatCategoryEnum +} + +// TMeURLType Describes the type of a URL linking to an internal Telegram entity +type TMeURLType interface { + GetTMeURLTypeEnum() TMeURLTypeEnum +} + +// TextParseMode Describes the way the text should be parsed for TextEntities +type TextParseMode interface { + GetTextParseModeEnum() TextParseModeEnum +} + +// ProxyType Describes the type of the proxy server +type ProxyType interface { + GetProxyTypeEnum() ProxyTypeEnum +} + +// Update Contains notifications about data changes +type Update interface { + GetUpdateEnum() UpdateEnum +} + +// Error An object of this type can be returned on every function call, in case of an error +type Error struct { + tdCommon + Code int32 `json:"code"` // Error code; subject to future changes. If the error code is 406, the error message must not be processed in any way and must not be displayed to the user + Message string `json:"message"` // Error message; subject to future changes +} + +// MessageType return the string telegram-type of Error +func (error *Error) MessageType() string { + return "error" +} + +// NewError creates a new Error +// +// @param code Error code; subject to future changes. If the error code is 406, the error message must not be processed in any way and must not be displayed to the user +// @param message Error message; subject to future changes +func NewError(code int32, message string) *Error { + errorTemp := Error{ + tdCommon: tdCommon{Type: "error"}, + Code: code, + Message: message, + } + + return &errorTemp +} + +// Ok An object of this type is returned on a successful function call for certain functions +type Ok struct { + tdCommon +} + +// MessageType return the string telegram-type of Ok +func (ok *Ok) MessageType() string { + return "ok" +} + +// NewOk creates a new Ok +// +func NewOk() *Ok { + okTemp := Ok{ + tdCommon: tdCommon{Type: "ok"}, + } + + return &okTemp +} + +// TdlibParameters Contains parameters for TDLib initialization +type TdlibParameters struct { + tdCommon + UseTestDc bool `json:"use_test_dc"` // If set to true, the Telegram test environment will be used instead of the production environment + DatabaseDirectory string `json:"database_directory"` // The path to the directory for the persistent database; if empty, the current working directory will be used + FilesDirectory string `json:"files_directory"` // The path to the directory for storing files; if empty, database_directory will be used + UseFileDatabase bool `json:"use_file_database"` // If set to true, information about downloaded and uploaded files will be saved between application restarts + UseChatInfoDatabase bool `json:"use_chat_info_database"` // If set to true, the library will maintain a cache of users, basic groups, supergroups, channels and secret chats. Implies use_file_database + UseMessageDatabase bool `json:"use_message_database"` // If set to true, the library will maintain a cache of chats and messages. Implies use_chat_info_database + UseSecretChats bool `json:"use_secret_chats"` // If set to true, support for secret chats will be enabled + APIID int32 `json:"api_id"` // Application identifier for Telegram API access, which can be obtained at https://my.telegram.org + APIHash string `json:"api_hash"` // Application identifier hash for Telegram API access, which can be obtained at https://my.telegram.org + SystemLanguageCode string `json:"system_language_code"` // IETF language tag of the user's operating system language; must be non-empty + DeviceModel string `json:"device_model"` // Model of the device the application is being run on; must be non-empty + SystemVersion string `json:"system_version"` // Version of the operating system the application is being run on; must be non-empty + ApplicationVersion string `json:"application_version"` // Application version; must be non-empty + EnableStorageOptimizer bool `json:"enable_storage_optimizer"` // If set to true, old files will automatically be deleted + IgnoreFileNames bool `json:"ignore_file_names"` // If set to true, original file names will be ignored. Otherwise, downloaded files will be saved under names as close as possible to the original name +} + +// MessageType return the string telegram-type of TdlibParameters +func (tdlibParameters *TdlibParameters) MessageType() string { + return "tdlibParameters" +} + +// NewTdlibParameters creates a new TdlibParameters +// +// @param useTestDc If set to true, the Telegram test environment will be used instead of the production environment +// @param databaseDirectory The path to the directory for the persistent database; if empty, the current working directory will be used +// @param filesDirectory The path to the directory for storing files; if empty, database_directory will be used +// @param useFileDatabase If set to true, information about downloaded and uploaded files will be saved between application restarts +// @param useChatInfoDatabase If set to true, the library will maintain a cache of users, basic groups, supergroups, channels and secret chats. Implies use_file_database +// @param useMessageDatabase If set to true, the library will maintain a cache of chats and messages. Implies use_chat_info_database +// @param useSecretChats If set to true, support for secret chats will be enabled +// @param aPIID Application identifier for Telegram API access, which can be obtained at https://my.telegram.org +// @param aPIHash Application identifier hash for Telegram API access, which can be obtained at https://my.telegram.org +// @param systemLanguageCode IETF language tag of the user's operating system language; must be non-empty +// @param deviceModel Model of the device the application is being run on; must be non-empty +// @param systemVersion Version of the operating system the application is being run on; must be non-empty +// @param applicationVersion Application version; must be non-empty +// @param enableStorageOptimizer If set to true, old files will automatically be deleted +// @param ignoreFileNames If set to true, original file names will be ignored. Otherwise, downloaded files will be saved under names as close as possible to the original name +func NewTdlibParameters(useTestDc bool, databaseDirectory string, filesDirectory string, useFileDatabase bool, useChatInfoDatabase bool, useMessageDatabase bool, useSecretChats bool, aPIID int32, aPIHash string, systemLanguageCode string, deviceModel string, systemVersion string, applicationVersion string, enableStorageOptimizer bool, ignoreFileNames bool) *TdlibParameters { + tdlibParametersTemp := TdlibParameters{ + tdCommon: tdCommon{Type: "tdlibParameters"}, + UseTestDc: useTestDc, + DatabaseDirectory: databaseDirectory, + FilesDirectory: filesDirectory, + UseFileDatabase: useFileDatabase, + UseChatInfoDatabase: useChatInfoDatabase, + UseMessageDatabase: useMessageDatabase, + UseSecretChats: useSecretChats, + APIID: aPIID, + APIHash: aPIHash, + SystemLanguageCode: systemLanguageCode, + DeviceModel: deviceModel, + SystemVersion: systemVersion, + ApplicationVersion: applicationVersion, + EnableStorageOptimizer: enableStorageOptimizer, + IgnoreFileNames: ignoreFileNames, + } + + return &tdlibParametersTemp +} + +// AuthenticationCodeTypeTelegramMessage An authentication code is delivered via a private Telegram message, which can be viewed in another client +type AuthenticationCodeTypeTelegramMessage struct { + tdCommon + Length int32 `json:"length"` // Length of the code +} + +// MessageType return the string telegram-type of AuthenticationCodeTypeTelegramMessage +func (authenticationCodeTypeTelegramMessage *AuthenticationCodeTypeTelegramMessage) MessageType() string { + return "authenticationCodeTypeTelegramMessage" +} + +// NewAuthenticationCodeTypeTelegramMessage creates a new AuthenticationCodeTypeTelegramMessage +// +// @param length Length of the code +func NewAuthenticationCodeTypeTelegramMessage(length int32) *AuthenticationCodeTypeTelegramMessage { + authenticationCodeTypeTelegramMessageTemp := AuthenticationCodeTypeTelegramMessage{ + tdCommon: tdCommon{Type: "authenticationCodeTypeTelegramMessage"}, + Length: length, + } + + return &authenticationCodeTypeTelegramMessageTemp +} + +// GetAuthenticationCodeTypeEnum return the enum type of this object +func (authenticationCodeTypeTelegramMessage *AuthenticationCodeTypeTelegramMessage) GetAuthenticationCodeTypeEnum() AuthenticationCodeTypeEnum { + return AuthenticationCodeTypeTelegramMessageType +} + +// AuthenticationCodeTypeSms An authentication code is delivered via an SMS message to the specified phone number +type AuthenticationCodeTypeSms struct { + tdCommon + Length int32 `json:"length"` // Length of the code +} + +// MessageType return the string telegram-type of AuthenticationCodeTypeSms +func (authenticationCodeTypeSms *AuthenticationCodeTypeSms) MessageType() string { + return "authenticationCodeTypeSms" +} + +// NewAuthenticationCodeTypeSms creates a new AuthenticationCodeTypeSms +// +// @param length Length of the code +func NewAuthenticationCodeTypeSms(length int32) *AuthenticationCodeTypeSms { + authenticationCodeTypeSmsTemp := AuthenticationCodeTypeSms{ + tdCommon: tdCommon{Type: "authenticationCodeTypeSms"}, + Length: length, + } + + return &authenticationCodeTypeSmsTemp +} + +// GetAuthenticationCodeTypeEnum return the enum type of this object +func (authenticationCodeTypeSms *AuthenticationCodeTypeSms) GetAuthenticationCodeTypeEnum() AuthenticationCodeTypeEnum { + return AuthenticationCodeTypeSmsType +} + +// AuthenticationCodeTypeCall An authentication code is delivered via a phone call to the specified phone number +type AuthenticationCodeTypeCall struct { + tdCommon + Length int32 `json:"length"` // Length of the code +} + +// MessageType return the string telegram-type of AuthenticationCodeTypeCall +func (authenticationCodeTypeCall *AuthenticationCodeTypeCall) MessageType() string { + return "authenticationCodeTypeCall" +} + +// NewAuthenticationCodeTypeCall creates a new AuthenticationCodeTypeCall +// +// @param length Length of the code +func NewAuthenticationCodeTypeCall(length int32) *AuthenticationCodeTypeCall { + authenticationCodeTypeCallTemp := AuthenticationCodeTypeCall{ + tdCommon: tdCommon{Type: "authenticationCodeTypeCall"}, + Length: length, + } + + return &authenticationCodeTypeCallTemp +} + +// GetAuthenticationCodeTypeEnum return the enum type of this object +func (authenticationCodeTypeCall *AuthenticationCodeTypeCall) GetAuthenticationCodeTypeEnum() AuthenticationCodeTypeEnum { + return AuthenticationCodeTypeCallType +} + +// AuthenticationCodeTypeFlashCall An authentication code is delivered by an immediately cancelled call to the specified phone number. The number from which the call was made is the code +type AuthenticationCodeTypeFlashCall struct { + tdCommon + Pattern string `json:"pattern"` // Pattern of the phone number from which the call will be made +} + +// MessageType return the string telegram-type of AuthenticationCodeTypeFlashCall +func (authenticationCodeTypeFlashCall *AuthenticationCodeTypeFlashCall) MessageType() string { + return "authenticationCodeTypeFlashCall" +} + +// NewAuthenticationCodeTypeFlashCall creates a new AuthenticationCodeTypeFlashCall +// +// @param pattern Pattern of the phone number from which the call will be made +func NewAuthenticationCodeTypeFlashCall(pattern string) *AuthenticationCodeTypeFlashCall { + authenticationCodeTypeFlashCallTemp := AuthenticationCodeTypeFlashCall{ + tdCommon: tdCommon{Type: "authenticationCodeTypeFlashCall"}, + Pattern: pattern, + } + + return &authenticationCodeTypeFlashCallTemp +} + +// GetAuthenticationCodeTypeEnum return the enum type of this object +func (authenticationCodeTypeFlashCall *AuthenticationCodeTypeFlashCall) GetAuthenticationCodeTypeEnum() AuthenticationCodeTypeEnum { + return AuthenticationCodeTypeFlashCallType +} + +// AuthenticationCodeInfo Information about the authentication code that was sent +type AuthenticationCodeInfo struct { + tdCommon + PhoneNumber string `json:"phone_number"` // A phone number that is being authenticated + Type AuthenticationCodeType `json:"type"` // Describes the way the code was sent to the user + NextType AuthenticationCodeType `json:"next_type"` // Describes the way the next code will be sent to the user; may be null + Timeout int32 `json:"timeout"` // Timeout before the code should be re-sent, in seconds +} + +// MessageType return the string telegram-type of AuthenticationCodeInfo +func (authenticationCodeInfo *AuthenticationCodeInfo) MessageType() string { + return "authenticationCodeInfo" +} + +// NewAuthenticationCodeInfo creates a new AuthenticationCodeInfo +// +// @param phoneNumber A phone number that is being authenticated +// @param typeParam Describes the way the code was sent to the user +// @param nextType Describes the way the next code will be sent to the user; may be null +// @param timeout Timeout before the code should be re-sent, in seconds +func NewAuthenticationCodeInfo(phoneNumber string, typeParam AuthenticationCodeType, nextType AuthenticationCodeType, timeout int32) *AuthenticationCodeInfo { + authenticationCodeInfoTemp := AuthenticationCodeInfo{ + tdCommon: tdCommon{Type: "authenticationCodeInfo"}, + PhoneNumber: phoneNumber, + Type: typeParam, + NextType: nextType, + Timeout: timeout, + } + + return &authenticationCodeInfoTemp +} + +// UnmarshalJSON unmarshal to json +func (authenticationCodeInfo *AuthenticationCodeInfo) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + PhoneNumber string `json:"phone_number"` // A phone number that is being authenticated + Timeout int32 `json:"timeout"` // Timeout before the code should be re-sent, in seconds + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + authenticationCodeInfo.tdCommon = tempObj.tdCommon + authenticationCodeInfo.PhoneNumber = tempObj.PhoneNumber + authenticationCodeInfo.Timeout = tempObj.Timeout + + fieldType, _ := unmarshalAuthenticationCodeType(objMap["type"]) + authenticationCodeInfo.Type = fieldType + + fieldNextType, _ := unmarshalAuthenticationCodeType(objMap["next_type"]) + authenticationCodeInfo.NextType = fieldNextType + + return nil +} + +// EmailAddressAuthenticationCodeInfo Information about the email address authentication code that was sent +type EmailAddressAuthenticationCodeInfo struct { + tdCommon + EmailAddressPattern string `json:"email_address_pattern"` // Pattern of the email address to which an authentication code was sent + Length int32 `json:"length"` // Length of the code; 0 if unknown +} + +// MessageType return the string telegram-type of EmailAddressAuthenticationCodeInfo +func (emailAddressAuthenticationCodeInfo *EmailAddressAuthenticationCodeInfo) MessageType() string { + return "emailAddressAuthenticationCodeInfo" +} + +// NewEmailAddressAuthenticationCodeInfo creates a new EmailAddressAuthenticationCodeInfo +// +// @param emailAddressPattern Pattern of the email address to which an authentication code was sent +// @param length Length of the code; 0 if unknown +func NewEmailAddressAuthenticationCodeInfo(emailAddressPattern string, length int32) *EmailAddressAuthenticationCodeInfo { + emailAddressAuthenticationCodeInfoTemp := EmailAddressAuthenticationCodeInfo{ + tdCommon: tdCommon{Type: "emailAddressAuthenticationCodeInfo"}, + EmailAddressPattern: emailAddressPattern, + Length: length, + } + + return &emailAddressAuthenticationCodeInfoTemp +} + +// TextEntity Represents a part of the text that needs to be formatted in some unusual way +type TextEntity struct { + tdCommon + Offset int32 `json:"offset"` // Offset of the entity in UTF-16 code points + Length int32 `json:"length"` // Length of the entity, in UTF-16 code points + Type TextEntityType `json:"type"` // Type of the entity +} + +// MessageType return the string telegram-type of TextEntity +func (textEntity *TextEntity) MessageType() string { + return "textEntity" +} + +// NewTextEntity creates a new TextEntity +// +// @param offset Offset of the entity in UTF-16 code points +// @param length Length of the entity, in UTF-16 code points +// @param typeParam Type of the entity +func NewTextEntity(offset int32, length int32, typeParam TextEntityType) *TextEntity { + textEntityTemp := TextEntity{ + tdCommon: tdCommon{Type: "textEntity"}, + Offset: offset, + Length: length, + Type: typeParam, + } + + return &textEntityTemp +} + +// UnmarshalJSON unmarshal to json +func (textEntity *TextEntity) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Offset int32 `json:"offset"` // Offset of the entity in UTF-16 code points + Length int32 `json:"length"` // Length of the entity, in UTF-16 code points + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + textEntity.tdCommon = tempObj.tdCommon + textEntity.Offset = tempObj.Offset + textEntity.Length = tempObj.Length + + fieldType, _ := unmarshalTextEntityType(objMap["type"]) + textEntity.Type = fieldType + + return nil +} + +// TextEntities Contains a list of text entities +type TextEntities struct { + tdCommon + Entities []TextEntity `json:"entities"` // List of text entities +} + +// MessageType return the string telegram-type of TextEntities +func (textEntities *TextEntities) MessageType() string { + return "textEntities" +} + +// NewTextEntities creates a new TextEntities +// +// @param entities List of text entities +func NewTextEntities(entities []TextEntity) *TextEntities { + textEntitiesTemp := TextEntities{ + tdCommon: tdCommon{Type: "textEntities"}, + Entities: entities, + } + + return &textEntitiesTemp +} + +// FormattedText A text with some entities +type FormattedText struct { + tdCommon + Text string `json:"text"` // The text + Entities []TextEntity `json:"entities"` // Entities contained in the text +} + +// MessageType return the string telegram-type of FormattedText +func (formattedText *FormattedText) MessageType() string { + return "formattedText" +} + +// NewFormattedText creates a new FormattedText +// +// @param text The text +// @param entities Entities contained in the text +func NewFormattedText(text string, entities []TextEntity) *FormattedText { + formattedTextTemp := FormattedText{ + tdCommon: tdCommon{Type: "formattedText"}, + Text: text, + Entities: entities, + } + + return &formattedTextTemp +} + +// TermsOfService Contains Telegram terms of service +type TermsOfService struct { + tdCommon + Text *FormattedText `json:"text"` // Text of the terms of service + MinUserAge int32 `json:"min_user_age"` // Mininum age of a user to be able to accept the terms; 0 if any + ShowPopup bool `json:"show_popup"` // True, if a blocking popup with terms of service must be shown to the user +} + +// MessageType return the string telegram-type of TermsOfService +func (termsOfService *TermsOfService) MessageType() string { + return "termsOfService" +} + +// NewTermsOfService creates a new TermsOfService +// +// @param text Text of the terms of service +// @param minUserAge Mininum age of a user to be able to accept the terms; 0 if any +// @param showPopup True, if a blocking popup with terms of service must be shown to the user +func NewTermsOfService(text *FormattedText, minUserAge int32, showPopup bool) *TermsOfService { + termsOfServiceTemp := TermsOfService{ + tdCommon: tdCommon{Type: "termsOfService"}, + Text: text, + MinUserAge: minUserAge, + ShowPopup: showPopup, + } + + return &termsOfServiceTemp +} + +// AuthorizationStateWaitTdlibParameters TDLib needs TdlibParameters for initialization +type AuthorizationStateWaitTdlibParameters struct { + tdCommon +} + +// MessageType return the string telegram-type of AuthorizationStateWaitTdlibParameters +func (authorizationStateWaitTdlibParameters *AuthorizationStateWaitTdlibParameters) MessageType() string { + return "authorizationStateWaitTdlibParameters" +} + +// NewAuthorizationStateWaitTdlibParameters creates a new AuthorizationStateWaitTdlibParameters +// +func NewAuthorizationStateWaitTdlibParameters() *AuthorizationStateWaitTdlibParameters { + authorizationStateWaitTdlibParametersTemp := AuthorizationStateWaitTdlibParameters{ + tdCommon: tdCommon{Type: "authorizationStateWaitTdlibParameters"}, + } + + return &authorizationStateWaitTdlibParametersTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitTdlibParameters *AuthorizationStateWaitTdlibParameters) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitTdlibParametersType +} + +// AuthorizationStateWaitEncryptionKey TDLib needs an encryption key to decrypt the local database +type AuthorizationStateWaitEncryptionKey struct { + tdCommon + IsEncrypted bool `json:"is_encrypted"` // True, if the database is currently encrypted +} + +// MessageType return the string telegram-type of AuthorizationStateWaitEncryptionKey +func (authorizationStateWaitEncryptionKey *AuthorizationStateWaitEncryptionKey) MessageType() string { + return "authorizationStateWaitEncryptionKey" +} + +// NewAuthorizationStateWaitEncryptionKey creates a new AuthorizationStateWaitEncryptionKey +// +// @param isEncrypted True, if the database is currently encrypted +func NewAuthorizationStateWaitEncryptionKey(isEncrypted bool) *AuthorizationStateWaitEncryptionKey { + authorizationStateWaitEncryptionKeyTemp := AuthorizationStateWaitEncryptionKey{ + tdCommon: tdCommon{Type: "authorizationStateWaitEncryptionKey"}, + IsEncrypted: isEncrypted, + } + + return &authorizationStateWaitEncryptionKeyTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitEncryptionKey *AuthorizationStateWaitEncryptionKey) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitEncryptionKeyType +} + +// AuthorizationStateWaitPhoneNumber TDLib needs the user's phone number to authorize +type AuthorizationStateWaitPhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of AuthorizationStateWaitPhoneNumber +func (authorizationStateWaitPhoneNumber *AuthorizationStateWaitPhoneNumber) MessageType() string { + return "authorizationStateWaitPhoneNumber" +} + +// NewAuthorizationStateWaitPhoneNumber creates a new AuthorizationStateWaitPhoneNumber +// +func NewAuthorizationStateWaitPhoneNumber() *AuthorizationStateWaitPhoneNumber { + authorizationStateWaitPhoneNumberTemp := AuthorizationStateWaitPhoneNumber{ + tdCommon: tdCommon{Type: "authorizationStateWaitPhoneNumber"}, + } + + return &authorizationStateWaitPhoneNumberTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitPhoneNumber *AuthorizationStateWaitPhoneNumber) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitPhoneNumberType +} + +// AuthorizationStateWaitCode TDLib needs the user's authentication code to finalize authorization +type AuthorizationStateWaitCode struct { + tdCommon + IsRegistered bool `json:"is_registered"` // True, if the user is already registered + TermsOfService *TermsOfService `json:"terms_of_service"` // Telegram terms of service, which should be accepted before user can continue registration; may be null + CodeInfo *AuthenticationCodeInfo `json:"code_info"` // Information about the authorization code that was sent +} + +// MessageType return the string telegram-type of AuthorizationStateWaitCode +func (authorizationStateWaitCode *AuthorizationStateWaitCode) MessageType() string { + return "authorizationStateWaitCode" +} + +// NewAuthorizationStateWaitCode creates a new AuthorizationStateWaitCode +// +// @param isRegistered True, if the user is already registered +// @param termsOfService Telegram terms of service, which should be accepted before user can continue registration; may be null +// @param codeInfo Information about the authorization code that was sent +func NewAuthorizationStateWaitCode(isRegistered bool, termsOfService *TermsOfService, codeInfo *AuthenticationCodeInfo) *AuthorizationStateWaitCode { + authorizationStateWaitCodeTemp := AuthorizationStateWaitCode{ + tdCommon: tdCommon{Type: "authorizationStateWaitCode"}, + IsRegistered: isRegistered, + TermsOfService: termsOfService, + CodeInfo: codeInfo, + } + + return &authorizationStateWaitCodeTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitCode *AuthorizationStateWaitCode) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitCodeType +} + +// AuthorizationStateWaitPassword The user has been authorized, but needs to enter a password to start using the application +type AuthorizationStateWaitPassword struct { + tdCommon + PasswordHint string `json:"password_hint"` // Hint for the password; can be empty + HasRecoveryEmailAddress bool `json:"has_recovery_email_address"` // True if a recovery email address has been set up + RecoveryEmailAddressPattern string `json:"recovery_email_address_pattern"` // Pattern of the email address to which the recovery email was sent; empty until a recovery email has been sent +} + +// MessageType return the string telegram-type of AuthorizationStateWaitPassword +func (authorizationStateWaitPassword *AuthorizationStateWaitPassword) MessageType() string { + return "authorizationStateWaitPassword" +} + +// NewAuthorizationStateWaitPassword creates a new AuthorizationStateWaitPassword +// +// @param passwordHint Hint for the password; can be empty +// @param hasRecoveryEmailAddress True if a recovery email address has been set up +// @param recoveryEmailAddressPattern Pattern of the email address to which the recovery email was sent; empty until a recovery email has been sent +func NewAuthorizationStateWaitPassword(passwordHint string, hasRecoveryEmailAddress bool, recoveryEmailAddressPattern string) *AuthorizationStateWaitPassword { + authorizationStateWaitPasswordTemp := AuthorizationStateWaitPassword{ + tdCommon: tdCommon{Type: "authorizationStateWaitPassword"}, + PasswordHint: passwordHint, + HasRecoveryEmailAddress: hasRecoveryEmailAddress, + RecoveryEmailAddressPattern: recoveryEmailAddressPattern, + } + + return &authorizationStateWaitPasswordTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitPassword *AuthorizationStateWaitPassword) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitPasswordType +} + +// AuthorizationStateReady The user has been successfully authorized. TDLib is now ready to answer queries +type AuthorizationStateReady struct { + tdCommon +} + +// MessageType return the string telegram-type of AuthorizationStateReady +func (authorizationStateReady *AuthorizationStateReady) MessageType() string { + return "authorizationStateReady" +} + +// NewAuthorizationStateReady creates a new AuthorizationStateReady +// +func NewAuthorizationStateReady() *AuthorizationStateReady { + authorizationStateReadyTemp := AuthorizationStateReady{ + tdCommon: tdCommon{Type: "authorizationStateReady"}, + } + + return &authorizationStateReadyTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateReady *AuthorizationStateReady) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateReadyType +} + +// AuthorizationStateLoggingOut The user is currently logging out +type AuthorizationStateLoggingOut struct { + tdCommon +} + +// MessageType return the string telegram-type of AuthorizationStateLoggingOut +func (authorizationStateLoggingOut *AuthorizationStateLoggingOut) MessageType() string { + return "authorizationStateLoggingOut" +} + +// NewAuthorizationStateLoggingOut creates a new AuthorizationStateLoggingOut +// +func NewAuthorizationStateLoggingOut() *AuthorizationStateLoggingOut { + authorizationStateLoggingOutTemp := AuthorizationStateLoggingOut{ + tdCommon: tdCommon{Type: "authorizationStateLoggingOut"}, + } + + return &authorizationStateLoggingOutTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateLoggingOut *AuthorizationStateLoggingOut) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateLoggingOutType +} + +// AuthorizationStateClosing TDLib is closing, all subsequent queries will be answered with the error 500. Note that closing TDLib can take a while. All resources will be freed only after authorizationStateClosed has been received +type AuthorizationStateClosing struct { + tdCommon +} + +// MessageType return the string telegram-type of AuthorizationStateClosing +func (authorizationStateClosing *AuthorizationStateClosing) MessageType() string { + return "authorizationStateClosing" +} + +// NewAuthorizationStateClosing creates a new AuthorizationStateClosing +// +func NewAuthorizationStateClosing() *AuthorizationStateClosing { + authorizationStateClosingTemp := AuthorizationStateClosing{ + tdCommon: tdCommon{Type: "authorizationStateClosing"}, + } + + return &authorizationStateClosingTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateClosing *AuthorizationStateClosing) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateClosingType +} + +// AuthorizationStateClosed TDLib client is in its final state. All databases are closed and all resources are released. No other updates will be received after this. All queries will be responded to +type AuthorizationStateClosed struct { + tdCommon +} + +// MessageType return the string telegram-type of AuthorizationStateClosed +func (authorizationStateClosed *AuthorizationStateClosed) MessageType() string { + return "authorizationStateClosed" +} + +// NewAuthorizationStateClosed creates a new AuthorizationStateClosed +// +func NewAuthorizationStateClosed() *AuthorizationStateClosed { + authorizationStateClosedTemp := AuthorizationStateClosed{ + tdCommon: tdCommon{Type: "authorizationStateClosed"}, + } + + return &authorizationStateClosedTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateClosed *AuthorizationStateClosed) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateClosedType +} + +// PasswordState Represents the current state of 2-step verification +type PasswordState struct { + tdCommon + HasPassword bool `json:"has_password"` // True if a 2-step verification password is set + PasswordHint string `json:"password_hint"` // Hint for the password; can be empty + HasRecoveryEmailAddress bool `json:"has_recovery_email_address"` // True if a recovery email is set + HasPassportData bool `json:"has_passport_data"` // True if some Telegram Passport elements were saved + UnconfirmedRecoveryEmailAddressPattern string `json:"unconfirmed_recovery_email_address_pattern"` // Pattern of the email address to which the confirmation email was sent +} + +// MessageType return the string telegram-type of PasswordState +func (passwordState *PasswordState) MessageType() string { + return "passwordState" +} + +// NewPasswordState creates a new PasswordState +// +// @param hasPassword True if a 2-step verification password is set +// @param passwordHint Hint for the password; can be empty +// @param hasRecoveryEmailAddress True if a recovery email is set +// @param hasPassportData True if some Telegram Passport elements were saved +// @param unconfirmedRecoveryEmailAddressPattern Pattern of the email address to which the confirmation email was sent +func NewPasswordState(hasPassword bool, passwordHint string, hasRecoveryEmailAddress bool, hasPassportData bool, unconfirmedRecoveryEmailAddressPattern string) *PasswordState { + passwordStateTemp := PasswordState{ + tdCommon: tdCommon{Type: "passwordState"}, + HasPassword: hasPassword, + PasswordHint: passwordHint, + HasRecoveryEmailAddress: hasRecoveryEmailAddress, + HasPassportData: hasPassportData, + UnconfirmedRecoveryEmailAddressPattern: unconfirmedRecoveryEmailAddressPattern, + } + + return &passwordStateTemp +} + +// RecoveryEmailAddress Contains information about the current recovery email address +type RecoveryEmailAddress struct { + tdCommon + RecoveryEmailAddress string `json:"recovery_email_address"` // Recovery email address +} + +// MessageType return the string telegram-type of RecoveryEmailAddress +func (recoveryEmailAddress *RecoveryEmailAddress) MessageType() string { + return "recoveryEmailAddress" +} + +// NewRecoveryEmailAddress creates a new RecoveryEmailAddress +// +// @param recoveryEmailAddress Recovery email address +func NewRecoveryEmailAddress(recoveryEmailAddress string) *RecoveryEmailAddress { + recoveryEmailAddressTemp := RecoveryEmailAddress{ + tdCommon: tdCommon{Type: "recoveryEmailAddress"}, + RecoveryEmailAddress: recoveryEmailAddress, + } + + return &recoveryEmailAddressTemp +} + +// TemporaryPasswordState Returns information about the availability of a temporary password, which can be used for payments +type TemporaryPasswordState struct { + tdCommon + HasPassword bool `json:"has_password"` // True, if a temporary password is available + ValidFor int32 `json:"valid_for"` // Time left before the temporary password expires, in seconds +} + +// MessageType return the string telegram-type of TemporaryPasswordState +func (temporaryPasswordState *TemporaryPasswordState) MessageType() string { + return "temporaryPasswordState" +} + +// NewTemporaryPasswordState creates a new TemporaryPasswordState +// +// @param hasPassword True, if a temporary password is available +// @param validFor Time left before the temporary password expires, in seconds +func NewTemporaryPasswordState(hasPassword bool, validFor int32) *TemporaryPasswordState { + temporaryPasswordStateTemp := TemporaryPasswordState{ + tdCommon: tdCommon{Type: "temporaryPasswordState"}, + HasPassword: hasPassword, + ValidFor: validFor, + } + + return &temporaryPasswordStateTemp +} + +// LocalFile Represents a local file +type LocalFile struct { + tdCommon + Path string `json:"path"` // Local path to the locally available file part; may be empty + CanBeDownloaded bool `json:"can_be_downloaded"` // True, if it is possible to try to download or generate the file + CanBeDeleted bool `json:"can_be_deleted"` // True, if the file can be deleted + IsDownloadingActive bool `json:"is_downloading_active"` // True, if the file is currently being downloaded (or a local copy is being generated by some other means) + IsDownloadingCompleted bool `json:"is_downloading_completed"` // True, if the local copy is fully available + DownloadedPrefixSize int32 `json:"downloaded_prefix_size"` // If is_downloading_completed is false, then only some prefix of the file is ready to be read. downloaded_prefix_size is the size of that prefix + DownloadedSize int32 `json:"downloaded_size"` // Total downloaded file bytes. Should be used only for calculating download progress. The actual file size may be bigger, and some parts of it may contain garbage +} + +// MessageType return the string telegram-type of LocalFile +func (localFile *LocalFile) MessageType() string { + return "localFile" +} + +// NewLocalFile creates a new LocalFile +// +// @param path Local path to the locally available file part; may be empty +// @param canBeDownloaded True, if it is possible to try to download or generate the file +// @param canBeDeleted True, if the file can be deleted +// @param isDownloadingActive True, if the file is currently being downloaded (or a local copy is being generated by some other means) +// @param isDownloadingCompleted True, if the local copy is fully available +// @param downloadedPrefixSize If is_downloading_completed is false, then only some prefix of the file is ready to be read. downloaded_prefix_size is the size of that prefix +// @param downloadedSize Total downloaded file bytes. Should be used only for calculating download progress. The actual file size may be bigger, and some parts of it may contain garbage +func NewLocalFile(path string, canBeDownloaded bool, canBeDeleted bool, isDownloadingActive bool, isDownloadingCompleted bool, downloadedPrefixSize int32, downloadedSize int32) *LocalFile { + localFileTemp := LocalFile{ + tdCommon: tdCommon{Type: "localFile"}, + Path: path, + CanBeDownloaded: canBeDownloaded, + CanBeDeleted: canBeDeleted, + IsDownloadingActive: isDownloadingActive, + IsDownloadingCompleted: isDownloadingCompleted, + DownloadedPrefixSize: downloadedPrefixSize, + DownloadedSize: downloadedSize, + } + + return &localFileTemp +} + +// RemoteFile Represents a remote file +type RemoteFile struct { + tdCommon + ID string `json:"id"` // Remote file identifier; may be empty. Can be used across application restarts or even from other devices for the current user. If the ID starts with "http://" or "https://", it represents the HTTP URL of the file. TDLib is currently unable to download files if only their URL is known. + IsUploadingActive bool `json:"is_uploading_active"` // True, if the file is currently being uploaded (or a remote copy is being generated by some other means) + IsUploadingCompleted bool `json:"is_uploading_completed"` // True, if a remote copy is fully available + UploadedSize int32 `json:"uploaded_size"` // Size of the remote available part of the file; 0 if unknown +} + +// MessageType return the string telegram-type of RemoteFile +func (remoteFile *RemoteFile) MessageType() string { + return "remoteFile" +} + +// NewRemoteFile creates a new RemoteFile +// +// @param iD Remote file identifier; may be empty. Can be used across application restarts or even from other devices for the current user. If the ID starts with "http://" or "https://", it represents the HTTP URL of the file. TDLib is currently unable to download files if only their URL is known. +// @param isUploadingActive True, if the file is currently being uploaded (or a remote copy is being generated by some other means) +// @param isUploadingCompleted True, if a remote copy is fully available +// @param uploadedSize Size of the remote available part of the file; 0 if unknown +func NewRemoteFile(iD string, isUploadingActive bool, isUploadingCompleted bool, uploadedSize int32) *RemoteFile { + remoteFileTemp := RemoteFile{ + tdCommon: tdCommon{Type: "remoteFile"}, + ID: iD, + IsUploadingActive: isUploadingActive, + IsUploadingCompleted: isUploadingCompleted, + UploadedSize: uploadedSize, + } + + return &remoteFileTemp +} + +// File Represents a file +type File struct { + tdCommon + ID int32 `json:"id"` // Unique file identifier + Size int32 `json:"size"` // File size; 0 if unknown + ExpectedSize int32 `json:"expected_size"` // Expected file size in case the exact file size is unknown, but an approximate size is known. Can be used to show download/upload progress + Local *LocalFile `json:"local"` // Information about the local copy of the file + Remote *RemoteFile `json:"remote"` // Information about the remote copy of the file +} + +// MessageType return the string telegram-type of File +func (file *File) MessageType() string { + return "file" +} + +// NewFile creates a new File +// +// @param iD Unique file identifier +// @param size File size; 0 if unknown +// @param expectedSize Expected file size in case the exact file size is unknown, but an approximate size is known. Can be used to show download/upload progress +// @param local Information about the local copy of the file +// @param remote Information about the remote copy of the file +func NewFile(iD int32, size int32, expectedSize int32, local *LocalFile, remote *RemoteFile) *File { + fileTemp := File{ + tdCommon: tdCommon{Type: "file"}, + ID: iD, + Size: size, + ExpectedSize: expectedSize, + Local: local, + Remote: remote, + } + + return &fileTemp +} + +// InputFileID A file defined by its unique ID +type InputFileID struct { + tdCommon + ID int32 `json:"id"` // Unique file identifier +} + +// MessageType return the string telegram-type of InputFileID +func (inputFileID *InputFileID) MessageType() string { + return "inputFileId" +} + +// NewInputFileID creates a new InputFileID +// +// @param iD Unique file identifier +func NewInputFileID(iD int32) *InputFileID { + inputFileIDTemp := InputFileID{ + tdCommon: tdCommon{Type: "inputFileId"}, + ID: iD, + } + + return &inputFileIDTemp +} + +// GetInputFileEnum return the enum type of this object +func (inputFileID *InputFileID) GetInputFileEnum() InputFileEnum { + return InputFileIDType +} + +// InputFileRemote A file defined by its remote ID +type InputFileRemote struct { + tdCommon + ID string `json:"id"` // Remote file identifier +} + +// MessageType return the string telegram-type of InputFileRemote +func (inputFileRemote *InputFileRemote) MessageType() string { + return "inputFileRemote" +} + +// NewInputFileRemote creates a new InputFileRemote +// +// @param iD Remote file identifier +func NewInputFileRemote(iD string) *InputFileRemote { + inputFileRemoteTemp := InputFileRemote{ + tdCommon: tdCommon{Type: "inputFileRemote"}, + ID: iD, + } + + return &inputFileRemoteTemp +} + +// GetInputFileEnum return the enum type of this object +func (inputFileRemote *InputFileRemote) GetInputFileEnum() InputFileEnum { + return InputFileRemoteType +} + +// InputFileLocal A file defined by a local path +type InputFileLocal struct { + tdCommon + Path string `json:"path"` // Local path to the file +} + +// MessageType return the string telegram-type of InputFileLocal +func (inputFileLocal *InputFileLocal) MessageType() string { + return "inputFileLocal" +} + +// NewInputFileLocal creates a new InputFileLocal +// +// @param path Local path to the file +func NewInputFileLocal(path string) *InputFileLocal { + inputFileLocalTemp := InputFileLocal{ + tdCommon: tdCommon{Type: "inputFileLocal"}, + Path: path, + } + + return &inputFileLocalTemp +} + +// GetInputFileEnum return the enum type of this object +func (inputFileLocal *InputFileLocal) GetInputFileEnum() InputFileEnum { + return InputFileLocalType +} + +// InputFileGenerated A file generated by the client +type InputFileGenerated struct { + tdCommon + OriginalPath string `json:"original_path"` // Local path to a file from which the file is generated; may be empty if there is no such file + Conversion string `json:"conversion"` // String specifying the conversion applied to the original file; should be persistent across application restarts + ExpectedSize int32 `json:"expected_size"` // Expected size of the generated file; 0 if unknown +} + +// MessageType return the string telegram-type of InputFileGenerated +func (inputFileGenerated *InputFileGenerated) MessageType() string { + return "inputFileGenerated" +} + +// NewInputFileGenerated creates a new InputFileGenerated +// +// @param originalPath Local path to a file from which the file is generated; may be empty if there is no such file +// @param conversion String specifying the conversion applied to the original file; should be persistent across application restarts +// @param expectedSize Expected size of the generated file; 0 if unknown +func NewInputFileGenerated(originalPath string, conversion string, expectedSize int32) *InputFileGenerated { + inputFileGeneratedTemp := InputFileGenerated{ + tdCommon: tdCommon{Type: "inputFileGenerated"}, + OriginalPath: originalPath, + Conversion: conversion, + ExpectedSize: expectedSize, + } + + return &inputFileGeneratedTemp +} + +// GetInputFileEnum return the enum type of this object +func (inputFileGenerated *InputFileGenerated) GetInputFileEnum() InputFileEnum { + return InputFileGeneratedType +} + +// PhotoSize Photo description +type PhotoSize struct { + tdCommon + Type string `json:"type"` // Thumbnail type (see https://core.telegram.org/constructor/photoSize) + Photo *File `json:"photo"` // Information about the photo file + Width int32 `json:"width"` // Photo width + Height int32 `json:"height"` // Photo height +} + +// MessageType return the string telegram-type of PhotoSize +func (photoSize *PhotoSize) MessageType() string { + return "photoSize" +} + +// NewPhotoSize creates a new PhotoSize +// +// @param typeParam Thumbnail type (see https://core.telegram.org/constructor/photoSize) +// @param photo Information about the photo file +// @param width Photo width +// @param height Photo height +func NewPhotoSize(typeParam string, photo *File, width int32, height int32) *PhotoSize { + photoSizeTemp := PhotoSize{ + tdCommon: tdCommon{Type: "photoSize"}, + Type: typeParam, + Photo: photo, + Width: width, + Height: height, + } + + return &photoSizeTemp +} + +// MaskPointForehead A mask should be placed relatively to the forehead +type MaskPointForehead struct { + tdCommon +} + +// MessageType return the string telegram-type of MaskPointForehead +func (maskPointForehead *MaskPointForehead) MessageType() string { + return "maskPointForehead" +} + +// NewMaskPointForehead creates a new MaskPointForehead +// +func NewMaskPointForehead() *MaskPointForehead { + maskPointForeheadTemp := MaskPointForehead{ + tdCommon: tdCommon{Type: "maskPointForehead"}, + } + + return &maskPointForeheadTemp +} + +// GetMaskPointEnum return the enum type of this object +func (maskPointForehead *MaskPointForehead) GetMaskPointEnum() MaskPointEnum { + return MaskPointForeheadType +} + +// MaskPointEyes A mask should be placed relatively to the eyes +type MaskPointEyes struct { + tdCommon +} + +// MessageType return the string telegram-type of MaskPointEyes +func (maskPointEyes *MaskPointEyes) MessageType() string { + return "maskPointEyes" +} + +// NewMaskPointEyes creates a new MaskPointEyes +// +func NewMaskPointEyes() *MaskPointEyes { + maskPointEyesTemp := MaskPointEyes{ + tdCommon: tdCommon{Type: "maskPointEyes"}, + } + + return &maskPointEyesTemp +} + +// GetMaskPointEnum return the enum type of this object +func (maskPointEyes *MaskPointEyes) GetMaskPointEnum() MaskPointEnum { + return MaskPointEyesType +} + +// MaskPointMouth A mask should be placed relatively to the mouth +type MaskPointMouth struct { + tdCommon +} + +// MessageType return the string telegram-type of MaskPointMouth +func (maskPointMouth *MaskPointMouth) MessageType() string { + return "maskPointMouth" +} + +// NewMaskPointMouth creates a new MaskPointMouth +// +func NewMaskPointMouth() *MaskPointMouth { + maskPointMouthTemp := MaskPointMouth{ + tdCommon: tdCommon{Type: "maskPointMouth"}, + } + + return &maskPointMouthTemp +} + +// GetMaskPointEnum return the enum type of this object +func (maskPointMouth *MaskPointMouth) GetMaskPointEnum() MaskPointEnum { + return MaskPointMouthType +} + +// MaskPointChin A mask should be placed relatively to the chin +type MaskPointChin struct { + tdCommon +} + +// MessageType return the string telegram-type of MaskPointChin +func (maskPointChin *MaskPointChin) MessageType() string { + return "maskPointChin" +} + +// NewMaskPointChin creates a new MaskPointChin +// +func NewMaskPointChin() *MaskPointChin { + maskPointChinTemp := MaskPointChin{ + tdCommon: tdCommon{Type: "maskPointChin"}, + } + + return &maskPointChinTemp +} + +// GetMaskPointEnum return the enum type of this object +func (maskPointChin *MaskPointChin) GetMaskPointEnum() MaskPointEnum { + return MaskPointChinType +} + +// MaskPosition Position on a photo where a mask should be placed +type MaskPosition struct { + tdCommon + Point MaskPoint `json:"point"` // Part of the face, relative to which the mask should be placed + XShift float64 `json:"x_shift"` // Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. (For example, -1.0 will place the mask just to the left of the default mask position) + YShift float64 `json:"y_shift"` // Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. (For example, 1.0 will place the mask just below the default mask position) + Scale float64 `json:"scale"` // Mask scaling coefficient. (For example, 2.0 means a doubled size) +} + +// MessageType return the string telegram-type of MaskPosition +func (maskPosition *MaskPosition) MessageType() string { + return "maskPosition" +} + +// NewMaskPosition creates a new MaskPosition +// +// @param point Part of the face, relative to which the mask should be placed +// @param xShift Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. (For example, -1.0 will place the mask just to the left of the default mask position) +// @param yShift Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. (For example, 1.0 will place the mask just below the default mask position) +// @param scale Mask scaling coefficient. (For example, 2.0 means a doubled size) +func NewMaskPosition(point MaskPoint, xShift float64, yShift float64, scale float64) *MaskPosition { + maskPositionTemp := MaskPosition{ + tdCommon: tdCommon{Type: "maskPosition"}, + Point: point, + XShift: xShift, + YShift: yShift, + Scale: scale, + } + + return &maskPositionTemp +} + +// UnmarshalJSON unmarshal to json +func (maskPosition *MaskPosition) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + XShift float64 `json:"x_shift"` // Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. (For example, -1.0 will place the mask just to the left of the default mask position) + YShift float64 `json:"y_shift"` // Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. (For example, 1.0 will place the mask just below the default mask position) + Scale float64 `json:"scale"` // Mask scaling coefficient. (For example, 2.0 means a doubled size) + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + maskPosition.tdCommon = tempObj.tdCommon + maskPosition.XShift = tempObj.XShift + maskPosition.YShift = tempObj.YShift + maskPosition.Scale = tempObj.Scale + + fieldPoint, _ := unmarshalMaskPoint(objMap["point"]) + maskPosition.Point = fieldPoint + + return nil +} + +// Animation Describes an animation file. The animation must be encoded in GIF or MPEG4 format +type Animation struct { + tdCommon + Duration int32 `json:"duration"` // Duration of the animation, in seconds; as defined by the sender + Width int32 `json:"width"` // Width of the animation + Height int32 `json:"height"` // Height of the animation + FileName string `json:"file_name"` // Original name of the file; as defined by the sender + MimeType string `json:"mime_type"` // MIME type of the file, usually "image/gif" or "video/mp4" + Thumbnail *PhotoSize `json:"thumbnail"` // Animation thumbnail; may be null + Animation *File `json:"animation"` // File containing the animation +} + +// MessageType return the string telegram-type of Animation +func (animation *Animation) MessageType() string { + return "animation" +} + +// NewAnimation creates a new Animation +// +// @param duration Duration of the animation, in seconds; as defined by the sender +// @param width Width of the animation +// @param height Height of the animation +// @param fileName Original name of the file; as defined by the sender +// @param mimeType MIME type of the file, usually "image/gif" or "video/mp4" +// @param thumbnail Animation thumbnail; may be null +// @param animation File containing the animation +func NewAnimation(duration int32, width int32, height int32, fileName string, mimeType string, thumbnail *PhotoSize, animation *File) *Animation { + animationTemp := Animation{ + tdCommon: tdCommon{Type: "animation"}, + Duration: duration, + Width: width, + Height: height, + FileName: fileName, + MimeType: mimeType, + Thumbnail: thumbnail, + Animation: animation, + } + + return &animationTemp +} + +// Audio Describes an audio file. Audio is usually in MP3 format +type Audio struct { + tdCommon + Duration int32 `json:"duration"` // Duration of the audio, in seconds; as defined by the sender + Title string `json:"title"` // Title of the audio; as defined by the sender + Performer string `json:"performer"` // Performer of the audio; as defined by the sender + FileName string `json:"file_name"` // Original name of the file; as defined by the sender + MimeType string `json:"mime_type"` // The MIME type of the file; as defined by the sender + AlbumCoverThumbnail *PhotoSize `json:"album_cover_thumbnail"` // The thumbnail of the album cover; as defined by the sender. The full size thumbnail should be extracted from the downloaded file; may be null + Audio *File `json:"audio"` // File containing the audio +} + +// MessageType return the string telegram-type of Audio +func (audio *Audio) MessageType() string { + return "audio" +} + +// NewAudio creates a new Audio +// +// @param duration Duration of the audio, in seconds; as defined by the sender +// @param title Title of the audio; as defined by the sender +// @param performer Performer of the audio; as defined by the sender +// @param fileName Original name of the file; as defined by the sender +// @param mimeType The MIME type of the file; as defined by the sender +// @param albumCoverThumbnail The thumbnail of the album cover; as defined by the sender. The full size thumbnail should be extracted from the downloaded file; may be null +// @param audio File containing the audio +func NewAudio(duration int32, title string, performer string, fileName string, mimeType string, albumCoverThumbnail *PhotoSize, audio *File) *Audio { + audioTemp := Audio{ + tdCommon: tdCommon{Type: "audio"}, + Duration: duration, + Title: title, + Performer: performer, + FileName: fileName, + MimeType: mimeType, + AlbumCoverThumbnail: albumCoverThumbnail, + Audio: audio, + } + + return &audioTemp +} + +// Document Describes a document of any type +type Document struct { + tdCommon + FileName string `json:"file_name"` // Original name of the file; as defined by the sender + MimeType string `json:"mime_type"` // MIME type of the file; as defined by the sender + Thumbnail *PhotoSize `json:"thumbnail"` // Document thumbnail; as defined by the sender; may be null + Document *File `json:"document"` // File containing the document +} + +// MessageType return the string telegram-type of Document +func (document *Document) MessageType() string { + return "document" +} + +// NewDocument creates a new Document +// +// @param fileName Original name of the file; as defined by the sender +// @param mimeType MIME type of the file; as defined by the sender +// @param thumbnail Document thumbnail; as defined by the sender; may be null +// @param document File containing the document +func NewDocument(fileName string, mimeType string, thumbnail *PhotoSize, document *File) *Document { + documentTemp := Document{ + tdCommon: tdCommon{Type: "document"}, + FileName: fileName, + MimeType: mimeType, + Thumbnail: thumbnail, + Document: document, + } + + return &documentTemp +} + +// Photo Describes a photo +type Photo struct { + tdCommon + ID JSONInt64 `json:"id"` // Photo identifier; 0 for deleted photos + HasStickers bool `json:"has_stickers"` // True, if stickers were added to the photo + Sizes []PhotoSize `json:"sizes"` // Available variants of the photo, in different sizes +} + +// MessageType return the string telegram-type of Photo +func (photo *Photo) MessageType() string { + return "photo" +} + +// NewPhoto creates a new Photo +// +// @param iD Photo identifier; 0 for deleted photos +// @param hasStickers True, if stickers were added to the photo +// @param sizes Available variants of the photo, in different sizes +func NewPhoto(iD JSONInt64, hasStickers bool, sizes []PhotoSize) *Photo { + photoTemp := Photo{ + tdCommon: tdCommon{Type: "photo"}, + ID: iD, + HasStickers: hasStickers, + Sizes: sizes, + } + + return &photoTemp +} + +// Sticker Describes a sticker +type Sticker struct { + tdCommon + SetID JSONInt64 `json:"set_id"` // The identifier of the sticker set to which the sticker belongs; 0 if none + Width int32 `json:"width"` // Sticker width; as defined by the sender + Height int32 `json:"height"` // Sticker height; as defined by the sender + Emoji string `json:"emoji"` // Emoji corresponding to the sticker + IsMask bool `json:"is_mask"` // True, if the sticker is a mask + MaskPosition *MaskPosition `json:"mask_position"` // Position where the mask should be placed; may be null + Thumbnail *PhotoSize `json:"thumbnail"` // Sticker thumbnail in WEBP or JPEG format; may be null + Sticker *File `json:"sticker"` // File containing the sticker +} + +// MessageType return the string telegram-type of Sticker +func (sticker *Sticker) MessageType() string { + return "sticker" +} + +// NewSticker creates a new Sticker +// +// @param setID The identifier of the sticker set to which the sticker belongs; 0 if none +// @param width Sticker width; as defined by the sender +// @param height Sticker height; as defined by the sender +// @param emoji Emoji corresponding to the sticker +// @param isMask True, if the sticker is a mask +// @param maskPosition Position where the mask should be placed; may be null +// @param thumbnail Sticker thumbnail in WEBP or JPEG format; may be null +// @param sticker File containing the sticker +func NewSticker(setID JSONInt64, width int32, height int32, emoji string, isMask bool, maskPosition *MaskPosition, thumbnail *PhotoSize, sticker *File) *Sticker { + stickerTemp := Sticker{ + tdCommon: tdCommon{Type: "sticker"}, + SetID: setID, + Width: width, + Height: height, + Emoji: emoji, + IsMask: isMask, + MaskPosition: maskPosition, + Thumbnail: thumbnail, + Sticker: sticker, + } + + return &stickerTemp +} + +// Video Describes a video file +type Video struct { + tdCommon + Duration int32 `json:"duration"` // Duration of the video, in seconds; as defined by the sender + Width int32 `json:"width"` // Video width; as defined by the sender + Height int32 `json:"height"` // Video height; as defined by the sender + FileName string `json:"file_name"` // Original name of the file; as defined by the sender + MimeType string `json:"mime_type"` // MIME type of the file; as defined by the sender + HasStickers bool `json:"has_stickers"` // True, if stickers were added to the photo + SupportsStreaming bool `json:"supports_streaming"` // True, if the video should be tried to be streamed + Thumbnail *PhotoSize `json:"thumbnail"` // Video thumbnail; as defined by the sender; may be null + Video *File `json:"video"` // File containing the video +} + +// MessageType return the string telegram-type of Video +func (video *Video) MessageType() string { + return "video" +} + +// NewVideo creates a new Video +// +// @param duration Duration of the video, in seconds; as defined by the sender +// @param width Video width; as defined by the sender +// @param height Video height; as defined by the sender +// @param fileName Original name of the file; as defined by the sender +// @param mimeType MIME type of the file; as defined by the sender +// @param hasStickers True, if stickers were added to the photo +// @param supportsStreaming True, if the video should be tried to be streamed +// @param thumbnail Video thumbnail; as defined by the sender; may be null +// @param video File containing the video +func NewVideo(duration int32, width int32, height int32, fileName string, mimeType string, hasStickers bool, supportsStreaming bool, thumbnail *PhotoSize, video *File) *Video { + videoTemp := Video{ + tdCommon: tdCommon{Type: "video"}, + Duration: duration, + Width: width, + Height: height, + FileName: fileName, + MimeType: mimeType, + HasStickers: hasStickers, + SupportsStreaming: supportsStreaming, + Thumbnail: thumbnail, + Video: video, + } + + return &videoTemp +} + +// VideoNote Describes a video note. The video must be equal in width and height, cropped to a circle, and stored in MPEG4 format +type VideoNote struct { + tdCommon + Duration int32 `json:"duration"` // Duration of the video, in seconds; as defined by the sender + Length int32 `json:"length"` // Video width and height; as defined by the sender + Thumbnail *PhotoSize `json:"thumbnail"` // Video thumbnail; as defined by the sender; may be null + Video *File `json:"video"` // File containing the video +} + +// MessageType return the string telegram-type of VideoNote +func (videoNote *VideoNote) MessageType() string { + return "videoNote" +} + +// NewVideoNote creates a new VideoNote +// +// @param duration Duration of the video, in seconds; as defined by the sender +// @param length Video width and height; as defined by the sender +// @param thumbnail Video thumbnail; as defined by the sender; may be null +// @param video File containing the video +func NewVideoNote(duration int32, length int32, thumbnail *PhotoSize, video *File) *VideoNote { + videoNoteTemp := VideoNote{ + tdCommon: tdCommon{Type: "videoNote"}, + Duration: duration, + Length: length, + Thumbnail: thumbnail, + Video: video, + } + + return &videoNoteTemp +} + +// VoiceNote Describes a voice note. The voice note must be encoded with the Opus codec, and stored inside an OGG container. Voice notes can have only a single audio channel +type VoiceNote struct { + tdCommon + Duration int32 `json:"duration"` // Duration of the voice note, in seconds; as defined by the sender + Waveform []byte `json:"waveform"` // A waveform representation of the voice note in 5-bit format + MimeType string `json:"mime_type"` // MIME type of the file; as defined by the sender + Voice *File `json:"voice"` // File containing the voice note +} + +// MessageType return the string telegram-type of VoiceNote +func (voiceNote *VoiceNote) MessageType() string { + return "voiceNote" +} + +// NewVoiceNote creates a new VoiceNote +// +// @param duration Duration of the voice note, in seconds; as defined by the sender +// @param waveform A waveform representation of the voice note in 5-bit format +// @param mimeType MIME type of the file; as defined by the sender +// @param voice File containing the voice note +func NewVoiceNote(duration int32, waveform []byte, mimeType string, voice *File) *VoiceNote { + voiceNoteTemp := VoiceNote{ + tdCommon: tdCommon{Type: "voiceNote"}, + Duration: duration, + Waveform: waveform, + MimeType: mimeType, + Voice: voice, + } + + return &voiceNoteTemp +} + +// Contact Describes a user contact +type Contact struct { + tdCommon + PhoneNumber string `json:"phone_number"` // Phone number of the user + FirstName string `json:"first_name"` // First name of the user; 1-255 characters in length + LastName string `json:"last_name"` // Last name of the user + Vcard string `json:"vcard"` // Additional data about the user in a form of vCard; 0-2048 bytes in length + UserID int32 `json:"user_id"` // Identifier of the user, if known; otherwise 0 +} + +// MessageType return the string telegram-type of Contact +func (contact *Contact) MessageType() string { + return "contact" +} + +// NewContact creates a new Contact +// +// @param phoneNumber Phone number of the user +// @param firstName First name of the user; 1-255 characters in length +// @param lastName Last name of the user +// @param vcard Additional data about the user in a form of vCard; 0-2048 bytes in length +// @param userID Identifier of the user, if known; otherwise 0 +func NewContact(phoneNumber string, firstName string, lastName string, vcard string, userID int32) *Contact { + contactTemp := Contact{ + tdCommon: tdCommon{Type: "contact"}, + PhoneNumber: phoneNumber, + FirstName: firstName, + LastName: lastName, + Vcard: vcard, + UserID: userID, + } + + return &contactTemp +} + +// Location Describes a location on planet Earth +type Location struct { + tdCommon + Latitude float64 `json:"latitude"` // Latitude of the location in degrees; as defined by the sender + Longitude float64 `json:"longitude"` // Longitude of the location, in degrees; as defined by the sender +} + +// MessageType return the string telegram-type of Location +func (location *Location) MessageType() string { + return "location" +} + +// NewLocation creates a new Location +// +// @param latitude Latitude of the location in degrees; as defined by the sender +// @param longitude Longitude of the location, in degrees; as defined by the sender +func NewLocation(latitude float64, longitude float64) *Location { + locationTemp := Location{ + tdCommon: tdCommon{Type: "location"}, + Latitude: latitude, + Longitude: longitude, + } + + return &locationTemp +} + +// Venue Describes a venue +type Venue struct { + tdCommon + Location *Location `json:"location"` // Venue location; as defined by the sender + Title string `json:"title"` // Venue name; as defined by the sender + Address string `json:"address"` // Venue address; as defined by the sender + Provider string `json:"provider"` // Provider of the venue database; as defined by the sender. Currently only "foursquare" needs to be supported + ID string `json:"id"` // Identifier of the venue in the provider database; as defined by the sender + Type string `json:"type"` // Type of the venue in the provider database; as defined by the sender +} + +// MessageType return the string telegram-type of Venue +func (venue *Venue) MessageType() string { + return "venue" +} + +// NewVenue creates a new Venue +// +// @param location Venue location; as defined by the sender +// @param title Venue name; as defined by the sender +// @param address Venue address; as defined by the sender +// @param provider Provider of the venue database; as defined by the sender. Currently only "foursquare" needs to be supported +// @param iD Identifier of the venue in the provider database; as defined by the sender +// @param typeParam Type of the venue in the provider database; as defined by the sender +func NewVenue(location *Location, title string, address string, provider string, iD string, typeParam string) *Venue { + venueTemp := Venue{ + tdCommon: tdCommon{Type: "venue"}, + Location: location, + Title: title, + Address: address, + Provider: provider, + ID: iD, + Type: typeParam, + } + + return &venueTemp +} + +// Game Describes a game +type Game struct { + tdCommon + ID JSONInt64 `json:"id"` // Game ID + ShortName string `json:"short_name"` // Game short name. To share a game use the URL https://t.me/{bot_username}?game={game_short_name} + Title string `json:"title"` // Game title + Text *FormattedText `json:"text"` // Game text, usually containing scoreboards for a game + Description string `json:"description"` // + Photo *Photo `json:"photo"` // Game photo + Animation *Animation `json:"animation"` // Game animation; may be null +} + +// MessageType return the string telegram-type of Game +func (game *Game) MessageType() string { + return "game" +} + +// NewGame creates a new Game +// +// @param iD Game ID +// @param shortName Game short name. To share a game use the URL https://t.me/{bot_username}?game={game_short_name} +// @param title Game title +// @param text Game text, usually containing scoreboards for a game +// @param description +// @param photo Game photo +// @param animation Game animation; may be null +func NewGame(iD JSONInt64, shortName string, title string, text *FormattedText, description string, photo *Photo, animation *Animation) *Game { + gameTemp := Game{ + tdCommon: tdCommon{Type: "game"}, + ID: iD, + ShortName: shortName, + Title: title, + Text: text, + Description: description, + Photo: photo, + Animation: animation, + } + + return &gameTemp +} + +// ProfilePhoto Describes a user profile photo +type ProfilePhoto struct { + tdCommon + ID JSONInt64 `json:"id"` // Photo identifier; 0 for an empty photo. Can be used to find a photo in a list of userProfilePhotos + Small *File `json:"small"` // A small (160x160) user profile photo + Big *File `json:"big"` // A big (640x640) user profile photo +} + +// MessageType return the string telegram-type of ProfilePhoto +func (profilePhoto *ProfilePhoto) MessageType() string { + return "profilePhoto" +} + +// NewProfilePhoto creates a new ProfilePhoto +// +// @param iD Photo identifier; 0 for an empty photo. Can be used to find a photo in a list of userProfilePhotos +// @param small A small (160x160) user profile photo +// @param big A big (640x640) user profile photo +func NewProfilePhoto(iD JSONInt64, small *File, big *File) *ProfilePhoto { + profilePhotoTemp := ProfilePhoto{ + tdCommon: tdCommon{Type: "profilePhoto"}, + ID: iD, + Small: small, + Big: big, + } + + return &profilePhotoTemp +} + +// ChatPhoto Describes the photo of a chat +type ChatPhoto struct { + tdCommon + Small *File `json:"small"` // A small (160x160) chat photo + Big *File `json:"big"` // A big (640x640) chat photo +} + +// MessageType return the string telegram-type of ChatPhoto +func (chatPhoto *ChatPhoto) MessageType() string { + return "chatPhoto" +} + +// NewChatPhoto creates a new ChatPhoto +// +// @param small A small (160x160) chat photo +// @param big A big (640x640) chat photo +func NewChatPhoto(small *File, big *File) *ChatPhoto { + chatPhotoTemp := ChatPhoto{ + tdCommon: tdCommon{Type: "chatPhoto"}, + Small: small, + Big: big, + } + + return &chatPhotoTemp +} + +// LinkStateNone The phone number of user A is not known to user B +type LinkStateNone struct { + tdCommon +} + +// MessageType return the string telegram-type of LinkStateNone +func (linkStateNone *LinkStateNone) MessageType() string { + return "linkStateNone" +} + +// NewLinkStateNone creates a new LinkStateNone +// +func NewLinkStateNone() *LinkStateNone { + linkStateNoneTemp := LinkStateNone{ + tdCommon: tdCommon{Type: "linkStateNone"}, + } + + return &linkStateNoneTemp +} + +// GetLinkStateEnum return the enum type of this object +func (linkStateNone *LinkStateNone) GetLinkStateEnum() LinkStateEnum { + return LinkStateNoneType +} + +// LinkStateKnowsPhoneNumber The phone number of user A is known but that number has not been saved to the contacts list of user B +type LinkStateKnowsPhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of LinkStateKnowsPhoneNumber +func (linkStateKnowsPhoneNumber *LinkStateKnowsPhoneNumber) MessageType() string { + return "linkStateKnowsPhoneNumber" +} + +// NewLinkStateKnowsPhoneNumber creates a new LinkStateKnowsPhoneNumber +// +func NewLinkStateKnowsPhoneNumber() *LinkStateKnowsPhoneNumber { + linkStateKnowsPhoneNumberTemp := LinkStateKnowsPhoneNumber{ + tdCommon: tdCommon{Type: "linkStateKnowsPhoneNumber"}, + } + + return &linkStateKnowsPhoneNumberTemp +} + +// GetLinkStateEnum return the enum type of this object +func (linkStateKnowsPhoneNumber *LinkStateKnowsPhoneNumber) GetLinkStateEnum() LinkStateEnum { + return LinkStateKnowsPhoneNumberType +} + +// LinkStateIsContact The phone number of user A has been saved to the contacts list of user B +type LinkStateIsContact struct { + tdCommon +} + +// MessageType return the string telegram-type of LinkStateIsContact +func (linkStateIsContact *LinkStateIsContact) MessageType() string { + return "linkStateIsContact" +} + +// NewLinkStateIsContact creates a new LinkStateIsContact +// +func NewLinkStateIsContact() *LinkStateIsContact { + linkStateIsContactTemp := LinkStateIsContact{ + tdCommon: tdCommon{Type: "linkStateIsContact"}, + } + + return &linkStateIsContactTemp +} + +// GetLinkStateEnum return the enum type of this object +func (linkStateIsContact *LinkStateIsContact) GetLinkStateEnum() LinkStateEnum { + return LinkStateIsContactType +} + +// UserTypeRegular A regular user +type UserTypeRegular struct { + tdCommon +} + +// MessageType return the string telegram-type of UserTypeRegular +func (userTypeRegular *UserTypeRegular) MessageType() string { + return "userTypeRegular" +} + +// NewUserTypeRegular creates a new UserTypeRegular +// +func NewUserTypeRegular() *UserTypeRegular { + userTypeRegularTemp := UserTypeRegular{ + tdCommon: tdCommon{Type: "userTypeRegular"}, + } + + return &userTypeRegularTemp +} + +// GetUserTypeEnum return the enum type of this object +func (userTypeRegular *UserTypeRegular) GetUserTypeEnum() UserTypeEnum { + return UserTypeRegularType +} + +// UserTypeDeleted A deleted user or deleted bot. No information on the user besides the user_id is available. It is not possible to perform any active actions on this type of user +type UserTypeDeleted struct { + tdCommon +} + +// MessageType return the string telegram-type of UserTypeDeleted +func (userTypeDeleted *UserTypeDeleted) MessageType() string { + return "userTypeDeleted" +} + +// NewUserTypeDeleted creates a new UserTypeDeleted +// +func NewUserTypeDeleted() *UserTypeDeleted { + userTypeDeletedTemp := UserTypeDeleted{ + tdCommon: tdCommon{Type: "userTypeDeleted"}, + } + + return &userTypeDeletedTemp +} + +// GetUserTypeEnum return the enum type of this object +func (userTypeDeleted *UserTypeDeleted) GetUserTypeEnum() UserTypeEnum { + return UserTypeDeletedType +} + +// UserTypeBot A bot (see https://core.telegram.org/bots) +type UserTypeBot struct { + tdCommon + CanJoinGroups bool `json:"can_join_groups"` // True, if the bot can be invited to basic group and supergroup chats + CanReadAllGroupMessages bool `json:"can_read_all_group_messages"` // True, if the bot can read all messages in basic group or supergroup chats and not just those addressed to the bot. In private and channel chats a bot can always read all messages + IsInline bool `json:"is_inline"` // True, if the bot supports inline queries + InlineQueryPlaceholder string `json:"inline_query_placeholder"` // Placeholder for inline queries (displayed on the client input field) + NeedLocation bool `json:"need_location"` // True, if the location of the user should be sent with every inline query to this bot +} + +// MessageType return the string telegram-type of UserTypeBot +func (userTypeBot *UserTypeBot) MessageType() string { + return "userTypeBot" +} + +// NewUserTypeBot creates a new UserTypeBot +// +// @param canJoinGroups True, if the bot can be invited to basic group and supergroup chats +// @param canReadAllGroupMessages True, if the bot can read all messages in basic group or supergroup chats and not just those addressed to the bot. In private and channel chats a bot can always read all messages +// @param isInline True, if the bot supports inline queries +// @param inlineQueryPlaceholder Placeholder for inline queries (displayed on the client input field) +// @param needLocation True, if the location of the user should be sent with every inline query to this bot +func NewUserTypeBot(canJoinGroups bool, canReadAllGroupMessages bool, isInline bool, inlineQueryPlaceholder string, needLocation bool) *UserTypeBot { + userTypeBotTemp := UserTypeBot{ + tdCommon: tdCommon{Type: "userTypeBot"}, + CanJoinGroups: canJoinGroups, + CanReadAllGroupMessages: canReadAllGroupMessages, + IsInline: isInline, + InlineQueryPlaceholder: inlineQueryPlaceholder, + NeedLocation: needLocation, + } + + return &userTypeBotTemp +} + +// GetUserTypeEnum return the enum type of this object +func (userTypeBot *UserTypeBot) GetUserTypeEnum() UserTypeEnum { + return UserTypeBotType +} + +// UserTypeUnknown No information on the user besides the user_id is available, yet this user has not been deleted. This object is extremely rare and must be handled like a deleted user. It is not possible to perform any actions on users of this type +type UserTypeUnknown struct { + tdCommon +} + +// MessageType return the string telegram-type of UserTypeUnknown +func (userTypeUnknown *UserTypeUnknown) MessageType() string { + return "userTypeUnknown" +} + +// NewUserTypeUnknown creates a new UserTypeUnknown +// +func NewUserTypeUnknown() *UserTypeUnknown { + userTypeUnknownTemp := UserTypeUnknown{ + tdCommon: tdCommon{Type: "userTypeUnknown"}, + } + + return &userTypeUnknownTemp +} + +// GetUserTypeEnum return the enum type of this object +func (userTypeUnknown *UserTypeUnknown) GetUserTypeEnum() UserTypeEnum { + return UserTypeUnknownType +} + +// BotCommand Represents commands supported by a bot +type BotCommand struct { + tdCommon + Command string `json:"command"` // Text of the bot command + Description string `json:"description"` // +} + +// MessageType return the string telegram-type of BotCommand +func (botCommand *BotCommand) MessageType() string { + return "botCommand" +} + +// NewBotCommand creates a new BotCommand +// +// @param command Text of the bot command +// @param description +func NewBotCommand(command string, description string) *BotCommand { + botCommandTemp := BotCommand{ + tdCommon: tdCommon{Type: "botCommand"}, + Command: command, + Description: description, + } + + return &botCommandTemp +} + +// BotInfo Provides information about a bot and its supported commands +type BotInfo struct { + tdCommon + Description string `json:"description"` // + Commands []BotCommand `json:"commands"` // A list of commands supported by the bot +} + +// MessageType return the string telegram-type of BotInfo +func (botInfo *BotInfo) MessageType() string { + return "botInfo" +} + +// NewBotInfo creates a new BotInfo +// +// @param description +// @param commands A list of commands supported by the bot +func NewBotInfo(description string, commands []BotCommand) *BotInfo { + botInfoTemp := BotInfo{ + tdCommon: tdCommon{Type: "botInfo"}, + Description: description, + Commands: commands, + } + + return &botInfoTemp +} + +// User Represents a user +type User struct { + tdCommon + ID int32 `json:"id"` // User identifier + FirstName string `json:"first_name"` // First name of the user + LastName string `json:"last_name"` // Last name of the user + Username string `json:"username"` // Username of the user + PhoneNumber string `json:"phone_number"` // Phone number of the user + Status UserStatus `json:"status"` // Current online status of the user + ProfilePhoto *ProfilePhoto `json:"profile_photo"` // Profile photo of the user; may be null + OutgoingLink LinkState `json:"outgoing_link"` // Relationship from the current user to the other user + IncomingLink LinkState `json:"incoming_link"` // Relationship from the other user to the current user + IsVerified bool `json:"is_verified"` // True, if the user is verified + RestrictionReason string `json:"restriction_reason"` // If non-empty, it contains the reason why access to this user must be restricted. The format of the string is "{type}: {description}". + HaveAccess bool `json:"have_access"` // If false, the user is inaccessible, and the only information known about the user is inside this class. It can't be passed to any method except GetUser + Type UserType `json:"type"` // Type of the user + LanguageCode string `json:"language_code"` // IETF language tag of the user's language; only available to bots +} + +// MessageType return the string telegram-type of User +func (user *User) MessageType() string { + return "user" +} + +// NewUser creates a new User +// +// @param iD User identifier +// @param firstName First name of the user +// @param lastName Last name of the user +// @param username Username of the user +// @param phoneNumber Phone number of the user +// @param status Current online status of the user +// @param profilePhoto Profile photo of the user; may be null +// @param outgoingLink Relationship from the current user to the other user +// @param incomingLink Relationship from the other user to the current user +// @param isVerified True, if the user is verified +// @param restrictionReason If non-empty, it contains the reason why access to this user must be restricted. The format of the string is "{type}: {description}". +// @param haveAccess If false, the user is inaccessible, and the only information known about the user is inside this class. It can't be passed to any method except GetUser +// @param typeParam Type of the user +// @param languageCode IETF language tag of the user's language; only available to bots +func NewUser(iD int32, firstName string, lastName string, username string, phoneNumber string, status UserStatus, profilePhoto *ProfilePhoto, outgoingLink LinkState, incomingLink LinkState, isVerified bool, restrictionReason string, haveAccess bool, typeParam UserType, languageCode string) *User { + userTemp := User{ + tdCommon: tdCommon{Type: "user"}, + ID: iD, + FirstName: firstName, + LastName: lastName, + Username: username, + PhoneNumber: phoneNumber, + Status: status, + ProfilePhoto: profilePhoto, + OutgoingLink: outgoingLink, + IncomingLink: incomingLink, + IsVerified: isVerified, + RestrictionReason: restrictionReason, + HaveAccess: haveAccess, + Type: typeParam, + LanguageCode: languageCode, + } + + return &userTemp +} + +// UnmarshalJSON unmarshal to json +func (user *User) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int32 `json:"id"` // User identifier + FirstName string `json:"first_name"` // First name of the user + LastName string `json:"last_name"` // Last name of the user + Username string `json:"username"` // Username of the user + PhoneNumber string `json:"phone_number"` // Phone number of the user + ProfilePhoto *ProfilePhoto `json:"profile_photo"` // Profile photo of the user; may be null + IsVerified bool `json:"is_verified"` // True, if the user is verified + RestrictionReason string `json:"restriction_reason"` // If non-empty, it contains the reason why access to this user must be restricted. The format of the string is "{type}: {description}". + HaveAccess bool `json:"have_access"` // If false, the user is inaccessible, and the only information known about the user is inside this class. It can't be passed to any method except GetUser + LanguageCode string `json:"language_code"` // IETF language tag of the user's language; only available to bots + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + user.tdCommon = tempObj.tdCommon + user.ID = tempObj.ID + user.FirstName = tempObj.FirstName + user.LastName = tempObj.LastName + user.Username = tempObj.Username + user.PhoneNumber = tempObj.PhoneNumber + user.ProfilePhoto = tempObj.ProfilePhoto + user.IsVerified = tempObj.IsVerified + user.RestrictionReason = tempObj.RestrictionReason + user.HaveAccess = tempObj.HaveAccess + user.LanguageCode = tempObj.LanguageCode + + fieldStatus, _ := unmarshalUserStatus(objMap["status"]) + user.Status = fieldStatus + + fieldOutgoingLink, _ := unmarshalLinkState(objMap["outgoing_link"]) + user.OutgoingLink = fieldOutgoingLink + + fieldIncomingLink, _ := unmarshalLinkState(objMap["incoming_link"]) + user.IncomingLink = fieldIncomingLink + + fieldType, _ := unmarshalUserType(objMap["type"]) + user.Type = fieldType + + return nil +} + +// UserFullInfo Contains full information about a user (except the full list of profile photos) +type UserFullInfo struct { + tdCommon + IsBlocked bool `json:"is_blocked"` // True, if the user is blacklisted by the current user + CanBeCalled bool `json:"can_be_called"` // True, if the user can be called + HasPrivateCalls bool `json:"has_private_calls"` // True, if the user can't be called due to their privacy settings + Bio string `json:"bio"` // A short user bio + ShareText string `json:"share_text"` // For bots, the text that is included with the link when users share the bot + GroupInCommonCount int32 `json:"group_in_common_count"` // Number of group chats where both the other user and the current user are a member; 0 for the current user + BotInfo *BotInfo `json:"bot_info"` // If the user is a bot, information about the bot; may be null +} + +// MessageType return the string telegram-type of UserFullInfo +func (userFullInfo *UserFullInfo) MessageType() string { + return "userFullInfo" +} + +// NewUserFullInfo creates a new UserFullInfo +// +// @param isBlocked True, if the user is blacklisted by the current user +// @param canBeCalled True, if the user can be called +// @param hasPrivateCalls True, if the user can't be called due to their privacy settings +// @param bio A short user bio +// @param shareText For bots, the text that is included with the link when users share the bot +// @param groupInCommonCount Number of group chats where both the other user and the current user are a member; 0 for the current user +// @param botInfo If the user is a bot, information about the bot; may be null +func NewUserFullInfo(isBlocked bool, canBeCalled bool, hasPrivateCalls bool, bio string, shareText string, groupInCommonCount int32, botInfo *BotInfo) *UserFullInfo { + userFullInfoTemp := UserFullInfo{ + tdCommon: tdCommon{Type: "userFullInfo"}, + IsBlocked: isBlocked, + CanBeCalled: canBeCalled, + HasPrivateCalls: hasPrivateCalls, + Bio: bio, + ShareText: shareText, + GroupInCommonCount: groupInCommonCount, + BotInfo: botInfo, + } + + return &userFullInfoTemp +} + +// UserProfilePhotos Contains part of the list of user photos +type UserProfilePhotos struct { + tdCommon + TotalCount int32 `json:"total_count"` // Total number of user profile photos + Photos []Photo `json:"photos"` // A list of photos +} + +// MessageType return the string telegram-type of UserProfilePhotos +func (userProfilePhotos *UserProfilePhotos) MessageType() string { + return "userProfilePhotos" +} + +// NewUserProfilePhotos creates a new UserProfilePhotos +// +// @param totalCount Total number of user profile photos +// @param photos A list of photos +func NewUserProfilePhotos(totalCount int32, photos []Photo) *UserProfilePhotos { + userProfilePhotosTemp := UserProfilePhotos{ + tdCommon: tdCommon{Type: "userProfilePhotos"}, + TotalCount: totalCount, + Photos: photos, + } + + return &userProfilePhotosTemp +} + +// Users Represents a list of users +type Users struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of users found + UserIDs []int32 `json:"user_ids"` // A list of user identifiers +} + +// MessageType return the string telegram-type of Users +func (users *Users) MessageType() string { + return "users" +} + +// NewUsers creates a new Users +// +// @param totalCount Approximate total count of users found +// @param userIDs A list of user identifiers +func NewUsers(totalCount int32, userIDs []int32) *Users { + usersTemp := Users{ + tdCommon: tdCommon{Type: "users"}, + TotalCount: totalCount, + UserIDs: userIDs, + } + + return &usersTemp +} + +// ChatMemberStatusCreator The user is the creator of a chat and has all the administrator privileges +type ChatMemberStatusCreator struct { + tdCommon + IsMember bool `json:"is_member"` // True, if the user is a member of the chat +} + +// MessageType return the string telegram-type of ChatMemberStatusCreator +func (chatMemberStatusCreator *ChatMemberStatusCreator) MessageType() string { + return "chatMemberStatusCreator" +} + +// NewChatMemberStatusCreator creates a new ChatMemberStatusCreator +// +// @param isMember True, if the user is a member of the chat +func NewChatMemberStatusCreator(isMember bool) *ChatMemberStatusCreator { + chatMemberStatusCreatorTemp := ChatMemberStatusCreator{ + tdCommon: tdCommon{Type: "chatMemberStatusCreator"}, + IsMember: isMember, + } + + return &chatMemberStatusCreatorTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusCreator *ChatMemberStatusCreator) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusCreatorType +} + +// ChatMemberStatusAdministrator The user is a member of a chat and has some additional privileges. In basic groups, administrators can edit and delete messages sent by others, add new members, and ban unprivileged members. In supergroups and channels, there are more detailed options for administrator privileges +type ChatMemberStatusAdministrator struct { + tdCommon + CanBeEdited bool `json:"can_be_edited"` // True, if the current user can edit the administrator privileges for the called user + CanChangeInfo bool `json:"can_change_info"` // True, if the administrator can change the chat title, photo, and other settings + CanPostMessages bool `json:"can_post_messages"` // True, if the administrator can create channel posts; applicable to channels only + CanEditMessages bool `json:"can_edit_messages"` // True, if the administrator can edit messages of other users and pin messages; applicable to channels only + CanDeleteMessages bool `json:"can_delete_messages"` // True, if the administrator can delete messages of other users + CanInviteUsers bool `json:"can_invite_users"` // True, if the administrator can invite new users to the chat + CanRestrictMembers bool `json:"can_restrict_members"` // True, if the administrator can restrict, ban, or unban chat members + CanPinMessages bool `json:"can_pin_messages"` // True, if the administrator can pin messages; applicable to supergroups only + CanPromoteMembers bool `json:"can_promote_members"` // True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that were directly or indirectly promoted by him +} + +// MessageType return the string telegram-type of ChatMemberStatusAdministrator +func (chatMemberStatusAdministrator *ChatMemberStatusAdministrator) MessageType() string { + return "chatMemberStatusAdministrator" +} + +// NewChatMemberStatusAdministrator creates a new ChatMemberStatusAdministrator +// +// @param canBeEdited True, if the current user can edit the administrator privileges for the called user +// @param canChangeInfo True, if the administrator can change the chat title, photo, and other settings +// @param canPostMessages True, if the administrator can create channel posts; applicable to channels only +// @param canEditMessages True, if the administrator can edit messages of other users and pin messages; applicable to channels only +// @param canDeleteMessages True, if the administrator can delete messages of other users +// @param canInviteUsers True, if the administrator can invite new users to the chat +// @param canRestrictMembers True, if the administrator can restrict, ban, or unban chat members +// @param canPinMessages True, if the administrator can pin messages; applicable to supergroups only +// @param canPromoteMembers True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that were directly or indirectly promoted by him +func NewChatMemberStatusAdministrator(canBeEdited bool, canChangeInfo bool, canPostMessages bool, canEditMessages bool, canDeleteMessages bool, canInviteUsers bool, canRestrictMembers bool, canPinMessages bool, canPromoteMembers bool) *ChatMemberStatusAdministrator { + chatMemberStatusAdministratorTemp := ChatMemberStatusAdministrator{ + tdCommon: tdCommon{Type: "chatMemberStatusAdministrator"}, + CanBeEdited: canBeEdited, + CanChangeInfo: canChangeInfo, + CanPostMessages: canPostMessages, + CanEditMessages: canEditMessages, + CanDeleteMessages: canDeleteMessages, + CanInviteUsers: canInviteUsers, + CanRestrictMembers: canRestrictMembers, + CanPinMessages: canPinMessages, + CanPromoteMembers: canPromoteMembers, + } + + return &chatMemberStatusAdministratorTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusAdministrator *ChatMemberStatusAdministrator) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusAdministratorType +} + +// ChatMemberStatusMember The user is a member of a chat, without any additional privileges or restrictions +type ChatMemberStatusMember struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMemberStatusMember +func (chatMemberStatusMember *ChatMemberStatusMember) MessageType() string { + return "chatMemberStatusMember" +} + +// NewChatMemberStatusMember creates a new ChatMemberStatusMember +// +func NewChatMemberStatusMember() *ChatMemberStatusMember { + chatMemberStatusMemberTemp := ChatMemberStatusMember{ + tdCommon: tdCommon{Type: "chatMemberStatusMember"}, + } + + return &chatMemberStatusMemberTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusMember *ChatMemberStatusMember) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusMemberType +} + +// ChatMemberStatusRestricted The user is under certain restrictions in the chat. Not supported in basic groups and channels +type ChatMemberStatusRestricted struct { + tdCommon + IsMember bool `json:"is_member"` // True, if the user is a member of the chat + RestrictedUntilDate int32 `json:"restricted_until_date"` // Point in time (Unix timestamp) when restrictions will be lifted from the user; 0 if never. If the user is restricted for more than 366 days or for less than 30 seconds from the current time, the user is considered to be restricted forever + CanSendMessages bool `json:"can_send_messages"` // True, if the user can send text messages, contacts, locations, and venues + CanSendMediaMessages bool `json:"can_send_media_messages"` // True, if the user can send audio files, documents, photos, videos, video notes, and voice notes. Implies can_send_messages permissions + CanSendOtherMessages bool `json:"can_send_other_messages"` // True, if the user can send animations, games, and stickers and use inline bots. Implies can_send_media_messages permissions + CanAddWebPagePreviews bool `json:"can_add_web_page_previews"` // True, if the user may add a web page preview to his messages. Implies can_send_messages permissions +} + +// MessageType return the string telegram-type of ChatMemberStatusRestricted +func (chatMemberStatusRestricted *ChatMemberStatusRestricted) MessageType() string { + return "chatMemberStatusRestricted" +} + +// NewChatMemberStatusRestricted creates a new ChatMemberStatusRestricted +// +// @param isMember True, if the user is a member of the chat +// @param restrictedUntilDate Point in time (Unix timestamp) when restrictions will be lifted from the user; 0 if never. If the user is restricted for more than 366 days or for less than 30 seconds from the current time, the user is considered to be restricted forever +// @param canSendMessages True, if the user can send text messages, contacts, locations, and venues +// @param canSendMediaMessages True, if the user can send audio files, documents, photos, videos, video notes, and voice notes. Implies can_send_messages permissions +// @param canSendOtherMessages True, if the user can send animations, games, and stickers and use inline bots. Implies can_send_media_messages permissions +// @param canAddWebPagePreviews True, if the user may add a web page preview to his messages. Implies can_send_messages permissions +func NewChatMemberStatusRestricted(isMember bool, restrictedUntilDate int32, canSendMessages bool, canSendMediaMessages bool, canSendOtherMessages bool, canAddWebPagePreviews bool) *ChatMemberStatusRestricted { + chatMemberStatusRestrictedTemp := ChatMemberStatusRestricted{ + tdCommon: tdCommon{Type: "chatMemberStatusRestricted"}, + IsMember: isMember, + RestrictedUntilDate: restrictedUntilDate, + CanSendMessages: canSendMessages, + CanSendMediaMessages: canSendMediaMessages, + CanSendOtherMessages: canSendOtherMessages, + CanAddWebPagePreviews: canAddWebPagePreviews, + } + + return &chatMemberStatusRestrictedTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusRestricted *ChatMemberStatusRestricted) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusRestrictedType +} + +// ChatMemberStatusLeft The user is not a chat member +type ChatMemberStatusLeft struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMemberStatusLeft +func (chatMemberStatusLeft *ChatMemberStatusLeft) MessageType() string { + return "chatMemberStatusLeft" +} + +// NewChatMemberStatusLeft creates a new ChatMemberStatusLeft +// +func NewChatMemberStatusLeft() *ChatMemberStatusLeft { + chatMemberStatusLeftTemp := ChatMemberStatusLeft{ + tdCommon: tdCommon{Type: "chatMemberStatusLeft"}, + } + + return &chatMemberStatusLeftTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusLeft *ChatMemberStatusLeft) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusLeftType +} + +// ChatMemberStatusBanned The user was banned (and hence is not a member of the chat). Implies the user can't return to the chat or view messages +type ChatMemberStatusBanned struct { + tdCommon + BannedUntilDate int32 `json:"banned_until_date"` // Point in time (Unix timestamp) when the user will be unbanned; 0 if never. If the user is banned for more than 366 days or for less than 30 seconds from the current time, the user is considered to be banned forever +} + +// MessageType return the string telegram-type of ChatMemberStatusBanned +func (chatMemberStatusBanned *ChatMemberStatusBanned) MessageType() string { + return "chatMemberStatusBanned" +} + +// NewChatMemberStatusBanned creates a new ChatMemberStatusBanned +// +// @param bannedUntilDate Point in time (Unix timestamp) when the user will be unbanned; 0 if never. If the user is banned for more than 366 days or for less than 30 seconds from the current time, the user is considered to be banned forever +func NewChatMemberStatusBanned(bannedUntilDate int32) *ChatMemberStatusBanned { + chatMemberStatusBannedTemp := ChatMemberStatusBanned{ + tdCommon: tdCommon{Type: "chatMemberStatusBanned"}, + BannedUntilDate: bannedUntilDate, + } + + return &chatMemberStatusBannedTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusBanned *ChatMemberStatusBanned) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusBannedType +} + +// ChatMember A user with information about joining/leaving a chat +type ChatMember struct { + tdCommon + UserID int32 `json:"user_id"` // User identifier of the chat member + InviterUserID int32 `json:"inviter_user_id"` // Identifier of a user that invited/promoted/banned this member in the chat; 0 if unknown + JoinedChatDate int32 `json:"joined_chat_date"` // Point in time (Unix timestamp) when the user joined a chat + Status ChatMemberStatus `json:"status"` // Status of the member in the chat + BotInfo *BotInfo `json:"bot_info"` // If the user is a bot, information about the bot; may be null. Can be null even for a bot if the bot is not a chat member +} + +// MessageType return the string telegram-type of ChatMember +func (chatMember *ChatMember) MessageType() string { + return "chatMember" +} + +// NewChatMember creates a new ChatMember +// +// @param userID User identifier of the chat member +// @param inviterUserID Identifier of a user that invited/promoted/banned this member in the chat; 0 if unknown +// @param joinedChatDate Point in time (Unix timestamp) when the user joined a chat +// @param status Status of the member in the chat +// @param botInfo If the user is a bot, information about the bot; may be null. Can be null even for a bot if the bot is not a chat member +func NewChatMember(userID int32, inviterUserID int32, joinedChatDate int32, status ChatMemberStatus, botInfo *BotInfo) *ChatMember { + chatMemberTemp := ChatMember{ + tdCommon: tdCommon{Type: "chatMember"}, + UserID: userID, + InviterUserID: inviterUserID, + JoinedChatDate: joinedChatDate, + Status: status, + BotInfo: botInfo, + } + + return &chatMemberTemp +} + +// UnmarshalJSON unmarshal to json +func (chatMember *ChatMember) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + UserID int32 `json:"user_id"` // User identifier of the chat member + InviterUserID int32 `json:"inviter_user_id"` // Identifier of a user that invited/promoted/banned this member in the chat; 0 if unknown + JoinedChatDate int32 `json:"joined_chat_date"` // Point in time (Unix timestamp) when the user joined a chat + BotInfo *BotInfo `json:"bot_info"` // If the user is a bot, information about the bot; may be null. Can be null even for a bot if the bot is not a chat member + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatMember.tdCommon = tempObj.tdCommon + chatMember.UserID = tempObj.UserID + chatMember.InviterUserID = tempObj.InviterUserID + chatMember.JoinedChatDate = tempObj.JoinedChatDate + chatMember.BotInfo = tempObj.BotInfo + + fieldStatus, _ := unmarshalChatMemberStatus(objMap["status"]) + chatMember.Status = fieldStatus + + return nil +} + +// ChatMembers Contains a list of chat members +type ChatMembers struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of chat members found + Members []ChatMember `json:"members"` // A list of chat members +} + +// MessageType return the string telegram-type of ChatMembers +func (chatMembers *ChatMembers) MessageType() string { + return "chatMembers" +} + +// NewChatMembers creates a new ChatMembers +// +// @param totalCount Approximate total count of chat members found +// @param members A list of chat members +func NewChatMembers(totalCount int32, members []ChatMember) *ChatMembers { + chatMembersTemp := ChatMembers{ + tdCommon: tdCommon{Type: "chatMembers"}, + TotalCount: totalCount, + Members: members, + } + + return &chatMembersTemp +} + +// ChatMembersFilterAdministrators Returns the creator and administrators +type ChatMembersFilterAdministrators struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMembersFilterAdministrators +func (chatMembersFilterAdministrators *ChatMembersFilterAdministrators) MessageType() string { + return "chatMembersFilterAdministrators" +} + +// NewChatMembersFilterAdministrators creates a new ChatMembersFilterAdministrators +// +func NewChatMembersFilterAdministrators() *ChatMembersFilterAdministrators { + chatMembersFilterAdministratorsTemp := ChatMembersFilterAdministrators{ + tdCommon: tdCommon{Type: "chatMembersFilterAdministrators"}, + } + + return &chatMembersFilterAdministratorsTemp +} + +// GetChatMembersFilterEnum return the enum type of this object +func (chatMembersFilterAdministrators *ChatMembersFilterAdministrators) GetChatMembersFilterEnum() ChatMembersFilterEnum { + return ChatMembersFilterAdministratorsType +} + +// ChatMembersFilterMembers Returns all chat members, including restricted chat members +type ChatMembersFilterMembers struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMembersFilterMembers +func (chatMembersFilterMembers *ChatMembersFilterMembers) MessageType() string { + return "chatMembersFilterMembers" +} + +// NewChatMembersFilterMembers creates a new ChatMembersFilterMembers +// +func NewChatMembersFilterMembers() *ChatMembersFilterMembers { + chatMembersFilterMembersTemp := ChatMembersFilterMembers{ + tdCommon: tdCommon{Type: "chatMembersFilterMembers"}, + } + + return &chatMembersFilterMembersTemp +} + +// GetChatMembersFilterEnum return the enum type of this object +func (chatMembersFilterMembers *ChatMembersFilterMembers) GetChatMembersFilterEnum() ChatMembersFilterEnum { + return ChatMembersFilterMembersType +} + +// ChatMembersFilterRestricted Returns users under certain restrictions in the chat; can be used only by administrators in a supergroup +type ChatMembersFilterRestricted struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMembersFilterRestricted +func (chatMembersFilterRestricted *ChatMembersFilterRestricted) MessageType() string { + return "chatMembersFilterRestricted" +} + +// NewChatMembersFilterRestricted creates a new ChatMembersFilterRestricted +// +func NewChatMembersFilterRestricted() *ChatMembersFilterRestricted { + chatMembersFilterRestrictedTemp := ChatMembersFilterRestricted{ + tdCommon: tdCommon{Type: "chatMembersFilterRestricted"}, + } + + return &chatMembersFilterRestrictedTemp +} + +// GetChatMembersFilterEnum return the enum type of this object +func (chatMembersFilterRestricted *ChatMembersFilterRestricted) GetChatMembersFilterEnum() ChatMembersFilterEnum { + return ChatMembersFilterRestrictedType +} + +// ChatMembersFilterBanned Returns users banned from the chat; can be used only by administrators in a supergroup or in a channel +type ChatMembersFilterBanned struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMembersFilterBanned +func (chatMembersFilterBanned *ChatMembersFilterBanned) MessageType() string { + return "chatMembersFilterBanned" +} + +// NewChatMembersFilterBanned creates a new ChatMembersFilterBanned +// +func NewChatMembersFilterBanned() *ChatMembersFilterBanned { + chatMembersFilterBannedTemp := ChatMembersFilterBanned{ + tdCommon: tdCommon{Type: "chatMembersFilterBanned"}, + } + + return &chatMembersFilterBannedTemp +} + +// GetChatMembersFilterEnum return the enum type of this object +func (chatMembersFilterBanned *ChatMembersFilterBanned) GetChatMembersFilterEnum() ChatMembersFilterEnum { + return ChatMembersFilterBannedType +} + +// ChatMembersFilterBots Returns bot members of the chat +type ChatMembersFilterBots struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMembersFilterBots +func (chatMembersFilterBots *ChatMembersFilterBots) MessageType() string { + return "chatMembersFilterBots" +} + +// NewChatMembersFilterBots creates a new ChatMembersFilterBots +// +func NewChatMembersFilterBots() *ChatMembersFilterBots { + chatMembersFilterBotsTemp := ChatMembersFilterBots{ + tdCommon: tdCommon{Type: "chatMembersFilterBots"}, + } + + return &chatMembersFilterBotsTemp +} + +// GetChatMembersFilterEnum return the enum type of this object +func (chatMembersFilterBots *ChatMembersFilterBots) GetChatMembersFilterEnum() ChatMembersFilterEnum { + return ChatMembersFilterBotsType +} + +// SupergroupMembersFilterRecent Returns recently active users in reverse chronological order +type SupergroupMembersFilterRecent struct { + tdCommon +} + +// MessageType return the string telegram-type of SupergroupMembersFilterRecent +func (supergroupMembersFilterRecent *SupergroupMembersFilterRecent) MessageType() string { + return "supergroupMembersFilterRecent" +} + +// NewSupergroupMembersFilterRecent creates a new SupergroupMembersFilterRecent +// +func NewSupergroupMembersFilterRecent() *SupergroupMembersFilterRecent { + supergroupMembersFilterRecentTemp := SupergroupMembersFilterRecent{ + tdCommon: tdCommon{Type: "supergroupMembersFilterRecent"}, + } + + return &supergroupMembersFilterRecentTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterRecent *SupergroupMembersFilterRecent) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterRecentType +} + +// SupergroupMembersFilterAdministrators Returns the creator and administrators +type SupergroupMembersFilterAdministrators struct { + tdCommon +} + +// MessageType return the string telegram-type of SupergroupMembersFilterAdministrators +func (supergroupMembersFilterAdministrators *SupergroupMembersFilterAdministrators) MessageType() string { + return "supergroupMembersFilterAdministrators" +} + +// NewSupergroupMembersFilterAdministrators creates a new SupergroupMembersFilterAdministrators +// +func NewSupergroupMembersFilterAdministrators() *SupergroupMembersFilterAdministrators { + supergroupMembersFilterAdministratorsTemp := SupergroupMembersFilterAdministrators{ + tdCommon: tdCommon{Type: "supergroupMembersFilterAdministrators"}, + } + + return &supergroupMembersFilterAdministratorsTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterAdministrators *SupergroupMembersFilterAdministrators) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterAdministratorsType +} + +// SupergroupMembersFilterSearch Used to search for supergroup or channel members via a (string) query +type SupergroupMembersFilterSearch struct { + tdCommon + Query string `json:"query"` // Query to search for +} + +// MessageType return the string telegram-type of SupergroupMembersFilterSearch +func (supergroupMembersFilterSearch *SupergroupMembersFilterSearch) MessageType() string { + return "supergroupMembersFilterSearch" +} + +// NewSupergroupMembersFilterSearch creates a new SupergroupMembersFilterSearch +// +// @param query Query to search for +func NewSupergroupMembersFilterSearch(query string) *SupergroupMembersFilterSearch { + supergroupMembersFilterSearchTemp := SupergroupMembersFilterSearch{ + tdCommon: tdCommon{Type: "supergroupMembersFilterSearch"}, + Query: query, + } + + return &supergroupMembersFilterSearchTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterSearch *SupergroupMembersFilterSearch) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterSearchType +} + +// SupergroupMembersFilterRestricted Returns restricted supergroup members; can be used only by administrators +type SupergroupMembersFilterRestricted struct { + tdCommon + Query string `json:"query"` // Query to search for +} + +// MessageType return the string telegram-type of SupergroupMembersFilterRestricted +func (supergroupMembersFilterRestricted *SupergroupMembersFilterRestricted) MessageType() string { + return "supergroupMembersFilterRestricted" +} + +// NewSupergroupMembersFilterRestricted creates a new SupergroupMembersFilterRestricted +// +// @param query Query to search for +func NewSupergroupMembersFilterRestricted(query string) *SupergroupMembersFilterRestricted { + supergroupMembersFilterRestrictedTemp := SupergroupMembersFilterRestricted{ + tdCommon: tdCommon{Type: "supergroupMembersFilterRestricted"}, + Query: query, + } + + return &supergroupMembersFilterRestrictedTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterRestricted *SupergroupMembersFilterRestricted) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterRestrictedType +} + +// SupergroupMembersFilterBanned Returns users banned from the supergroup or channel; can be used only by administrators +type SupergroupMembersFilterBanned struct { + tdCommon + Query string `json:"query"` // Query to search for +} + +// MessageType return the string telegram-type of SupergroupMembersFilterBanned +func (supergroupMembersFilterBanned *SupergroupMembersFilterBanned) MessageType() string { + return "supergroupMembersFilterBanned" +} + +// NewSupergroupMembersFilterBanned creates a new SupergroupMembersFilterBanned +// +// @param query Query to search for +func NewSupergroupMembersFilterBanned(query string) *SupergroupMembersFilterBanned { + supergroupMembersFilterBannedTemp := SupergroupMembersFilterBanned{ + tdCommon: tdCommon{Type: "supergroupMembersFilterBanned"}, + Query: query, + } + + return &supergroupMembersFilterBannedTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterBanned *SupergroupMembersFilterBanned) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterBannedType +} + +// SupergroupMembersFilterBots Returns bot members of the supergroup or channel +type SupergroupMembersFilterBots struct { + tdCommon +} + +// MessageType return the string telegram-type of SupergroupMembersFilterBots +func (supergroupMembersFilterBots *SupergroupMembersFilterBots) MessageType() string { + return "supergroupMembersFilterBots" +} + +// NewSupergroupMembersFilterBots creates a new SupergroupMembersFilterBots +// +func NewSupergroupMembersFilterBots() *SupergroupMembersFilterBots { + supergroupMembersFilterBotsTemp := SupergroupMembersFilterBots{ + tdCommon: tdCommon{Type: "supergroupMembersFilterBots"}, + } + + return &supergroupMembersFilterBotsTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterBots *SupergroupMembersFilterBots) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterBotsType +} + +// BasicGroup Represents a basic group of 0-200 users (must be upgraded to a supergroup to accommodate more than 200 users) +type BasicGroup struct { + tdCommon + ID int32 `json:"id"` // Group identifier + MemberCount int32 `json:"member_count"` // Number of members in the group + Status ChatMemberStatus `json:"status"` // Status of the current user in the group + EveryoneIsAdministrator bool `json:"everyone_is_administrator"` // True, if all members have been granted administrator rights in the group + IsActive bool `json:"is_active"` // True, if the group is active + UpgradedToSupergroupID int32 `json:"upgraded_to_supergroup_id"` // Identifier of the supergroup to which this group was upgraded; 0 if none +} + +// MessageType return the string telegram-type of BasicGroup +func (basicGroup *BasicGroup) MessageType() string { + return "basicGroup" +} + +// NewBasicGroup creates a new BasicGroup +// +// @param iD Group identifier +// @param memberCount Number of members in the group +// @param status Status of the current user in the group +// @param everyoneIsAdministrator True, if all members have been granted administrator rights in the group +// @param isActive True, if the group is active +// @param upgradedToSupergroupID Identifier of the supergroup to which this group was upgraded; 0 if none +func NewBasicGroup(iD int32, memberCount int32, status ChatMemberStatus, everyoneIsAdministrator bool, isActive bool, upgradedToSupergroupID int32) *BasicGroup { + basicGroupTemp := BasicGroup{ + tdCommon: tdCommon{Type: "basicGroup"}, + ID: iD, + MemberCount: memberCount, + Status: status, + EveryoneIsAdministrator: everyoneIsAdministrator, + IsActive: isActive, + UpgradedToSupergroupID: upgradedToSupergroupID, + } + + return &basicGroupTemp +} + +// UnmarshalJSON unmarshal to json +func (basicGroup *BasicGroup) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int32 `json:"id"` // Group identifier + MemberCount int32 `json:"member_count"` // Number of members in the group + EveryoneIsAdministrator bool `json:"everyone_is_administrator"` // True, if all members have been granted administrator rights in the group + IsActive bool `json:"is_active"` // True, if the group is active + UpgradedToSupergroupID int32 `json:"upgraded_to_supergroup_id"` // Identifier of the supergroup to which this group was upgraded; 0 if none + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + basicGroup.tdCommon = tempObj.tdCommon + basicGroup.ID = tempObj.ID + basicGroup.MemberCount = tempObj.MemberCount + basicGroup.EveryoneIsAdministrator = tempObj.EveryoneIsAdministrator + basicGroup.IsActive = tempObj.IsActive + basicGroup.UpgradedToSupergroupID = tempObj.UpgradedToSupergroupID + + fieldStatus, _ := unmarshalChatMemberStatus(objMap["status"]) + basicGroup.Status = fieldStatus + + return nil +} + +// BasicGroupFullInfo Contains full information about a basic group +type BasicGroupFullInfo struct { + tdCommon + CreatorUserID int32 `json:"creator_user_id"` // User identifier of the creator of the group; 0 if unknown + Members []ChatMember `json:"members"` // Group members + InviteLink string `json:"invite_link"` // Invite link for this group; available only for the group creator and only after it has been generated at least once +} + +// MessageType return the string telegram-type of BasicGroupFullInfo +func (basicGroupFullInfo *BasicGroupFullInfo) MessageType() string { + return "basicGroupFullInfo" +} + +// NewBasicGroupFullInfo creates a new BasicGroupFullInfo +// +// @param creatorUserID User identifier of the creator of the group; 0 if unknown +// @param members Group members +// @param inviteLink Invite link for this group; available only for the group creator and only after it has been generated at least once +func NewBasicGroupFullInfo(creatorUserID int32, members []ChatMember, inviteLink string) *BasicGroupFullInfo { + basicGroupFullInfoTemp := BasicGroupFullInfo{ + tdCommon: tdCommon{Type: "basicGroupFullInfo"}, + CreatorUserID: creatorUserID, + Members: members, + InviteLink: inviteLink, + } + + return &basicGroupFullInfoTemp +} + +// Supergroup Represents a supergroup or channel with zero or more members (subscribers in the case of channels). From the point of view of the system, a channel is a special kind of a supergroup: only administrators can post and see the list of members, and posts from all administrators use the name and photo of the channel instead of individual names and profile photos. Unlike supergroups, channels can have an unlimited number of subscribers +type Supergroup struct { + tdCommon + ID int32 `json:"id"` // Supergroup or channel identifier + Username string `json:"username"` // Username of the supergroup or channel; empty for private supergroups or channels + Date int32 `json:"date"` // Point in time (Unix timestamp) when the current user joined, or the point in time when the supergroup or channel was created, in case the user is not a member + Status ChatMemberStatus `json:"status"` // Status of the current user in the supergroup or channel + MemberCount int32 `json:"member_count"` // Member count; 0 if unknown. Currently it is guaranteed to be known only if the supergroup or channel was found through SearchPublicChats + AnyoneCanInvite bool `json:"anyone_can_invite"` // True, if any member of the supergroup can invite other members. This field has no meaning for channels + SignMessages bool `json:"sign_messages"` // True, if messages sent to the channel should contain information about the sender. This field is only applicable to channels + IsChannel bool `json:"is_channel"` // True, if the supergroup is a channel + IsVerified bool `json:"is_verified"` // True, if the supergroup or channel is verified + RestrictionReason string `json:"restriction_reason"` // If non-empty, contains the reason why access to this supergroup or channel must be restricted. Format of the string is "{type}: {description}". +} + +// MessageType return the string telegram-type of Supergroup +func (supergroup *Supergroup) MessageType() string { + return "supergroup" +} + +// NewSupergroup creates a new Supergroup +// +// @param iD Supergroup or channel identifier +// @param username Username of the supergroup or channel; empty for private supergroups or channels +// @param date Point in time (Unix timestamp) when the current user joined, or the point in time when the supergroup or channel was created, in case the user is not a member +// @param status Status of the current user in the supergroup or channel +// @param memberCount Member count; 0 if unknown. Currently it is guaranteed to be known only if the supergroup or channel was found through SearchPublicChats +// @param anyoneCanInvite True, if any member of the supergroup can invite other members. This field has no meaning for channels +// @param signMessages True, if messages sent to the channel should contain information about the sender. This field is only applicable to channels +// @param isChannel True, if the supergroup is a channel +// @param isVerified True, if the supergroup or channel is verified +// @param restrictionReason If non-empty, contains the reason why access to this supergroup or channel must be restricted. Format of the string is "{type}: {description}". +func NewSupergroup(iD int32, username string, date int32, status ChatMemberStatus, memberCount int32, anyoneCanInvite bool, signMessages bool, isChannel bool, isVerified bool, restrictionReason string) *Supergroup { + supergroupTemp := Supergroup{ + tdCommon: tdCommon{Type: "supergroup"}, + ID: iD, + Username: username, + Date: date, + Status: status, + MemberCount: memberCount, + AnyoneCanInvite: anyoneCanInvite, + SignMessages: signMessages, + IsChannel: isChannel, + IsVerified: isVerified, + RestrictionReason: restrictionReason, + } + + return &supergroupTemp +} + +// UnmarshalJSON unmarshal to json +func (supergroup *Supergroup) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int32 `json:"id"` // Supergroup or channel identifier + Username string `json:"username"` // Username of the supergroup or channel; empty for private supergroups or channels + Date int32 `json:"date"` // Point in time (Unix timestamp) when the current user joined, or the point in time when the supergroup or channel was created, in case the user is not a member + MemberCount int32 `json:"member_count"` // Member count; 0 if unknown. Currently it is guaranteed to be known only if the supergroup or channel was found through SearchPublicChats + AnyoneCanInvite bool `json:"anyone_can_invite"` // True, if any member of the supergroup can invite other members. This field has no meaning for channels + SignMessages bool `json:"sign_messages"` // True, if messages sent to the channel should contain information about the sender. This field is only applicable to channels + IsChannel bool `json:"is_channel"` // True, if the supergroup is a channel + IsVerified bool `json:"is_verified"` // True, if the supergroup or channel is verified + RestrictionReason string `json:"restriction_reason"` // If non-empty, contains the reason why access to this supergroup or channel must be restricted. Format of the string is "{type}: {description}". + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + supergroup.tdCommon = tempObj.tdCommon + supergroup.ID = tempObj.ID + supergroup.Username = tempObj.Username + supergroup.Date = tempObj.Date + supergroup.MemberCount = tempObj.MemberCount + supergroup.AnyoneCanInvite = tempObj.AnyoneCanInvite + supergroup.SignMessages = tempObj.SignMessages + supergroup.IsChannel = tempObj.IsChannel + supergroup.IsVerified = tempObj.IsVerified + supergroup.RestrictionReason = tempObj.RestrictionReason + + fieldStatus, _ := unmarshalChatMemberStatus(objMap["status"]) + supergroup.Status = fieldStatus + + return nil +} + +// SupergroupFullInfo Contains full information about a supergroup or channel +type SupergroupFullInfo struct { + tdCommon + Description string `json:"description"` // + MemberCount int32 `json:"member_count"` // Number of members in the supergroup or channel; 0 if unknown + AdministratorCount int32 `json:"administrator_count"` // Number of privileged users in the supergroup or channel; 0 if unknown + RestrictedCount int32 `json:"restricted_count"` // Number of restricted users in the supergroup; 0 if unknown + BannedCount int32 `json:"banned_count"` // Number of users banned from chat; 0 if unknown + CanGetMembers bool `json:"can_get_members"` // True, if members of the chat can be retrieved + CanSetUsername bool `json:"can_set_username"` // True, if the chat can be made public + CanSetStickerSet bool `json:"can_set_sticker_set"` // True, if the supergroup sticker set can be changed + IsAllHistoryAvailable bool `json:"is_all_history_available"` // True, if new chat members will have access to old messages. In public supergroups and both public and private channels, old messages are always available, so this option affects only private supergroups. The value of this field is only available for chat administrators + StickerSetID JSONInt64 `json:"sticker_set_id"` // Identifier of the supergroup sticker set; 0 if none + InviteLink string `json:"invite_link"` // Invite link for this chat + PinnedMessageID int64 `json:"pinned_message_id"` // Identifier of the pinned message in the chat; 0 if none + UpgradedFromBasicGroupID int32 `json:"upgraded_from_basic_group_id"` // Identifier of the basic group from which supergroup was upgraded; 0 if none + UpgradedFromMaxMessageID int64 `json:"upgraded_from_max_message_id"` // Identifier of the last message in the basic group from which supergroup was upgraded; 0 if none +} + +// MessageType return the string telegram-type of SupergroupFullInfo +func (supergroupFullInfo *SupergroupFullInfo) MessageType() string { + return "supergroupFullInfo" +} + +// NewSupergroupFullInfo creates a new SupergroupFullInfo +// +// @param description +// @param memberCount Number of members in the supergroup or channel; 0 if unknown +// @param administratorCount Number of privileged users in the supergroup or channel; 0 if unknown +// @param restrictedCount Number of restricted users in the supergroup; 0 if unknown +// @param bannedCount Number of users banned from chat; 0 if unknown +// @param canGetMembers True, if members of the chat can be retrieved +// @param canSetUsername True, if the chat can be made public +// @param canSetStickerSet True, if the supergroup sticker set can be changed +// @param isAllHistoryAvailable True, if new chat members will have access to old messages. In public supergroups and both public and private channels, old messages are always available, so this option affects only private supergroups. The value of this field is only available for chat administrators +// @param stickerSetID Identifier of the supergroup sticker set; 0 if none +// @param inviteLink Invite link for this chat +// @param pinnedMessageID Identifier of the pinned message in the chat; 0 if none +// @param upgradedFromBasicGroupID Identifier of the basic group from which supergroup was upgraded; 0 if none +// @param upgradedFromMaxMessageID Identifier of the last message in the basic group from which supergroup was upgraded; 0 if none +func NewSupergroupFullInfo(description string, memberCount int32, administratorCount int32, restrictedCount int32, bannedCount int32, canGetMembers bool, canSetUsername bool, canSetStickerSet bool, isAllHistoryAvailable bool, stickerSetID JSONInt64, inviteLink string, pinnedMessageID int64, upgradedFromBasicGroupID int32, upgradedFromMaxMessageID int64) *SupergroupFullInfo { + supergroupFullInfoTemp := SupergroupFullInfo{ + tdCommon: tdCommon{Type: "supergroupFullInfo"}, + Description: description, + MemberCount: memberCount, + AdministratorCount: administratorCount, + RestrictedCount: restrictedCount, + BannedCount: bannedCount, + CanGetMembers: canGetMembers, + CanSetUsername: canSetUsername, + CanSetStickerSet: canSetStickerSet, + IsAllHistoryAvailable: isAllHistoryAvailable, + StickerSetID: stickerSetID, + InviteLink: inviteLink, + PinnedMessageID: pinnedMessageID, + UpgradedFromBasicGroupID: upgradedFromBasicGroupID, + UpgradedFromMaxMessageID: upgradedFromMaxMessageID, + } + + return &supergroupFullInfoTemp +} + +// SecretChatStatePending The secret chat is not yet created; waiting for the other user to get online +type SecretChatStatePending struct { + tdCommon +} + +// MessageType return the string telegram-type of SecretChatStatePending +func (secretChatStatePending *SecretChatStatePending) MessageType() string { + return "secretChatStatePending" +} + +// NewSecretChatStatePending creates a new SecretChatStatePending +// +func NewSecretChatStatePending() *SecretChatStatePending { + secretChatStatePendingTemp := SecretChatStatePending{ + tdCommon: tdCommon{Type: "secretChatStatePending"}, + } + + return &secretChatStatePendingTemp +} + +// GetSecretChatStateEnum return the enum type of this object +func (secretChatStatePending *SecretChatStatePending) GetSecretChatStateEnum() SecretChatStateEnum { + return SecretChatStatePendingType +} + +// SecretChatStateReady The secret chat is ready to use +type SecretChatStateReady struct { + tdCommon +} + +// MessageType return the string telegram-type of SecretChatStateReady +func (secretChatStateReady *SecretChatStateReady) MessageType() string { + return "secretChatStateReady" +} + +// NewSecretChatStateReady creates a new SecretChatStateReady +// +func NewSecretChatStateReady() *SecretChatStateReady { + secretChatStateReadyTemp := SecretChatStateReady{ + tdCommon: tdCommon{Type: "secretChatStateReady"}, + } + + return &secretChatStateReadyTemp +} + +// GetSecretChatStateEnum return the enum type of this object +func (secretChatStateReady *SecretChatStateReady) GetSecretChatStateEnum() SecretChatStateEnum { + return SecretChatStateReadyType +} + +// SecretChatStateClosed The secret chat is closed +type SecretChatStateClosed struct { + tdCommon +} + +// MessageType return the string telegram-type of SecretChatStateClosed +func (secretChatStateClosed *SecretChatStateClosed) MessageType() string { + return "secretChatStateClosed" +} + +// NewSecretChatStateClosed creates a new SecretChatStateClosed +// +func NewSecretChatStateClosed() *SecretChatStateClosed { + secretChatStateClosedTemp := SecretChatStateClosed{ + tdCommon: tdCommon{Type: "secretChatStateClosed"}, + } + + return &secretChatStateClosedTemp +} + +// GetSecretChatStateEnum return the enum type of this object +func (secretChatStateClosed *SecretChatStateClosed) GetSecretChatStateEnum() SecretChatStateEnum { + return SecretChatStateClosedType +} + +// SecretChat Represents a secret chat +type SecretChat struct { + tdCommon + ID int32 `json:"id"` // Secret chat identifier + UserID int32 `json:"user_id"` // Identifier of the chat partner + State SecretChatState `json:"state"` // State of the secret chat + IsOutbound bool `json:"is_outbound"` // True, if the chat was created by the current user; otherwise false + TTL int32 `json:"ttl"` // Current message Time To Live setting (self-destruct timer) for the chat, in seconds + KeyHash []byte `json:"key_hash"` // Hash of the currently used key for comparison with the hash of the chat partner's key. This is a string of 36 bytes, which must be used to make a 12x12 square image with a color depth of 4. The first 16 bytes should be used to make a central 8x8 square, while the remaining 20 bytes should be used to construct a 2-pixel-wide border around that square. + Layer int32 `json:"layer"` // Secret chat layer; determines features supported by the other client. Video notes are supported if the layer >= 66 +} + +// MessageType return the string telegram-type of SecretChat +func (secretChat *SecretChat) MessageType() string { + return "secretChat" +} + +// NewSecretChat creates a new SecretChat +// +// @param iD Secret chat identifier +// @param userID Identifier of the chat partner +// @param state State of the secret chat +// @param isOutbound True, if the chat was created by the current user; otherwise false +// @param tTL Current message Time To Live setting (self-destruct timer) for the chat, in seconds +// @param keyHash Hash of the currently used key for comparison with the hash of the chat partner's key. This is a string of 36 bytes, which must be used to make a 12x12 square image with a color depth of 4. The first 16 bytes should be used to make a central 8x8 square, while the remaining 20 bytes should be used to construct a 2-pixel-wide border around that square. +// @param layer Secret chat layer; determines features supported by the other client. Video notes are supported if the layer >= 66 +func NewSecretChat(iD int32, userID int32, state SecretChatState, isOutbound bool, tTL int32, keyHash []byte, layer int32) *SecretChat { + secretChatTemp := SecretChat{ + tdCommon: tdCommon{Type: "secretChat"}, + ID: iD, + UserID: userID, + State: state, + IsOutbound: isOutbound, + TTL: tTL, + KeyHash: keyHash, + Layer: layer, + } + + return &secretChatTemp +} + +// UnmarshalJSON unmarshal to json +func (secretChat *SecretChat) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int32 `json:"id"` // Secret chat identifier + UserID int32 `json:"user_id"` // Identifier of the chat partner + IsOutbound bool `json:"is_outbound"` // True, if the chat was created by the current user; otherwise false + TTL int32 `json:"ttl"` // Current message Time To Live setting (self-destruct timer) for the chat, in seconds + KeyHash []byte `json:"key_hash"` // Hash of the currently used key for comparison with the hash of the chat partner's key. This is a string of 36 bytes, which must be used to make a 12x12 square image with a color depth of 4. The first 16 bytes should be used to make a central 8x8 square, while the remaining 20 bytes should be used to construct a 2-pixel-wide border around that square. + Layer int32 `json:"layer"` // Secret chat layer; determines features supported by the other client. Video notes are supported if the layer >= 66 + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + secretChat.tdCommon = tempObj.tdCommon + secretChat.ID = tempObj.ID + secretChat.UserID = tempObj.UserID + secretChat.IsOutbound = tempObj.IsOutbound + secretChat.TTL = tempObj.TTL + secretChat.KeyHash = tempObj.KeyHash + secretChat.Layer = tempObj.Layer + + fieldState, _ := unmarshalSecretChatState(objMap["state"]) + secretChat.State = fieldState + + return nil +} + +// MessageForwardedFromUser The message was originally written by a known user +type MessageForwardedFromUser struct { + tdCommon + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user that originally sent this message + Date int32 `json:"date"` // Point in time (Unix timestamp) when the message was originally sent + ForwardedFromChatID int64 `json:"forwarded_from_chat_id"` // For messages forwarded to the chat with the current user (saved messages), the identifier of the chat from which the message was forwarded; 0 if unknown + ForwardedFromMessageID int64 `json:"forwarded_from_message_id"` // For messages forwarded to the chat with the current user (saved messages) the identifier of the original message from which the new message was forwarded; 0 if unknown +} + +// MessageType return the string telegram-type of MessageForwardedFromUser +func (messageForwardedFromUser *MessageForwardedFromUser) MessageType() string { + return "messageForwardedFromUser" +} + +// NewMessageForwardedFromUser creates a new MessageForwardedFromUser +// +// @param senderUserID Identifier of the user that originally sent this message +// @param date Point in time (Unix timestamp) when the message was originally sent +// @param forwardedFromChatID For messages forwarded to the chat with the current user (saved messages), the identifier of the chat from which the message was forwarded; 0 if unknown +// @param forwardedFromMessageID For messages forwarded to the chat with the current user (saved messages) the identifier of the original message from which the new message was forwarded; 0 if unknown +func NewMessageForwardedFromUser(senderUserID int32, date int32, forwardedFromChatID int64, forwardedFromMessageID int64) *MessageForwardedFromUser { + messageForwardedFromUserTemp := MessageForwardedFromUser{ + tdCommon: tdCommon{Type: "messageForwardedFromUser"}, + SenderUserID: senderUserID, + Date: date, + ForwardedFromChatID: forwardedFromChatID, + ForwardedFromMessageID: forwardedFromMessageID, + } + + return &messageForwardedFromUserTemp +} + +// GetMessageForwardInfoEnum return the enum type of this object +func (messageForwardedFromUser *MessageForwardedFromUser) GetMessageForwardInfoEnum() MessageForwardInfoEnum { + return MessageForwardedFromUserType +} + +// MessageForwardedPost The message was originally a post in a channel +type MessageForwardedPost struct { + tdCommon + ChatID int64 `json:"chat_id"` // Identifier of the chat from which the message was forwarded + AuthorSignature string `json:"author_signature"` // Post author signature + Date int32 `json:"date"` // Point in time (Unix timestamp) when the message was originally sent + MessageID int64 `json:"message_id"` // Message identifier of the original message from which the new message was forwarded; 0 if unknown + ForwardedFromChatID int64 `json:"forwarded_from_chat_id"` // For messages forwarded to the chat with the current user (saved messages), the identifier of the chat from which the message was forwarded; 0 if unknown + ForwardedFromMessageID int64 `json:"forwarded_from_message_id"` // For messages forwarded to the chat with the current user (saved messages), the identifier of the original message from which the new message was forwarded; 0 if unknown +} + +// MessageType return the string telegram-type of MessageForwardedPost +func (messageForwardedPost *MessageForwardedPost) MessageType() string { + return "messageForwardedPost" +} + +// NewMessageForwardedPost creates a new MessageForwardedPost +// +// @param chatID Identifier of the chat from which the message was forwarded +// @param authorSignature Post author signature +// @param date Point in time (Unix timestamp) when the message was originally sent +// @param messageID Message identifier of the original message from which the new message was forwarded; 0 if unknown +// @param forwardedFromChatID For messages forwarded to the chat with the current user (saved messages), the identifier of the chat from which the message was forwarded; 0 if unknown +// @param forwardedFromMessageID For messages forwarded to the chat with the current user (saved messages), the identifier of the original message from which the new message was forwarded; 0 if unknown +func NewMessageForwardedPost(chatID int64, authorSignature string, date int32, messageID int64, forwardedFromChatID int64, forwardedFromMessageID int64) *MessageForwardedPost { + messageForwardedPostTemp := MessageForwardedPost{ + tdCommon: tdCommon{Type: "messageForwardedPost"}, + ChatID: chatID, + AuthorSignature: authorSignature, + Date: date, + MessageID: messageID, + ForwardedFromChatID: forwardedFromChatID, + ForwardedFromMessageID: forwardedFromMessageID, + } + + return &messageForwardedPostTemp +} + +// GetMessageForwardInfoEnum return the enum type of this object +func (messageForwardedPost *MessageForwardedPost) GetMessageForwardInfoEnum() MessageForwardInfoEnum { + return MessageForwardedPostType +} + +// MessageSendingStatePending The message is being sent now, but has not yet been delivered to the server +type MessageSendingStatePending struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageSendingStatePending +func (messageSendingStatePending *MessageSendingStatePending) MessageType() string { + return "messageSendingStatePending" +} + +// NewMessageSendingStatePending creates a new MessageSendingStatePending +// +func NewMessageSendingStatePending() *MessageSendingStatePending { + messageSendingStatePendingTemp := MessageSendingStatePending{ + tdCommon: tdCommon{Type: "messageSendingStatePending"}, + } + + return &messageSendingStatePendingTemp +} + +// GetMessageSendingStateEnum return the enum type of this object +func (messageSendingStatePending *MessageSendingStatePending) GetMessageSendingStateEnum() MessageSendingStateEnum { + return MessageSendingStatePendingType +} + +// MessageSendingStateFailed The message failed to be sent +type MessageSendingStateFailed struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageSendingStateFailed +func (messageSendingStateFailed *MessageSendingStateFailed) MessageType() string { + return "messageSendingStateFailed" +} + +// NewMessageSendingStateFailed creates a new MessageSendingStateFailed +// +func NewMessageSendingStateFailed() *MessageSendingStateFailed { + messageSendingStateFailedTemp := MessageSendingStateFailed{ + tdCommon: tdCommon{Type: "messageSendingStateFailed"}, + } + + return &messageSendingStateFailedTemp +} + +// GetMessageSendingStateEnum return the enum type of this object +func (messageSendingStateFailed *MessageSendingStateFailed) GetMessageSendingStateEnum() MessageSendingStateEnum { + return MessageSendingStateFailedType +} + +// Message Describes a message +type Message struct { + tdCommon + ID int64 `json:"id"` // Message identifier, unique for the chat to which the message belongs + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the message; 0 if unknown. It is unknown for channel posts + ChatID int64 `json:"chat_id"` // Chat identifier + SendingState MessageSendingState `json:"sending_state"` // Information about the sending state of the message; may be null + IsOutgoing bool `json:"is_outgoing"` // True, if the message is outgoing + CanBeEdited bool `json:"can_be_edited"` // True, if the message can be edited + CanBeForwarded bool `json:"can_be_forwarded"` // True, if the message can be forwarded + CanBeDeletedOnlyForSelf bool `json:"can_be_deleted_only_for_self"` // True, if the message can be deleted only for the current user while other users will continue to see it + CanBeDeletedForAllUsers bool `json:"can_be_deleted_for_all_users"` // True, if the message can be deleted for all users + IsChannelPost bool `json:"is_channel_post"` // True, if the message is a channel post. All messages to channels are channel posts, all other messages are not channel posts + ContainsUnreadMention bool `json:"contains_unread_mention"` // True, if the message contains an unread mention for the current user + Date int32 `json:"date"` // Point in time (Unix timestamp) when the message was sent + EditDate int32 `json:"edit_date"` // Point in time (Unix timestamp) when the message was last edited + ForwardInfo MessageForwardInfo `json:"forward_info"` // Information about the initial message sender; may be null + ReplyToMessageID int64 `json:"reply_to_message_id"` // If non-zero, the identifier of the message this message is replying to; can be the identifier of a deleted message + TTL int32 `json:"ttl"` // For self-destructing messages, the message's TTL (Time To Live), in seconds; 0 if none. TDLib will send updateDeleteMessages or updateMessageContent once the TTL expires + TTLExpiresIn float64 `json:"ttl_expires_in"` // Time left before the message expires, in seconds + ViaBotUserID int32 `json:"via_bot_user_id"` // If non-zero, the user identifier of the bot through which this message was sent + AuthorSignature string `json:"author_signature"` // For channel posts, optional author signature + Views int32 `json:"views"` // Number of times this message was viewed + MediaAlbumID JSONInt64 `json:"media_album_id"` // Unique identifier of an album this message belongs to. Only photos and videos can be grouped together in albums + Content MessageContent `json:"content"` // Content of the message + ReplyMarkup ReplyMarkup `json:"reply_markup"` // Reply markup for the message; may be null +} + +// MessageType return the string telegram-type of Message +func (message *Message) MessageType() string { + return "message" +} + +// NewMessage creates a new Message +// +// @param iD Message identifier, unique for the chat to which the message belongs +// @param senderUserID Identifier of the user who sent the message; 0 if unknown. It is unknown for channel posts +// @param chatID Chat identifier +// @param sendingState Information about the sending state of the message; may be null +// @param isOutgoing True, if the message is outgoing +// @param canBeEdited True, if the message can be edited +// @param canBeForwarded True, if the message can be forwarded +// @param canBeDeletedOnlyForSelf True, if the message can be deleted only for the current user while other users will continue to see it +// @param canBeDeletedForAllUsers True, if the message can be deleted for all users +// @param isChannelPost True, if the message is a channel post. All messages to channels are channel posts, all other messages are not channel posts +// @param containsUnreadMention True, if the message contains an unread mention for the current user +// @param date Point in time (Unix timestamp) when the message was sent +// @param editDate Point in time (Unix timestamp) when the message was last edited +// @param forwardInfo Information about the initial message sender; may be null +// @param replyToMessageID If non-zero, the identifier of the message this message is replying to; can be the identifier of a deleted message +// @param tTL For self-destructing messages, the message's TTL (Time To Live), in seconds; 0 if none. TDLib will send updateDeleteMessages or updateMessageContent once the TTL expires +// @param tTLExpiresIn Time left before the message expires, in seconds +// @param viaBotUserID If non-zero, the user identifier of the bot through which this message was sent +// @param authorSignature For channel posts, optional author signature +// @param views Number of times this message was viewed +// @param mediaAlbumID Unique identifier of an album this message belongs to. Only photos and videos can be grouped together in albums +// @param content Content of the message +// @param replyMarkup Reply markup for the message; may be null +func NewMessage(iD int64, senderUserID int32, chatID int64, sendingState MessageSendingState, isOutgoing bool, canBeEdited bool, canBeForwarded bool, canBeDeletedOnlyForSelf bool, canBeDeletedForAllUsers bool, isChannelPost bool, containsUnreadMention bool, date int32, editDate int32, forwardInfo MessageForwardInfo, replyToMessageID int64, tTL int32, tTLExpiresIn float64, viaBotUserID int32, authorSignature string, views int32, mediaAlbumID JSONInt64, content MessageContent, replyMarkup ReplyMarkup) *Message { + messageTemp := Message{ + tdCommon: tdCommon{Type: "message"}, + ID: iD, + SenderUserID: senderUserID, + ChatID: chatID, + SendingState: sendingState, + IsOutgoing: isOutgoing, + CanBeEdited: canBeEdited, + CanBeForwarded: canBeForwarded, + CanBeDeletedOnlyForSelf: canBeDeletedOnlyForSelf, + CanBeDeletedForAllUsers: canBeDeletedForAllUsers, + IsChannelPost: isChannelPost, + ContainsUnreadMention: containsUnreadMention, + Date: date, + EditDate: editDate, + ForwardInfo: forwardInfo, + ReplyToMessageID: replyToMessageID, + TTL: tTL, + TTLExpiresIn: tTLExpiresIn, + ViaBotUserID: viaBotUserID, + AuthorSignature: authorSignature, + Views: views, + MediaAlbumID: mediaAlbumID, + Content: content, + ReplyMarkup: replyMarkup, + } + + return &messageTemp +} + +// UnmarshalJSON unmarshal to json +func (message *Message) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int64 `json:"id"` // Message identifier, unique for the chat to which the message belongs + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the message; 0 if unknown. It is unknown for channel posts + ChatID int64 `json:"chat_id"` // Chat identifier + IsOutgoing bool `json:"is_outgoing"` // True, if the message is outgoing + CanBeEdited bool `json:"can_be_edited"` // True, if the message can be edited + CanBeForwarded bool `json:"can_be_forwarded"` // True, if the message can be forwarded + CanBeDeletedOnlyForSelf bool `json:"can_be_deleted_only_for_self"` // True, if the message can be deleted only for the current user while other users will continue to see it + CanBeDeletedForAllUsers bool `json:"can_be_deleted_for_all_users"` // True, if the message can be deleted for all users + IsChannelPost bool `json:"is_channel_post"` // True, if the message is a channel post. All messages to channels are channel posts, all other messages are not channel posts + ContainsUnreadMention bool `json:"contains_unread_mention"` // True, if the message contains an unread mention for the current user + Date int32 `json:"date"` // Point in time (Unix timestamp) when the message was sent + EditDate int32 `json:"edit_date"` // Point in time (Unix timestamp) when the message was last edited + ReplyToMessageID int64 `json:"reply_to_message_id"` // If non-zero, the identifier of the message this message is replying to; can be the identifier of a deleted message + TTL int32 `json:"ttl"` // For self-destructing messages, the message's TTL (Time To Live), in seconds; 0 if none. TDLib will send updateDeleteMessages or updateMessageContent once the TTL expires + TTLExpiresIn float64 `json:"ttl_expires_in"` // Time left before the message expires, in seconds + ViaBotUserID int32 `json:"via_bot_user_id"` // If non-zero, the user identifier of the bot through which this message was sent + AuthorSignature string `json:"author_signature"` // For channel posts, optional author signature + Views int32 `json:"views"` // Number of times this message was viewed + MediaAlbumID JSONInt64 `json:"media_album_id"` // Unique identifier of an album this message belongs to. Only photos and videos can be grouped together in albums + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + message.tdCommon = tempObj.tdCommon + message.ID = tempObj.ID + message.SenderUserID = tempObj.SenderUserID + message.ChatID = tempObj.ChatID + message.IsOutgoing = tempObj.IsOutgoing + message.CanBeEdited = tempObj.CanBeEdited + message.CanBeForwarded = tempObj.CanBeForwarded + message.CanBeDeletedOnlyForSelf = tempObj.CanBeDeletedOnlyForSelf + message.CanBeDeletedForAllUsers = tempObj.CanBeDeletedForAllUsers + message.IsChannelPost = tempObj.IsChannelPost + message.ContainsUnreadMention = tempObj.ContainsUnreadMention + message.Date = tempObj.Date + message.EditDate = tempObj.EditDate + message.ReplyToMessageID = tempObj.ReplyToMessageID + message.TTL = tempObj.TTL + message.TTLExpiresIn = tempObj.TTLExpiresIn + message.ViaBotUserID = tempObj.ViaBotUserID + message.AuthorSignature = tempObj.AuthorSignature + message.Views = tempObj.Views + message.MediaAlbumID = tempObj.MediaAlbumID + + fieldSendingState, _ := unmarshalMessageSendingState(objMap["sending_state"]) + message.SendingState = fieldSendingState + + fieldForwardInfo, _ := unmarshalMessageForwardInfo(objMap["forward_info"]) + message.ForwardInfo = fieldForwardInfo + + fieldContent, _ := unmarshalMessageContent(objMap["content"]) + message.Content = fieldContent + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + message.ReplyMarkup = fieldReplyMarkup + + return nil +} + +// Messages Contains a list of messages +type Messages struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of messages found + Messages []Message `json:"messages"` // List of messages; messages may be null +} + +// MessageType return the string telegram-type of Messages +func (messages *Messages) MessageType() string { + return "messages" +} + +// NewMessages creates a new Messages +// +// @param totalCount Approximate total count of messages found +// @param messages List of messages; messages may be null +func NewMessages(totalCount int32, messages []Message) *Messages { + messagesTemp := Messages{ + tdCommon: tdCommon{Type: "messages"}, + TotalCount: totalCount, + Messages: messages, + } + + return &messagesTemp +} + +// FoundMessages Contains a list of messages found by a search +type FoundMessages struct { + tdCommon + Messages []Message `json:"messages"` // List of messages + NextFromSearchID JSONInt64 `json:"next_from_search_id"` // Value to pass as from_search_id to get more results +} + +// MessageType return the string telegram-type of FoundMessages +func (foundMessages *FoundMessages) MessageType() string { + return "foundMessages" +} + +// NewFoundMessages creates a new FoundMessages +// +// @param messages List of messages +// @param nextFromSearchID Value to pass as from_search_id to get more results +func NewFoundMessages(messages []Message, nextFromSearchID JSONInt64) *FoundMessages { + foundMessagesTemp := FoundMessages{ + tdCommon: tdCommon{Type: "foundMessages"}, + Messages: messages, + NextFromSearchID: nextFromSearchID, + } + + return &foundMessagesTemp +} + +// NotificationSettingsScopePrivateChats Notification settings applied to all private and secret chats when the corresponding chat setting has a default value +type NotificationSettingsScopePrivateChats struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationSettingsScopePrivateChats +func (notificationSettingsScopePrivateChats *NotificationSettingsScopePrivateChats) MessageType() string { + return "notificationSettingsScopePrivateChats" +} + +// NewNotificationSettingsScopePrivateChats creates a new NotificationSettingsScopePrivateChats +// +func NewNotificationSettingsScopePrivateChats() *NotificationSettingsScopePrivateChats { + notificationSettingsScopePrivateChatsTemp := NotificationSettingsScopePrivateChats{ + tdCommon: tdCommon{Type: "notificationSettingsScopePrivateChats"}, + } + + return ¬ificationSettingsScopePrivateChatsTemp +} + +// GetNotificationSettingsScopeEnum return the enum type of this object +func (notificationSettingsScopePrivateChats *NotificationSettingsScopePrivateChats) GetNotificationSettingsScopeEnum() NotificationSettingsScopeEnum { + return NotificationSettingsScopePrivateChatsType +} + +// NotificationSettingsScopeGroupChats Notification settings applied to all basic groups, supergroups and channels when the corresponding chat setting has a default value +type NotificationSettingsScopeGroupChats struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationSettingsScopeGroupChats +func (notificationSettingsScopeGroupChats *NotificationSettingsScopeGroupChats) MessageType() string { + return "notificationSettingsScopeGroupChats" +} + +// NewNotificationSettingsScopeGroupChats creates a new NotificationSettingsScopeGroupChats +// +func NewNotificationSettingsScopeGroupChats() *NotificationSettingsScopeGroupChats { + notificationSettingsScopeGroupChatsTemp := NotificationSettingsScopeGroupChats{ + tdCommon: tdCommon{Type: "notificationSettingsScopeGroupChats"}, + } + + return ¬ificationSettingsScopeGroupChatsTemp +} + +// GetNotificationSettingsScopeEnum return the enum type of this object +func (notificationSettingsScopeGroupChats *NotificationSettingsScopeGroupChats) GetNotificationSettingsScopeEnum() NotificationSettingsScopeEnum { + return NotificationSettingsScopeGroupChatsType +} + +// ChatNotificationSettings Contains information about notification settings for a chat +type ChatNotificationSettings struct { + tdCommon + UseDefaultMuteFor bool `json:"use_default_mute_for"` // If true, mute_for is ignored and the value for the relevant type of chat is used instead + MuteFor int32 `json:"mute_for"` // Time left before notifications will be unmuted, in seconds + UseDefaultSound bool `json:"use_default_sound"` // If true, sound is ignored and the value for the relevant type of chat is used instead + Sound string `json:"sound"` // The name of an audio file to be used for notification sounds; only applies to iOS applications + UseDefaultShowPreview bool `json:"use_default_show_preview"` // If true, show_preview is ignored and the value for the relevant type of chat is used instead + ShowPreview bool `json:"show_preview"` // True, if message content should be displayed in notifications +} + +// MessageType return the string telegram-type of ChatNotificationSettings +func (chatNotificationSettings *ChatNotificationSettings) MessageType() string { + return "chatNotificationSettings" +} + +// NewChatNotificationSettings creates a new ChatNotificationSettings +// +// @param useDefaultMuteFor If true, mute_for is ignored and the value for the relevant type of chat is used instead +// @param muteFor Time left before notifications will be unmuted, in seconds +// @param useDefaultSound If true, sound is ignored and the value for the relevant type of chat is used instead +// @param sound The name of an audio file to be used for notification sounds; only applies to iOS applications +// @param useDefaultShowPreview If true, show_preview is ignored and the value for the relevant type of chat is used instead +// @param showPreview True, if message content should be displayed in notifications +func NewChatNotificationSettings(useDefaultMuteFor bool, muteFor int32, useDefaultSound bool, sound string, useDefaultShowPreview bool, showPreview bool) *ChatNotificationSettings { + chatNotificationSettingsTemp := ChatNotificationSettings{ + tdCommon: tdCommon{Type: "chatNotificationSettings"}, + UseDefaultMuteFor: useDefaultMuteFor, + MuteFor: muteFor, + UseDefaultSound: useDefaultSound, + Sound: sound, + UseDefaultShowPreview: useDefaultShowPreview, + ShowPreview: showPreview, + } + + return &chatNotificationSettingsTemp +} + +// ScopeNotificationSettings Contains information about notification settings for several chats +type ScopeNotificationSettings struct { + tdCommon + MuteFor int32 `json:"mute_for"` // Time left before notifications will be unmuted, in seconds + Sound string `json:"sound"` // The name of an audio file to be used for notification sounds; only applies to iOS applications + ShowPreview bool `json:"show_preview"` // True, if message content should be displayed in notifications +} + +// MessageType return the string telegram-type of ScopeNotificationSettings +func (scopeNotificationSettings *ScopeNotificationSettings) MessageType() string { + return "scopeNotificationSettings" +} + +// NewScopeNotificationSettings creates a new ScopeNotificationSettings +// +// @param muteFor Time left before notifications will be unmuted, in seconds +// @param sound The name of an audio file to be used for notification sounds; only applies to iOS applications +// @param showPreview True, if message content should be displayed in notifications +func NewScopeNotificationSettings(muteFor int32, sound string, showPreview bool) *ScopeNotificationSettings { + scopeNotificationSettingsTemp := ScopeNotificationSettings{ + tdCommon: tdCommon{Type: "scopeNotificationSettings"}, + MuteFor: muteFor, + Sound: sound, + ShowPreview: showPreview, + } + + return &scopeNotificationSettingsTemp +} + +// DraftMessage Contains information about a message draft +type DraftMessage struct { + tdCommon + ReplyToMessageID int64 `json:"reply_to_message_id"` // Identifier of the message to reply to; 0 if none + InputMessageText InputMessageContent `json:"input_message_text"` // Content of the message draft; this should always be of type inputMessageText +} + +// MessageType return the string telegram-type of DraftMessage +func (draftMessage *DraftMessage) MessageType() string { + return "draftMessage" +} + +// NewDraftMessage creates a new DraftMessage +// +// @param replyToMessageID Identifier of the message to reply to; 0 if none +// @param inputMessageText Content of the message draft; this should always be of type inputMessageText +func NewDraftMessage(replyToMessageID int64, inputMessageText InputMessageContent) *DraftMessage { + draftMessageTemp := DraftMessage{ + tdCommon: tdCommon{Type: "draftMessage"}, + ReplyToMessageID: replyToMessageID, + InputMessageText: inputMessageText, + } + + return &draftMessageTemp +} + +// UnmarshalJSON unmarshal to json +func (draftMessage *DraftMessage) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ReplyToMessageID int64 `json:"reply_to_message_id"` // Identifier of the message to reply to; 0 if none + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + draftMessage.tdCommon = tempObj.tdCommon + draftMessage.ReplyToMessageID = tempObj.ReplyToMessageID + + fieldInputMessageText, _ := unmarshalInputMessageContent(objMap["input_message_text"]) + draftMessage.InputMessageText = fieldInputMessageText + + return nil +} + +// ChatTypePrivate An ordinary chat with a user +type ChatTypePrivate struct { + tdCommon + UserID int32 `json:"user_id"` // User identifier +} + +// MessageType return the string telegram-type of ChatTypePrivate +func (chatTypePrivate *ChatTypePrivate) MessageType() string { + return "chatTypePrivate" +} + +// NewChatTypePrivate creates a new ChatTypePrivate +// +// @param userID User identifier +func NewChatTypePrivate(userID int32) *ChatTypePrivate { + chatTypePrivateTemp := ChatTypePrivate{ + tdCommon: tdCommon{Type: "chatTypePrivate"}, + UserID: userID, + } + + return &chatTypePrivateTemp +} + +// GetChatTypeEnum return the enum type of this object +func (chatTypePrivate *ChatTypePrivate) GetChatTypeEnum() ChatTypeEnum { + return ChatTypePrivateType +} + +// ChatTypeBasicGroup A basic group (i.e., a chat with 0-200 other users) +type ChatTypeBasicGroup struct { + tdCommon + BasicGroupID int32 `json:"basic_group_id"` // Basic group identifier +} + +// MessageType return the string telegram-type of ChatTypeBasicGroup +func (chatTypeBasicGroup *ChatTypeBasicGroup) MessageType() string { + return "chatTypeBasicGroup" +} + +// NewChatTypeBasicGroup creates a new ChatTypeBasicGroup +// +// @param basicGroupID Basic group identifier +func NewChatTypeBasicGroup(basicGroupID int32) *ChatTypeBasicGroup { + chatTypeBasicGroupTemp := ChatTypeBasicGroup{ + tdCommon: tdCommon{Type: "chatTypeBasicGroup"}, + BasicGroupID: basicGroupID, + } + + return &chatTypeBasicGroupTemp +} + +// GetChatTypeEnum return the enum type of this object +func (chatTypeBasicGroup *ChatTypeBasicGroup) GetChatTypeEnum() ChatTypeEnum { + return ChatTypeBasicGroupType +} + +// ChatTypeSupergroup A supergroup (i.e. a chat with up to GetOption("supergroup_max_size") other users), or channel (with unlimited members) +type ChatTypeSupergroup struct { + tdCommon + SupergroupID int32 `json:"supergroup_id"` // Supergroup or channel identifier + IsChannel bool `json:"is_channel"` // True, if the supergroup is a channel +} + +// MessageType return the string telegram-type of ChatTypeSupergroup +func (chatTypeSupergroup *ChatTypeSupergroup) MessageType() string { + return "chatTypeSupergroup" +} + +// NewChatTypeSupergroup creates a new ChatTypeSupergroup +// +// @param supergroupID Supergroup or channel identifier +// @param isChannel True, if the supergroup is a channel +func NewChatTypeSupergroup(supergroupID int32, isChannel bool) *ChatTypeSupergroup { + chatTypeSupergroupTemp := ChatTypeSupergroup{ + tdCommon: tdCommon{Type: "chatTypeSupergroup"}, + SupergroupID: supergroupID, + IsChannel: isChannel, + } + + return &chatTypeSupergroupTemp +} + +// GetChatTypeEnum return the enum type of this object +func (chatTypeSupergroup *ChatTypeSupergroup) GetChatTypeEnum() ChatTypeEnum { + return ChatTypeSupergroupType +} + +// ChatTypeSecret A secret chat with a user +type ChatTypeSecret struct { + tdCommon + SecretChatID int32 `json:"secret_chat_id"` // Secret chat identifier + UserID int32 `json:"user_id"` // User identifier of the secret chat peer +} + +// MessageType return the string telegram-type of ChatTypeSecret +func (chatTypeSecret *ChatTypeSecret) MessageType() string { + return "chatTypeSecret" +} + +// NewChatTypeSecret creates a new ChatTypeSecret +// +// @param secretChatID Secret chat identifier +// @param userID User identifier of the secret chat peer +func NewChatTypeSecret(secretChatID int32, userID int32) *ChatTypeSecret { + chatTypeSecretTemp := ChatTypeSecret{ + tdCommon: tdCommon{Type: "chatTypeSecret"}, + SecretChatID: secretChatID, + UserID: userID, + } + + return &chatTypeSecretTemp +} + +// GetChatTypeEnum return the enum type of this object +func (chatTypeSecret *ChatTypeSecret) GetChatTypeEnum() ChatTypeEnum { + return ChatTypeSecretType +} + +// Chat A chat. (Can be a private chat, basic group, supergroup, or secret chat) +type Chat struct { + tdCommon + ID int64 `json:"id"` // Chat unique identifier + Type ChatType `json:"type"` // Type of the chat + Title string `json:"title"` // Chat title + Photo *ChatPhoto `json:"photo"` // Chat photo; may be null + LastMessage *Message `json:"last_message"` // Last message in the chat; may be null + Order JSONInt64 `json:"order"` // Descending parameter by which chats are sorted in the main chat list. If the order number of two chats is the same, they must be sorted in descending order by ID. If 0, the position of the chat in the list is undetermined + IsPinned bool `json:"is_pinned"` // True, if the chat is pinned + IsMarkedAsUnread bool `json:"is_marked_as_unread"` // True, if the chat is marked as unread + IsSponsored bool `json:"is_sponsored"` // True, if the chat is sponsored by the user's MTProxy server + CanBeReported bool `json:"can_be_reported"` // True, if the chat can be reported to Telegram moderators through reportChat + DefaultDisableNotification bool `json:"default_disable_notification"` // Default value of the disable_notification parameter, used when a message is sent to the chat + UnreadCount int32 `json:"unread_count"` // Number of unread messages in the chat + LastReadInboxMessageID int64 `json:"last_read_inbox_message_id"` // Identifier of the last read incoming message + LastReadOutboxMessageID int64 `json:"last_read_outbox_message_id"` // Identifier of the last read outgoing message + UnreadMentionCount int32 `json:"unread_mention_count"` // Number of unread messages with a mention/reply in the chat + NotificationSettings *ChatNotificationSettings `json:"notification_settings"` // Notification settings for this chat + ReplyMarkupMessageID int64 `json:"reply_markup_message_id"` // Identifier of the message from which reply markup needs to be used; 0 if there is no default custom reply markup in the chat + DraftMessage *DraftMessage `json:"draft_message"` // A draft of a message in the chat; may be null + ClientData string `json:"client_data"` // Contains client-specific data associated with the chat. (For example, the chat position or local chat notification settings can be stored here.) Persistent if a message database is used +} + +// MessageType return the string telegram-type of Chat +func (chat *Chat) MessageType() string { + return "chat" +} + +// NewChat creates a new Chat +// +// @param iD Chat unique identifier +// @param typeParam Type of the chat +// @param title Chat title +// @param photo Chat photo; may be null +// @param lastMessage Last message in the chat; may be null +// @param order Descending parameter by which chats are sorted in the main chat list. If the order number of two chats is the same, they must be sorted in descending order by ID. If 0, the position of the chat in the list is undetermined +// @param isPinned True, if the chat is pinned +// @param isMarkedAsUnread True, if the chat is marked as unread +// @param isSponsored True, if the chat is sponsored by the user's MTProxy server +// @param canBeReported True, if the chat can be reported to Telegram moderators through reportChat +// @param defaultDisableNotification Default value of the disable_notification parameter, used when a message is sent to the chat +// @param unreadCount Number of unread messages in the chat +// @param lastReadInboxMessageID Identifier of the last read incoming message +// @param lastReadOutboxMessageID Identifier of the last read outgoing message +// @param unreadMentionCount Number of unread messages with a mention/reply in the chat +// @param notificationSettings Notification settings for this chat +// @param replyMarkupMessageID Identifier of the message from which reply markup needs to be used; 0 if there is no default custom reply markup in the chat +// @param draftMessage A draft of a message in the chat; may be null +// @param clientData Contains client-specific data associated with the chat. (For example, the chat position or local chat notification settings can be stored here.) Persistent if a message database is used +func NewChat(iD int64, typeParam ChatType, title string, photo *ChatPhoto, lastMessage *Message, order JSONInt64, isPinned bool, isMarkedAsUnread bool, isSponsored bool, canBeReported bool, defaultDisableNotification bool, unreadCount int32, lastReadInboxMessageID int64, lastReadOutboxMessageID int64, unreadMentionCount int32, notificationSettings *ChatNotificationSettings, replyMarkupMessageID int64, draftMessage *DraftMessage, clientData string) *Chat { + chatTemp := Chat{ + tdCommon: tdCommon{Type: "chat"}, + ID: iD, + Type: typeParam, + Title: title, + Photo: photo, + LastMessage: lastMessage, + Order: order, + IsPinned: isPinned, + IsMarkedAsUnread: isMarkedAsUnread, + IsSponsored: isSponsored, + CanBeReported: canBeReported, + DefaultDisableNotification: defaultDisableNotification, + UnreadCount: unreadCount, + LastReadInboxMessageID: lastReadInboxMessageID, + LastReadOutboxMessageID: lastReadOutboxMessageID, + UnreadMentionCount: unreadMentionCount, + NotificationSettings: notificationSettings, + ReplyMarkupMessageID: replyMarkupMessageID, + DraftMessage: draftMessage, + ClientData: clientData, + } + + return &chatTemp +} + +// UnmarshalJSON unmarshal to json +func (chat *Chat) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int64 `json:"id"` // Chat unique identifier + Title string `json:"title"` // Chat title + Photo *ChatPhoto `json:"photo"` // Chat photo; may be null + LastMessage *Message `json:"last_message"` // Last message in the chat; may be null + Order JSONInt64 `json:"order"` // Descending parameter by which chats are sorted in the main chat list. If the order number of two chats is the same, they must be sorted in descending order by ID. If 0, the position of the chat in the list is undetermined + IsPinned bool `json:"is_pinned"` // True, if the chat is pinned + IsMarkedAsUnread bool `json:"is_marked_as_unread"` // True, if the chat is marked as unread + IsSponsored bool `json:"is_sponsored"` // True, if the chat is sponsored by the user's MTProxy server + CanBeReported bool `json:"can_be_reported"` // True, if the chat can be reported to Telegram moderators through reportChat + DefaultDisableNotification bool `json:"default_disable_notification"` // Default value of the disable_notification parameter, used when a message is sent to the chat + UnreadCount int32 `json:"unread_count"` // Number of unread messages in the chat + LastReadInboxMessageID int64 `json:"last_read_inbox_message_id"` // Identifier of the last read incoming message + LastReadOutboxMessageID int64 `json:"last_read_outbox_message_id"` // Identifier of the last read outgoing message + UnreadMentionCount int32 `json:"unread_mention_count"` // Number of unread messages with a mention/reply in the chat + NotificationSettings *ChatNotificationSettings `json:"notification_settings"` // Notification settings for this chat + ReplyMarkupMessageID int64 `json:"reply_markup_message_id"` // Identifier of the message from which reply markup needs to be used; 0 if there is no default custom reply markup in the chat + DraftMessage *DraftMessage `json:"draft_message"` // A draft of a message in the chat; may be null + ClientData string `json:"client_data"` // Contains client-specific data associated with the chat. (For example, the chat position or local chat notification settings can be stored here.) Persistent if a message database is used + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chat.tdCommon = tempObj.tdCommon + chat.ID = tempObj.ID + chat.Title = tempObj.Title + chat.Photo = tempObj.Photo + chat.LastMessage = tempObj.LastMessage + chat.Order = tempObj.Order + chat.IsPinned = tempObj.IsPinned + chat.IsMarkedAsUnread = tempObj.IsMarkedAsUnread + chat.IsSponsored = tempObj.IsSponsored + chat.CanBeReported = tempObj.CanBeReported + chat.DefaultDisableNotification = tempObj.DefaultDisableNotification + chat.UnreadCount = tempObj.UnreadCount + chat.LastReadInboxMessageID = tempObj.LastReadInboxMessageID + chat.LastReadOutboxMessageID = tempObj.LastReadOutboxMessageID + chat.UnreadMentionCount = tempObj.UnreadMentionCount + chat.NotificationSettings = tempObj.NotificationSettings + chat.ReplyMarkupMessageID = tempObj.ReplyMarkupMessageID + chat.DraftMessage = tempObj.DraftMessage + chat.ClientData = tempObj.ClientData + + fieldType, _ := unmarshalChatType(objMap["type"]) + chat.Type = fieldType + + return nil +} + +// Chats Represents a list of chats +type Chats struct { + tdCommon + ChatIDs []int64 `json:"chat_ids"` // List of chat identifiers +} + +// MessageType return the string telegram-type of Chats +func (chats *Chats) MessageType() string { + return "chats" +} + +// NewChats creates a new Chats +// +// @param chatIDs List of chat identifiers +func NewChats(chatIDs []int64) *Chats { + chatsTemp := Chats{ + tdCommon: tdCommon{Type: "chats"}, + ChatIDs: chatIDs, + } + + return &chatsTemp +} + +// ChatInviteLink Contains a chat invite link +type ChatInviteLink struct { + tdCommon + InviteLink string `json:"invite_link"` // Chat invite link +} + +// MessageType return the string telegram-type of ChatInviteLink +func (chatInviteLink *ChatInviteLink) MessageType() string { + return "chatInviteLink" +} + +// NewChatInviteLink creates a new ChatInviteLink +// +// @param inviteLink Chat invite link +func NewChatInviteLink(inviteLink string) *ChatInviteLink { + chatInviteLinkTemp := ChatInviteLink{ + tdCommon: tdCommon{Type: "chatInviteLink"}, + InviteLink: inviteLink, + } + + return &chatInviteLinkTemp +} + +// ChatInviteLinkInfo Contains information about a chat invite link +type ChatInviteLinkInfo struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier of the invite link; 0 if the user is not a member of this chat + Type ChatType `json:"type"` // Contains information about the type of the chat + Title string `json:"title"` // Title of the chat + Photo *ChatPhoto `json:"photo"` // Chat photo; may be null + MemberCount int32 `json:"member_count"` // Number of members + MemberUserIDs []int32 `json:"member_user_ids"` // User identifiers of some chat members that may be known to the current user + IsPublic bool `json:"is_public"` // True, if the chat is a public supergroup or channel with a username +} + +// MessageType return the string telegram-type of ChatInviteLinkInfo +func (chatInviteLinkInfo *ChatInviteLinkInfo) MessageType() string { + return "chatInviteLinkInfo" +} + +// NewChatInviteLinkInfo creates a new ChatInviteLinkInfo +// +// @param chatID Chat identifier of the invite link; 0 if the user is not a member of this chat +// @param typeParam Contains information about the type of the chat +// @param title Title of the chat +// @param photo Chat photo; may be null +// @param memberCount Number of members +// @param memberUserIDs User identifiers of some chat members that may be known to the current user +// @param isPublic True, if the chat is a public supergroup or channel with a username +func NewChatInviteLinkInfo(chatID int64, typeParam ChatType, title string, photo *ChatPhoto, memberCount int32, memberUserIDs []int32, isPublic bool) *ChatInviteLinkInfo { + chatInviteLinkInfoTemp := ChatInviteLinkInfo{ + tdCommon: tdCommon{Type: "chatInviteLinkInfo"}, + ChatID: chatID, + Type: typeParam, + Title: title, + Photo: photo, + MemberCount: memberCount, + MemberUserIDs: memberUserIDs, + IsPublic: isPublic, + } + + return &chatInviteLinkInfoTemp +} + +// UnmarshalJSON unmarshal to json +func (chatInviteLinkInfo *ChatInviteLinkInfo) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier of the invite link; 0 if the user is not a member of this chat + Title string `json:"title"` // Title of the chat + Photo *ChatPhoto `json:"photo"` // Chat photo; may be null + MemberCount int32 `json:"member_count"` // Number of members + MemberUserIDs []int32 `json:"member_user_ids"` // User identifiers of some chat members that may be known to the current user + IsPublic bool `json:"is_public"` // True, if the chat is a public supergroup or channel with a username + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatInviteLinkInfo.tdCommon = tempObj.tdCommon + chatInviteLinkInfo.ChatID = tempObj.ChatID + chatInviteLinkInfo.Title = tempObj.Title + chatInviteLinkInfo.Photo = tempObj.Photo + chatInviteLinkInfo.MemberCount = tempObj.MemberCount + chatInviteLinkInfo.MemberUserIDs = tempObj.MemberUserIDs + chatInviteLinkInfo.IsPublic = tempObj.IsPublic + + fieldType, _ := unmarshalChatType(objMap["type"]) + chatInviteLinkInfo.Type = fieldType + + return nil +} + +// KeyboardButtonTypeText A simple button, with text that should be sent when the button is pressed +type KeyboardButtonTypeText struct { + tdCommon +} + +// MessageType return the string telegram-type of KeyboardButtonTypeText +func (keyboardButtonTypeText *KeyboardButtonTypeText) MessageType() string { + return "keyboardButtonTypeText" +} + +// NewKeyboardButtonTypeText creates a new KeyboardButtonTypeText +// +func NewKeyboardButtonTypeText() *KeyboardButtonTypeText { + keyboardButtonTypeTextTemp := KeyboardButtonTypeText{ + tdCommon: tdCommon{Type: "keyboardButtonTypeText"}, + } + + return &keyboardButtonTypeTextTemp +} + +// GetKeyboardButtonTypeEnum return the enum type of this object +func (keyboardButtonTypeText *KeyboardButtonTypeText) GetKeyboardButtonTypeEnum() KeyboardButtonTypeEnum { + return KeyboardButtonTypeTextType +} + +// KeyboardButtonTypeRequestPhoneNumber A button that sends the user's phone number when pressed; available only in private chats +type KeyboardButtonTypeRequestPhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of KeyboardButtonTypeRequestPhoneNumber +func (keyboardButtonTypeRequestPhoneNumber *KeyboardButtonTypeRequestPhoneNumber) MessageType() string { + return "keyboardButtonTypeRequestPhoneNumber" +} + +// NewKeyboardButtonTypeRequestPhoneNumber creates a new KeyboardButtonTypeRequestPhoneNumber +// +func NewKeyboardButtonTypeRequestPhoneNumber() *KeyboardButtonTypeRequestPhoneNumber { + keyboardButtonTypeRequestPhoneNumberTemp := KeyboardButtonTypeRequestPhoneNumber{ + tdCommon: tdCommon{Type: "keyboardButtonTypeRequestPhoneNumber"}, + } + + return &keyboardButtonTypeRequestPhoneNumberTemp +} + +// GetKeyboardButtonTypeEnum return the enum type of this object +func (keyboardButtonTypeRequestPhoneNumber *KeyboardButtonTypeRequestPhoneNumber) GetKeyboardButtonTypeEnum() KeyboardButtonTypeEnum { + return KeyboardButtonTypeRequestPhoneNumberType +} + +// KeyboardButtonTypeRequestLocation A button that sends the user's location when pressed; available only in private chats +type KeyboardButtonTypeRequestLocation struct { + tdCommon +} + +// MessageType return the string telegram-type of KeyboardButtonTypeRequestLocation +func (keyboardButtonTypeRequestLocation *KeyboardButtonTypeRequestLocation) MessageType() string { + return "keyboardButtonTypeRequestLocation" +} + +// NewKeyboardButtonTypeRequestLocation creates a new KeyboardButtonTypeRequestLocation +// +func NewKeyboardButtonTypeRequestLocation() *KeyboardButtonTypeRequestLocation { + keyboardButtonTypeRequestLocationTemp := KeyboardButtonTypeRequestLocation{ + tdCommon: tdCommon{Type: "keyboardButtonTypeRequestLocation"}, + } + + return &keyboardButtonTypeRequestLocationTemp +} + +// GetKeyboardButtonTypeEnum return the enum type of this object +func (keyboardButtonTypeRequestLocation *KeyboardButtonTypeRequestLocation) GetKeyboardButtonTypeEnum() KeyboardButtonTypeEnum { + return KeyboardButtonTypeRequestLocationType +} + +// KeyboardButton Represents a single button in a bot keyboard +type KeyboardButton struct { + tdCommon + Text string `json:"text"` // Text of the button + Type KeyboardButtonType `json:"type"` // Type of the button +} + +// MessageType return the string telegram-type of KeyboardButton +func (keyboardButton *KeyboardButton) MessageType() string { + return "keyboardButton" +} + +// NewKeyboardButton creates a new KeyboardButton +// +// @param text Text of the button +// @param typeParam Type of the button +func NewKeyboardButton(text string, typeParam KeyboardButtonType) *KeyboardButton { + keyboardButtonTemp := KeyboardButton{ + tdCommon: tdCommon{Type: "keyboardButton"}, + Text: text, + Type: typeParam, + } + + return &keyboardButtonTemp +} + +// UnmarshalJSON unmarshal to json +func (keyboardButton *KeyboardButton) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Text string `json:"text"` // Text of the button + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + keyboardButton.tdCommon = tempObj.tdCommon + keyboardButton.Text = tempObj.Text + + fieldType, _ := unmarshalKeyboardButtonType(objMap["type"]) + keyboardButton.Type = fieldType + + return nil +} + +// InlineKeyboardButtonTypeURL A button that opens a specified URL +type InlineKeyboardButtonTypeURL struct { + tdCommon + URL string `json:"url"` // HTTP or tg:// URL to open +} + +// MessageType return the string telegram-type of InlineKeyboardButtonTypeURL +func (inlineKeyboardButtonTypeURL *InlineKeyboardButtonTypeURL) MessageType() string { + return "inlineKeyboardButtonTypeUrl" +} + +// NewInlineKeyboardButtonTypeURL creates a new InlineKeyboardButtonTypeURL +// +// @param uRL HTTP or tg:// URL to open +func NewInlineKeyboardButtonTypeURL(uRL string) *InlineKeyboardButtonTypeURL { + inlineKeyboardButtonTypeURLTemp := InlineKeyboardButtonTypeURL{ + tdCommon: tdCommon{Type: "inlineKeyboardButtonTypeUrl"}, + URL: uRL, + } + + return &inlineKeyboardButtonTypeURLTemp +} + +// GetInlineKeyboardButtonTypeEnum return the enum type of this object +func (inlineKeyboardButtonTypeURL *InlineKeyboardButtonTypeURL) GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum { + return InlineKeyboardButtonTypeURLType +} + +// InlineKeyboardButtonTypeCallback A button that sends a special callback query to a bot +type InlineKeyboardButtonTypeCallback struct { + tdCommon + Data []byte `json:"data"` // Data to be sent to the bot via a callback query +} + +// MessageType return the string telegram-type of InlineKeyboardButtonTypeCallback +func (inlineKeyboardButtonTypeCallback *InlineKeyboardButtonTypeCallback) MessageType() string { + return "inlineKeyboardButtonTypeCallback" +} + +// NewInlineKeyboardButtonTypeCallback creates a new InlineKeyboardButtonTypeCallback +// +// @param data Data to be sent to the bot via a callback query +func NewInlineKeyboardButtonTypeCallback(data []byte) *InlineKeyboardButtonTypeCallback { + inlineKeyboardButtonTypeCallbackTemp := InlineKeyboardButtonTypeCallback{ + tdCommon: tdCommon{Type: "inlineKeyboardButtonTypeCallback"}, + Data: data, + } + + return &inlineKeyboardButtonTypeCallbackTemp +} + +// GetInlineKeyboardButtonTypeEnum return the enum type of this object +func (inlineKeyboardButtonTypeCallback *InlineKeyboardButtonTypeCallback) GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum { + return InlineKeyboardButtonTypeCallbackType +} + +// InlineKeyboardButtonTypeCallbackGame A button with a game that sends a special callback query to a bot. This button must be in the first column and row of the keyboard and can be attached only to a message with content of the type messageGame +type InlineKeyboardButtonTypeCallbackGame struct { + tdCommon +} + +// MessageType return the string telegram-type of InlineKeyboardButtonTypeCallbackGame +func (inlineKeyboardButtonTypeCallbackGame *InlineKeyboardButtonTypeCallbackGame) MessageType() string { + return "inlineKeyboardButtonTypeCallbackGame" +} + +// NewInlineKeyboardButtonTypeCallbackGame creates a new InlineKeyboardButtonTypeCallbackGame +// +func NewInlineKeyboardButtonTypeCallbackGame() *InlineKeyboardButtonTypeCallbackGame { + inlineKeyboardButtonTypeCallbackGameTemp := InlineKeyboardButtonTypeCallbackGame{ + tdCommon: tdCommon{Type: "inlineKeyboardButtonTypeCallbackGame"}, + } + + return &inlineKeyboardButtonTypeCallbackGameTemp +} + +// GetInlineKeyboardButtonTypeEnum return the enum type of this object +func (inlineKeyboardButtonTypeCallbackGame *InlineKeyboardButtonTypeCallbackGame) GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum { + return InlineKeyboardButtonTypeCallbackGameType +} + +// InlineKeyboardButtonTypeSwitchInline A button that forces an inline query to the bot to be inserted in the input field +type InlineKeyboardButtonTypeSwitchInline struct { + tdCommon + Query string `json:"query"` // Inline query to be sent to the bot + InCurrentChat bool `json:"in_current_chat"` // True, if the inline query should be sent from the current chat +} + +// MessageType return the string telegram-type of InlineKeyboardButtonTypeSwitchInline +func (inlineKeyboardButtonTypeSwitchInline *InlineKeyboardButtonTypeSwitchInline) MessageType() string { + return "inlineKeyboardButtonTypeSwitchInline" +} + +// NewInlineKeyboardButtonTypeSwitchInline creates a new InlineKeyboardButtonTypeSwitchInline +// +// @param query Inline query to be sent to the bot +// @param inCurrentChat True, if the inline query should be sent from the current chat +func NewInlineKeyboardButtonTypeSwitchInline(query string, inCurrentChat bool) *InlineKeyboardButtonTypeSwitchInline { + inlineKeyboardButtonTypeSwitchInlineTemp := InlineKeyboardButtonTypeSwitchInline{ + tdCommon: tdCommon{Type: "inlineKeyboardButtonTypeSwitchInline"}, + Query: query, + InCurrentChat: inCurrentChat, + } + + return &inlineKeyboardButtonTypeSwitchInlineTemp +} + +// GetInlineKeyboardButtonTypeEnum return the enum type of this object +func (inlineKeyboardButtonTypeSwitchInline *InlineKeyboardButtonTypeSwitchInline) GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum { + return InlineKeyboardButtonTypeSwitchInlineType +} + +// InlineKeyboardButtonTypeBuy A button to buy something. This button must be in the first column and row of the keyboard and can be attached only to a message with content of the type messageInvoice +type InlineKeyboardButtonTypeBuy struct { + tdCommon +} + +// MessageType return the string telegram-type of InlineKeyboardButtonTypeBuy +func (inlineKeyboardButtonTypeBuy *InlineKeyboardButtonTypeBuy) MessageType() string { + return "inlineKeyboardButtonTypeBuy" +} + +// NewInlineKeyboardButtonTypeBuy creates a new InlineKeyboardButtonTypeBuy +// +func NewInlineKeyboardButtonTypeBuy() *InlineKeyboardButtonTypeBuy { + inlineKeyboardButtonTypeBuyTemp := InlineKeyboardButtonTypeBuy{ + tdCommon: tdCommon{Type: "inlineKeyboardButtonTypeBuy"}, + } + + return &inlineKeyboardButtonTypeBuyTemp +} + +// GetInlineKeyboardButtonTypeEnum return the enum type of this object +func (inlineKeyboardButtonTypeBuy *InlineKeyboardButtonTypeBuy) GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum { + return InlineKeyboardButtonTypeBuyType +} + +// InlineKeyboardButton Represents a single button in an inline keyboard +type InlineKeyboardButton struct { + tdCommon + Text string `json:"text"` // Text of the button + Type InlineKeyboardButtonType `json:"type"` // Type of the button +} + +// MessageType return the string telegram-type of InlineKeyboardButton +func (inlineKeyboardButton *InlineKeyboardButton) MessageType() string { + return "inlineKeyboardButton" +} + +// NewInlineKeyboardButton creates a new InlineKeyboardButton +// +// @param text Text of the button +// @param typeParam Type of the button +func NewInlineKeyboardButton(text string, typeParam InlineKeyboardButtonType) *InlineKeyboardButton { + inlineKeyboardButtonTemp := InlineKeyboardButton{ + tdCommon: tdCommon{Type: "inlineKeyboardButton"}, + Text: text, + Type: typeParam, + } + + return &inlineKeyboardButtonTemp +} + +// UnmarshalJSON unmarshal to json +func (inlineKeyboardButton *InlineKeyboardButton) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Text string `json:"text"` // Text of the button + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inlineKeyboardButton.tdCommon = tempObj.tdCommon + inlineKeyboardButton.Text = tempObj.Text + + fieldType, _ := unmarshalInlineKeyboardButtonType(objMap["type"]) + inlineKeyboardButton.Type = fieldType + + return nil +} + +// ReplyMarkupRemoveKeyboard Instructs clients to remove the keyboard once this message has been received. This kind of keyboard can't be received in an incoming message; instead, UpdateChatReplyMarkup with message_id == 0 will be sent +type ReplyMarkupRemoveKeyboard struct { + tdCommon + IsPersonal bool `json:"is_personal"` // True, if the keyboard is removed only for the mentioned users or the target user of a reply +} + +// MessageType return the string telegram-type of ReplyMarkupRemoveKeyboard +func (replyMarkupRemoveKeyboard *ReplyMarkupRemoveKeyboard) MessageType() string { + return "replyMarkupRemoveKeyboard" +} + +// NewReplyMarkupRemoveKeyboard creates a new ReplyMarkupRemoveKeyboard +// +// @param isPersonal True, if the keyboard is removed only for the mentioned users or the target user of a reply +func NewReplyMarkupRemoveKeyboard(isPersonal bool) *ReplyMarkupRemoveKeyboard { + replyMarkupRemoveKeyboardTemp := ReplyMarkupRemoveKeyboard{ + tdCommon: tdCommon{Type: "replyMarkupRemoveKeyboard"}, + IsPersonal: isPersonal, + } + + return &replyMarkupRemoveKeyboardTemp +} + +// GetReplyMarkupEnum return the enum type of this object +func (replyMarkupRemoveKeyboard *ReplyMarkupRemoveKeyboard) GetReplyMarkupEnum() ReplyMarkupEnum { + return ReplyMarkupRemoveKeyboardType +} + +// ReplyMarkupForceReply Instructs clients to force a reply to this message +type ReplyMarkupForceReply struct { + tdCommon + IsPersonal bool `json:"is_personal"` // True, if a forced reply must automatically be shown to the current user. For outgoing messages, specify true to show the forced reply only for the mentioned users and for the target user of a reply +} + +// MessageType return the string telegram-type of ReplyMarkupForceReply +func (replyMarkupForceReply *ReplyMarkupForceReply) MessageType() string { + return "replyMarkupForceReply" +} + +// NewReplyMarkupForceReply creates a new ReplyMarkupForceReply +// +// @param isPersonal True, if a forced reply must automatically be shown to the current user. For outgoing messages, specify true to show the forced reply only for the mentioned users and for the target user of a reply +func NewReplyMarkupForceReply(isPersonal bool) *ReplyMarkupForceReply { + replyMarkupForceReplyTemp := ReplyMarkupForceReply{ + tdCommon: tdCommon{Type: "replyMarkupForceReply"}, + IsPersonal: isPersonal, + } + + return &replyMarkupForceReplyTemp +} + +// GetReplyMarkupEnum return the enum type of this object +func (replyMarkupForceReply *ReplyMarkupForceReply) GetReplyMarkupEnum() ReplyMarkupEnum { + return ReplyMarkupForceReplyType +} + +// ReplyMarkupShowKeyboard Contains a custom keyboard layout to quickly reply to bots +type ReplyMarkupShowKeyboard struct { + tdCommon + Rows [][]KeyboardButton `json:"rows"` // A list of rows of bot keyboard buttons + ResizeKeyboard bool `json:"resize_keyboard"` // True, if the client needs to resize the keyboard vertically + OneTime bool `json:"one_time"` // True, if the client needs to hide the keyboard after use + IsPersonal bool `json:"is_personal"` // True, if the keyboard must automatically be shown to the current user. For outgoing messages, specify true to show the keyboard only for the mentioned users and for the target user of a reply +} + +// MessageType return the string telegram-type of ReplyMarkupShowKeyboard +func (replyMarkupShowKeyboard *ReplyMarkupShowKeyboard) MessageType() string { + return "replyMarkupShowKeyboard" +} + +// NewReplyMarkupShowKeyboard creates a new ReplyMarkupShowKeyboard +// +// @param rows A list of rows of bot keyboard buttons +// @param resizeKeyboard True, if the client needs to resize the keyboard vertically +// @param oneTime True, if the client needs to hide the keyboard after use +// @param isPersonal True, if the keyboard must automatically be shown to the current user. For outgoing messages, specify true to show the keyboard only for the mentioned users and for the target user of a reply +func NewReplyMarkupShowKeyboard(rows [][]KeyboardButton, resizeKeyboard bool, oneTime bool, isPersonal bool) *ReplyMarkupShowKeyboard { + replyMarkupShowKeyboardTemp := ReplyMarkupShowKeyboard{ + tdCommon: tdCommon{Type: "replyMarkupShowKeyboard"}, + Rows: rows, + ResizeKeyboard: resizeKeyboard, + OneTime: oneTime, + IsPersonal: isPersonal, + } + + return &replyMarkupShowKeyboardTemp +} + +// GetReplyMarkupEnum return the enum type of this object +func (replyMarkupShowKeyboard *ReplyMarkupShowKeyboard) GetReplyMarkupEnum() ReplyMarkupEnum { + return ReplyMarkupShowKeyboardType +} + +// ReplyMarkupInlineKeyboard Contains an inline keyboard layout +type ReplyMarkupInlineKeyboard struct { + tdCommon + Rows [][]InlineKeyboardButton `json:"rows"` // A list of rows of inline keyboard buttons +} + +// MessageType return the string telegram-type of ReplyMarkupInlineKeyboard +func (replyMarkupInlineKeyboard *ReplyMarkupInlineKeyboard) MessageType() string { + return "replyMarkupInlineKeyboard" +} + +// NewReplyMarkupInlineKeyboard creates a new ReplyMarkupInlineKeyboard +// +// @param rows A list of rows of inline keyboard buttons +func NewReplyMarkupInlineKeyboard(rows [][]InlineKeyboardButton) *ReplyMarkupInlineKeyboard { + replyMarkupInlineKeyboardTemp := ReplyMarkupInlineKeyboard{ + tdCommon: tdCommon{Type: "replyMarkupInlineKeyboard"}, + Rows: rows, + } + + return &replyMarkupInlineKeyboardTemp +} + +// GetReplyMarkupEnum return the enum type of this object +func (replyMarkupInlineKeyboard *ReplyMarkupInlineKeyboard) GetReplyMarkupEnum() ReplyMarkupEnum { + return ReplyMarkupInlineKeyboardType +} + +// RichTextPlain A plain text +type RichTextPlain struct { + tdCommon + Text string `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextPlain +func (richTextPlain *RichTextPlain) MessageType() string { + return "richTextPlain" +} + +// NewRichTextPlain creates a new RichTextPlain +// +// @param text Text +func NewRichTextPlain(text string) *RichTextPlain { + richTextPlainTemp := RichTextPlain{ + tdCommon: tdCommon{Type: "richTextPlain"}, + Text: text, + } + + return &richTextPlainTemp +} + +// GetRichTextEnum return the enum type of this object +func (richTextPlain *RichTextPlain) GetRichTextEnum() RichTextEnum { + return RichTextPlainType +} + +// RichTextBold A bold rich text +type RichTextBold struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextBold +func (richTextBold *RichTextBold) MessageType() string { + return "richTextBold" +} + +// NewRichTextBold creates a new RichTextBold +// +// @param text Text +func NewRichTextBold(text RichText) *RichTextBold { + richTextBoldTemp := RichTextBold{ + tdCommon: tdCommon{Type: "richTextBold"}, + Text: text, + } + + return &richTextBoldTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextBold *RichTextBold) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextBold.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextBold.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextBold *RichTextBold) GetRichTextEnum() RichTextEnum { + return RichTextBoldType +} + +// RichTextItalic An italicized rich text +type RichTextItalic struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextItalic +func (richTextItalic *RichTextItalic) MessageType() string { + return "richTextItalic" +} + +// NewRichTextItalic creates a new RichTextItalic +// +// @param text Text +func NewRichTextItalic(text RichText) *RichTextItalic { + richTextItalicTemp := RichTextItalic{ + tdCommon: tdCommon{Type: "richTextItalic"}, + Text: text, + } + + return &richTextItalicTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextItalic *RichTextItalic) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextItalic.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextItalic.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextItalic *RichTextItalic) GetRichTextEnum() RichTextEnum { + return RichTextItalicType +} + +// RichTextUnderline An underlined rich text +type RichTextUnderline struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextUnderline +func (richTextUnderline *RichTextUnderline) MessageType() string { + return "richTextUnderline" +} + +// NewRichTextUnderline creates a new RichTextUnderline +// +// @param text Text +func NewRichTextUnderline(text RichText) *RichTextUnderline { + richTextUnderlineTemp := RichTextUnderline{ + tdCommon: tdCommon{Type: "richTextUnderline"}, + Text: text, + } + + return &richTextUnderlineTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextUnderline *RichTextUnderline) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextUnderline.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextUnderline.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextUnderline *RichTextUnderline) GetRichTextEnum() RichTextEnum { + return RichTextUnderlineType +} + +// RichTextStrikethrough A strike-through rich text +type RichTextStrikethrough struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextStrikethrough +func (richTextStrikethrough *RichTextStrikethrough) MessageType() string { + return "richTextStrikethrough" +} + +// NewRichTextStrikethrough creates a new RichTextStrikethrough +// +// @param text Text +func NewRichTextStrikethrough(text RichText) *RichTextStrikethrough { + richTextStrikethroughTemp := RichTextStrikethrough{ + tdCommon: tdCommon{Type: "richTextStrikethrough"}, + Text: text, + } + + return &richTextStrikethroughTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextStrikethrough *RichTextStrikethrough) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextStrikethrough.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextStrikethrough.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextStrikethrough *RichTextStrikethrough) GetRichTextEnum() RichTextEnum { + return RichTextStrikethroughType +} + +// RichTextFixed A fixed-width rich text +type RichTextFixed struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextFixed +func (richTextFixed *RichTextFixed) MessageType() string { + return "richTextFixed" +} + +// NewRichTextFixed creates a new RichTextFixed +// +// @param text Text +func NewRichTextFixed(text RichText) *RichTextFixed { + richTextFixedTemp := RichTextFixed{ + tdCommon: tdCommon{Type: "richTextFixed"}, + Text: text, + } + + return &richTextFixedTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextFixed *RichTextFixed) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextFixed.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextFixed.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextFixed *RichTextFixed) GetRichTextEnum() RichTextEnum { + return RichTextFixedType +} + +// RichTextURL A rich text URL link +type RichTextURL struct { + tdCommon + Text RichText `json:"text"` // Text + URL string `json:"url"` // URL +} + +// MessageType return the string telegram-type of RichTextURL +func (richTextURL *RichTextURL) MessageType() string { + return "richTextUrl" +} + +// NewRichTextURL creates a new RichTextURL +// +// @param text Text +// @param uRL URL +func NewRichTextURL(text RichText, uRL string) *RichTextURL { + richTextURLTemp := RichTextURL{ + tdCommon: tdCommon{Type: "richTextUrl"}, + Text: text, + URL: uRL, + } + + return &richTextURLTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextURL *RichTextURL) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + URL string `json:"url"` // URL + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextURL.tdCommon = tempObj.tdCommon + richTextURL.URL = tempObj.URL + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextURL.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextURL *RichTextURL) GetRichTextEnum() RichTextEnum { + return RichTextURLType +} + +// RichTextEmailAddress A rich text email link +type RichTextEmailAddress struct { + tdCommon + Text RichText `json:"text"` // Text + EmailAddress string `json:"email_address"` // Email address +} + +// MessageType return the string telegram-type of RichTextEmailAddress +func (richTextEmailAddress *RichTextEmailAddress) MessageType() string { + return "richTextEmailAddress" +} + +// NewRichTextEmailAddress creates a new RichTextEmailAddress +// +// @param text Text +// @param emailAddress Email address +func NewRichTextEmailAddress(text RichText, emailAddress string) *RichTextEmailAddress { + richTextEmailAddressTemp := RichTextEmailAddress{ + tdCommon: tdCommon{Type: "richTextEmailAddress"}, + Text: text, + EmailAddress: emailAddress, + } + + return &richTextEmailAddressTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextEmailAddress *RichTextEmailAddress) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + EmailAddress string `json:"email_address"` // Email address + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextEmailAddress.tdCommon = tempObj.tdCommon + richTextEmailAddress.EmailAddress = tempObj.EmailAddress + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextEmailAddress.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextEmailAddress *RichTextEmailAddress) GetRichTextEnum() RichTextEnum { + return RichTextEmailAddressType +} + +// RichTexts A concatenation of rich texts +type RichTexts struct { + tdCommon + Texts []RichText `json:"texts"` // Texts +} + +// MessageType return the string telegram-type of RichTexts +func (richTexts *RichTexts) MessageType() string { + return "richTexts" +} + +// NewRichTexts creates a new RichTexts +// +// @param texts Texts +func NewRichTexts(texts []RichText) *RichTexts { + richTextsTemp := RichTexts{ + tdCommon: tdCommon{Type: "richTexts"}, + Texts: texts, + } + + return &richTextsTemp +} + +// GetRichTextEnum return the enum type of this object +func (richTexts *RichTexts) GetRichTextEnum() RichTextEnum { + return RichTextsType +} + +// PageBlockTitle The title of a page +type PageBlockTitle struct { + tdCommon + Title RichText `json:"title"` // Title +} + +// MessageType return the string telegram-type of PageBlockTitle +func (pageBlockTitle *PageBlockTitle) MessageType() string { + return "pageBlockTitle" +} + +// NewPageBlockTitle creates a new PageBlockTitle +// +// @param title Title +func NewPageBlockTitle(title RichText) *PageBlockTitle { + pageBlockTitleTemp := PageBlockTitle{ + tdCommon: tdCommon{Type: "pageBlockTitle"}, + Title: title, + } + + return &pageBlockTitleTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockTitle *PageBlockTitle) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockTitle.tdCommon = tempObj.tdCommon + + fieldTitle, _ := unmarshalRichText(objMap["title"]) + pageBlockTitle.Title = fieldTitle + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockTitle *PageBlockTitle) GetPageBlockEnum() PageBlockEnum { + return PageBlockTitleType +} + +// PageBlockSubtitle The subtitle of a page +type PageBlockSubtitle struct { + tdCommon + Subtitle RichText `json:"subtitle"` // Subtitle +} + +// MessageType return the string telegram-type of PageBlockSubtitle +func (pageBlockSubtitle *PageBlockSubtitle) MessageType() string { + return "pageBlockSubtitle" +} + +// NewPageBlockSubtitle creates a new PageBlockSubtitle +// +// @param subtitle Subtitle +func NewPageBlockSubtitle(subtitle RichText) *PageBlockSubtitle { + pageBlockSubtitleTemp := PageBlockSubtitle{ + tdCommon: tdCommon{Type: "pageBlockSubtitle"}, + Subtitle: subtitle, + } + + return &pageBlockSubtitleTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockSubtitle *PageBlockSubtitle) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockSubtitle.tdCommon = tempObj.tdCommon + + fieldSubtitle, _ := unmarshalRichText(objMap["subtitle"]) + pageBlockSubtitle.Subtitle = fieldSubtitle + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockSubtitle *PageBlockSubtitle) GetPageBlockEnum() PageBlockEnum { + return PageBlockSubtitleType +} + +// PageBlockAuthorDate The author and publishing date of a page +type PageBlockAuthorDate struct { + tdCommon + Author RichText `json:"author"` // Author + PublishDate int32 `json:"publish_date"` // Point in time (Unix timestamp) when the article was published; 0 if unknown +} + +// MessageType return the string telegram-type of PageBlockAuthorDate +func (pageBlockAuthorDate *PageBlockAuthorDate) MessageType() string { + return "pageBlockAuthorDate" +} + +// NewPageBlockAuthorDate creates a new PageBlockAuthorDate +// +// @param author Author +// @param publishDate Point in time (Unix timestamp) when the article was published; 0 if unknown +func NewPageBlockAuthorDate(author RichText, publishDate int32) *PageBlockAuthorDate { + pageBlockAuthorDateTemp := PageBlockAuthorDate{ + tdCommon: tdCommon{Type: "pageBlockAuthorDate"}, + Author: author, + PublishDate: publishDate, + } + + return &pageBlockAuthorDateTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockAuthorDate *PageBlockAuthorDate) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + PublishDate int32 `json:"publish_date"` // Point in time (Unix timestamp) when the article was published; 0 if unknown + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockAuthorDate.tdCommon = tempObj.tdCommon + pageBlockAuthorDate.PublishDate = tempObj.PublishDate + + fieldAuthor, _ := unmarshalRichText(objMap["author"]) + pageBlockAuthorDate.Author = fieldAuthor + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockAuthorDate *PageBlockAuthorDate) GetPageBlockEnum() PageBlockEnum { + return PageBlockAuthorDateType +} + +// PageBlockHeader A header +type PageBlockHeader struct { + tdCommon + Header RichText `json:"header"` // Header +} + +// MessageType return the string telegram-type of PageBlockHeader +func (pageBlockHeader *PageBlockHeader) MessageType() string { + return "pageBlockHeader" +} + +// NewPageBlockHeader creates a new PageBlockHeader +// +// @param header Header +func NewPageBlockHeader(header RichText) *PageBlockHeader { + pageBlockHeaderTemp := PageBlockHeader{ + tdCommon: tdCommon{Type: "pageBlockHeader"}, + Header: header, + } + + return &pageBlockHeaderTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockHeader *PageBlockHeader) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockHeader.tdCommon = tempObj.tdCommon + + fieldHeader, _ := unmarshalRichText(objMap["header"]) + pageBlockHeader.Header = fieldHeader + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockHeader *PageBlockHeader) GetPageBlockEnum() PageBlockEnum { + return PageBlockHeaderType +} + +// PageBlockSubheader A subheader +type PageBlockSubheader struct { + tdCommon + Subheader RichText `json:"subheader"` // Subheader +} + +// MessageType return the string telegram-type of PageBlockSubheader +func (pageBlockSubheader *PageBlockSubheader) MessageType() string { + return "pageBlockSubheader" +} + +// NewPageBlockSubheader creates a new PageBlockSubheader +// +// @param subheader Subheader +func NewPageBlockSubheader(subheader RichText) *PageBlockSubheader { + pageBlockSubheaderTemp := PageBlockSubheader{ + tdCommon: tdCommon{Type: "pageBlockSubheader"}, + Subheader: subheader, + } + + return &pageBlockSubheaderTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockSubheader *PageBlockSubheader) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockSubheader.tdCommon = tempObj.tdCommon + + fieldSubheader, _ := unmarshalRichText(objMap["subheader"]) + pageBlockSubheader.Subheader = fieldSubheader + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockSubheader *PageBlockSubheader) GetPageBlockEnum() PageBlockEnum { + return PageBlockSubheaderType +} + +// PageBlockParagraph A text paragraph +type PageBlockParagraph struct { + tdCommon + Text RichText `json:"text"` // Paragraph text +} + +// MessageType return the string telegram-type of PageBlockParagraph +func (pageBlockParagraph *PageBlockParagraph) MessageType() string { + return "pageBlockParagraph" +} + +// NewPageBlockParagraph creates a new PageBlockParagraph +// +// @param text Paragraph text +func NewPageBlockParagraph(text RichText) *PageBlockParagraph { + pageBlockParagraphTemp := PageBlockParagraph{ + tdCommon: tdCommon{Type: "pageBlockParagraph"}, + Text: text, + } + + return &pageBlockParagraphTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockParagraph *PageBlockParagraph) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockParagraph.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + pageBlockParagraph.Text = fieldText + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockParagraph *PageBlockParagraph) GetPageBlockEnum() PageBlockEnum { + return PageBlockParagraphType +} + +// PageBlockPreformatted A preformatted text paragraph +type PageBlockPreformatted struct { + tdCommon + Text RichText `json:"text"` // Paragraph text + Language string `json:"language"` // Programming language for which the text should be formatted +} + +// MessageType return the string telegram-type of PageBlockPreformatted +func (pageBlockPreformatted *PageBlockPreformatted) MessageType() string { + return "pageBlockPreformatted" +} + +// NewPageBlockPreformatted creates a new PageBlockPreformatted +// +// @param text Paragraph text +// @param language Programming language for which the text should be formatted +func NewPageBlockPreformatted(text RichText, language string) *PageBlockPreformatted { + pageBlockPreformattedTemp := PageBlockPreformatted{ + tdCommon: tdCommon{Type: "pageBlockPreformatted"}, + Text: text, + Language: language, + } + + return &pageBlockPreformattedTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockPreformatted *PageBlockPreformatted) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Language string `json:"language"` // Programming language for which the text should be formatted + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockPreformatted.tdCommon = tempObj.tdCommon + pageBlockPreformatted.Language = tempObj.Language + + fieldText, _ := unmarshalRichText(objMap["text"]) + pageBlockPreformatted.Text = fieldText + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockPreformatted *PageBlockPreformatted) GetPageBlockEnum() PageBlockEnum { + return PageBlockPreformattedType +} + +// PageBlockFooter The footer of a page +type PageBlockFooter struct { + tdCommon + Footer RichText `json:"footer"` // Footer +} + +// MessageType return the string telegram-type of PageBlockFooter +func (pageBlockFooter *PageBlockFooter) MessageType() string { + return "pageBlockFooter" +} + +// NewPageBlockFooter creates a new PageBlockFooter +// +// @param footer Footer +func NewPageBlockFooter(footer RichText) *PageBlockFooter { + pageBlockFooterTemp := PageBlockFooter{ + tdCommon: tdCommon{Type: "pageBlockFooter"}, + Footer: footer, + } + + return &pageBlockFooterTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockFooter *PageBlockFooter) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockFooter.tdCommon = tempObj.tdCommon + + fieldFooter, _ := unmarshalRichText(objMap["footer"]) + pageBlockFooter.Footer = fieldFooter + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockFooter *PageBlockFooter) GetPageBlockEnum() PageBlockEnum { + return PageBlockFooterType +} + +// PageBlockDivider An empty block separating a page +type PageBlockDivider struct { + tdCommon +} + +// MessageType return the string telegram-type of PageBlockDivider +func (pageBlockDivider *PageBlockDivider) MessageType() string { + return "pageBlockDivider" +} + +// NewPageBlockDivider creates a new PageBlockDivider +// +func NewPageBlockDivider() *PageBlockDivider { + pageBlockDividerTemp := PageBlockDivider{ + tdCommon: tdCommon{Type: "pageBlockDivider"}, + } + + return &pageBlockDividerTemp +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockDivider *PageBlockDivider) GetPageBlockEnum() PageBlockEnum { + return PageBlockDividerType +} + +// PageBlockAnchor An invisible anchor on a page, which can be used in a URL to open the page from the specified anchor +type PageBlockAnchor struct { + tdCommon + Name string `json:"name"` // Name of the anchor +} + +// MessageType return the string telegram-type of PageBlockAnchor +func (pageBlockAnchor *PageBlockAnchor) MessageType() string { + return "pageBlockAnchor" +} + +// NewPageBlockAnchor creates a new PageBlockAnchor +// +// @param name Name of the anchor +func NewPageBlockAnchor(name string) *PageBlockAnchor { + pageBlockAnchorTemp := PageBlockAnchor{ + tdCommon: tdCommon{Type: "pageBlockAnchor"}, + Name: name, + } + + return &pageBlockAnchorTemp +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockAnchor *PageBlockAnchor) GetPageBlockEnum() PageBlockEnum { + return PageBlockAnchorType +} + +// PageBlockList A list of texts +type PageBlockList struct { + tdCommon + Items []RichText `json:"items"` // Texts + IsOrdered bool `json:"is_ordered"` // True, if the items should be marked with numbers +} + +// MessageType return the string telegram-type of PageBlockList +func (pageBlockList *PageBlockList) MessageType() string { + return "pageBlockList" +} + +// NewPageBlockList creates a new PageBlockList +// +// @param items Texts +// @param isOrdered True, if the items should be marked with numbers +func NewPageBlockList(items []RichText, isOrdered bool) *PageBlockList { + pageBlockListTemp := PageBlockList{ + tdCommon: tdCommon{Type: "pageBlockList"}, + Items: items, + IsOrdered: isOrdered, + } + + return &pageBlockListTemp +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockList *PageBlockList) GetPageBlockEnum() PageBlockEnum { + return PageBlockListType +} + +// PageBlockBlockQuote A block quote +type PageBlockBlockQuote struct { + tdCommon + Text RichText `json:"text"` // Quote text + Caption RichText `json:"caption"` // Quote caption +} + +// MessageType return the string telegram-type of PageBlockBlockQuote +func (pageBlockBlockQuote *PageBlockBlockQuote) MessageType() string { + return "pageBlockBlockQuote" +} + +// NewPageBlockBlockQuote creates a new PageBlockBlockQuote +// +// @param text Quote text +// @param caption Quote caption +func NewPageBlockBlockQuote(text RichText, caption RichText) *PageBlockBlockQuote { + pageBlockBlockQuoteTemp := PageBlockBlockQuote{ + tdCommon: tdCommon{Type: "pageBlockBlockQuote"}, + Text: text, + Caption: caption, + } + + return &pageBlockBlockQuoteTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockBlockQuote *PageBlockBlockQuote) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockBlockQuote.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + pageBlockBlockQuote.Text = fieldText + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockBlockQuote.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockBlockQuote *PageBlockBlockQuote) GetPageBlockEnum() PageBlockEnum { + return PageBlockBlockQuoteType +} + +// PageBlockPullQuote A pull quote +type PageBlockPullQuote struct { + tdCommon + Text RichText `json:"text"` // Quote text + Caption RichText `json:"caption"` // Quote caption +} + +// MessageType return the string telegram-type of PageBlockPullQuote +func (pageBlockPullQuote *PageBlockPullQuote) MessageType() string { + return "pageBlockPullQuote" +} + +// NewPageBlockPullQuote creates a new PageBlockPullQuote +// +// @param text Quote text +// @param caption Quote caption +func NewPageBlockPullQuote(text RichText, caption RichText) *PageBlockPullQuote { + pageBlockPullQuoteTemp := PageBlockPullQuote{ + tdCommon: tdCommon{Type: "pageBlockPullQuote"}, + Text: text, + Caption: caption, + } + + return &pageBlockPullQuoteTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockPullQuote *PageBlockPullQuote) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockPullQuote.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + pageBlockPullQuote.Text = fieldText + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockPullQuote.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockPullQuote *PageBlockPullQuote) GetPageBlockEnum() PageBlockEnum { + return PageBlockPullQuoteType +} + +// PageBlockAnimation An animation +type PageBlockAnimation struct { + tdCommon + Animation *Animation `json:"animation"` // Animation file; may be null + Caption RichText `json:"caption"` // Animation caption + NeedAutoplay bool `json:"need_autoplay"` // True, if the animation should be played automatically +} + +// MessageType return the string telegram-type of PageBlockAnimation +func (pageBlockAnimation *PageBlockAnimation) MessageType() string { + return "pageBlockAnimation" +} + +// NewPageBlockAnimation creates a new PageBlockAnimation +// +// @param animation Animation file; may be null +// @param caption Animation caption +// @param needAutoplay True, if the animation should be played automatically +func NewPageBlockAnimation(animation *Animation, caption RichText, needAutoplay bool) *PageBlockAnimation { + pageBlockAnimationTemp := PageBlockAnimation{ + tdCommon: tdCommon{Type: "pageBlockAnimation"}, + Animation: animation, + Caption: caption, + NeedAutoplay: needAutoplay, + } + + return &pageBlockAnimationTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockAnimation *PageBlockAnimation) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Animation *Animation `json:"animation"` // Animation file; may be null + NeedAutoplay bool `json:"need_autoplay"` // True, if the animation should be played automatically + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockAnimation.tdCommon = tempObj.tdCommon + pageBlockAnimation.Animation = tempObj.Animation + pageBlockAnimation.NeedAutoplay = tempObj.NeedAutoplay + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockAnimation.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockAnimation *PageBlockAnimation) GetPageBlockEnum() PageBlockEnum { + return PageBlockAnimationType +} + +// PageBlockAudio An audio file +type PageBlockAudio struct { + tdCommon + Audio *Audio `json:"audio"` // Audio file; may be null + Caption RichText `json:"caption"` // Audio file caption +} + +// MessageType return the string telegram-type of PageBlockAudio +func (pageBlockAudio *PageBlockAudio) MessageType() string { + return "pageBlockAudio" +} + +// NewPageBlockAudio creates a new PageBlockAudio +// +// @param audio Audio file; may be null +// @param caption Audio file caption +func NewPageBlockAudio(audio *Audio, caption RichText) *PageBlockAudio { + pageBlockAudioTemp := PageBlockAudio{ + tdCommon: tdCommon{Type: "pageBlockAudio"}, + Audio: audio, + Caption: caption, + } + + return &pageBlockAudioTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockAudio *PageBlockAudio) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Audio *Audio `json:"audio"` // Audio file; may be null + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockAudio.tdCommon = tempObj.tdCommon + pageBlockAudio.Audio = tempObj.Audio + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockAudio.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockAudio *PageBlockAudio) GetPageBlockEnum() PageBlockEnum { + return PageBlockAudioType +} + +// PageBlockPhoto A photo +type PageBlockPhoto struct { + tdCommon + Photo *Photo `json:"photo"` // Photo file; may be null + Caption RichText `json:"caption"` // Photo caption +} + +// MessageType return the string telegram-type of PageBlockPhoto +func (pageBlockPhoto *PageBlockPhoto) MessageType() string { + return "pageBlockPhoto" +} + +// NewPageBlockPhoto creates a new PageBlockPhoto +// +// @param photo Photo file; may be null +// @param caption Photo caption +func NewPageBlockPhoto(photo *Photo, caption RichText) *PageBlockPhoto { + pageBlockPhotoTemp := PageBlockPhoto{ + tdCommon: tdCommon{Type: "pageBlockPhoto"}, + Photo: photo, + Caption: caption, + } + + return &pageBlockPhotoTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockPhoto *PageBlockPhoto) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Photo *Photo `json:"photo"` // Photo file; may be null + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockPhoto.tdCommon = tempObj.tdCommon + pageBlockPhoto.Photo = tempObj.Photo + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockPhoto.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockPhoto *PageBlockPhoto) GetPageBlockEnum() PageBlockEnum { + return PageBlockPhotoType +} + +// PageBlockVideo A video +type PageBlockVideo struct { + tdCommon + Video *Video `json:"video"` // Video file; may be null + Caption RichText `json:"caption"` // Video caption + NeedAutoplay bool `json:"need_autoplay"` // True, if the video should be played automatically + IsLooped bool `json:"is_looped"` // True, if the video should be looped +} + +// MessageType return the string telegram-type of PageBlockVideo +func (pageBlockVideo *PageBlockVideo) MessageType() string { + return "pageBlockVideo" +} + +// NewPageBlockVideo creates a new PageBlockVideo +// +// @param video Video file; may be null +// @param caption Video caption +// @param needAutoplay True, if the video should be played automatically +// @param isLooped True, if the video should be looped +func NewPageBlockVideo(video *Video, caption RichText, needAutoplay bool, isLooped bool) *PageBlockVideo { + pageBlockVideoTemp := PageBlockVideo{ + tdCommon: tdCommon{Type: "pageBlockVideo"}, + Video: video, + Caption: caption, + NeedAutoplay: needAutoplay, + IsLooped: isLooped, + } + + return &pageBlockVideoTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockVideo *PageBlockVideo) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Video *Video `json:"video"` // Video file; may be null + NeedAutoplay bool `json:"need_autoplay"` // True, if the video should be played automatically + IsLooped bool `json:"is_looped"` // True, if the video should be looped + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockVideo.tdCommon = tempObj.tdCommon + pageBlockVideo.Video = tempObj.Video + pageBlockVideo.NeedAutoplay = tempObj.NeedAutoplay + pageBlockVideo.IsLooped = tempObj.IsLooped + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockVideo.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockVideo *PageBlockVideo) GetPageBlockEnum() PageBlockEnum { + return PageBlockVideoType +} + +// PageBlockCover A page cover +type PageBlockCover struct { + tdCommon + Cover PageBlock `json:"cover"` // Cover +} + +// MessageType return the string telegram-type of PageBlockCover +func (pageBlockCover *PageBlockCover) MessageType() string { + return "pageBlockCover" +} + +// NewPageBlockCover creates a new PageBlockCover +// +// @param cover Cover +func NewPageBlockCover(cover PageBlock) *PageBlockCover { + pageBlockCoverTemp := PageBlockCover{ + tdCommon: tdCommon{Type: "pageBlockCover"}, + Cover: cover, + } + + return &pageBlockCoverTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockCover *PageBlockCover) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockCover.tdCommon = tempObj.tdCommon + + fieldCover, _ := unmarshalPageBlock(objMap["cover"]) + pageBlockCover.Cover = fieldCover + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockCover *PageBlockCover) GetPageBlockEnum() PageBlockEnum { + return PageBlockCoverType +} + +// PageBlockEmbedded An embedded web page +type PageBlockEmbedded struct { + tdCommon + URL string `json:"url"` // Web page URL, if available + HTML string `json:"html"` // HTML-markup of the embedded page + PosterPhoto *Photo `json:"poster_photo"` // Poster photo, if available; may be null + Width int32 `json:"width"` // Block width + Height int32 `json:"height"` // Block height + Caption RichText `json:"caption"` // Block caption + IsFullWidth bool `json:"is_full_width"` // True, if the block should be full width + AllowScrolling bool `json:"allow_scrolling"` // True, if scrolling should be allowed +} + +// MessageType return the string telegram-type of PageBlockEmbedded +func (pageBlockEmbedded *PageBlockEmbedded) MessageType() string { + return "pageBlockEmbedded" +} + +// NewPageBlockEmbedded creates a new PageBlockEmbedded +// +// @param uRL Web page URL, if available +// @param hTML HTML-markup of the embedded page +// @param posterPhoto Poster photo, if available; may be null +// @param width Block width +// @param height Block height +// @param caption Block caption +// @param isFullWidth True, if the block should be full width +// @param allowScrolling True, if scrolling should be allowed +func NewPageBlockEmbedded(uRL string, hTML string, posterPhoto *Photo, width int32, height int32, caption RichText, isFullWidth bool, allowScrolling bool) *PageBlockEmbedded { + pageBlockEmbeddedTemp := PageBlockEmbedded{ + tdCommon: tdCommon{Type: "pageBlockEmbedded"}, + URL: uRL, + HTML: hTML, + PosterPhoto: posterPhoto, + Width: width, + Height: height, + Caption: caption, + IsFullWidth: isFullWidth, + AllowScrolling: allowScrolling, + } + + return &pageBlockEmbeddedTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockEmbedded *PageBlockEmbedded) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + URL string `json:"url"` // Web page URL, if available + HTML string `json:"html"` // HTML-markup of the embedded page + PosterPhoto *Photo `json:"poster_photo"` // Poster photo, if available; may be null + Width int32 `json:"width"` // Block width + Height int32 `json:"height"` // Block height + IsFullWidth bool `json:"is_full_width"` // True, if the block should be full width + AllowScrolling bool `json:"allow_scrolling"` // True, if scrolling should be allowed + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockEmbedded.tdCommon = tempObj.tdCommon + pageBlockEmbedded.URL = tempObj.URL + pageBlockEmbedded.HTML = tempObj.HTML + pageBlockEmbedded.PosterPhoto = tempObj.PosterPhoto + pageBlockEmbedded.Width = tempObj.Width + pageBlockEmbedded.Height = tempObj.Height + pageBlockEmbedded.IsFullWidth = tempObj.IsFullWidth + pageBlockEmbedded.AllowScrolling = tempObj.AllowScrolling + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockEmbedded.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockEmbedded *PageBlockEmbedded) GetPageBlockEnum() PageBlockEnum { + return PageBlockEmbeddedType +} + +// PageBlockEmbeddedPost An embedded post +type PageBlockEmbeddedPost struct { + tdCommon + URL string `json:"url"` // Web page URL + Author string `json:"author"` // Post author + AuthorPhoto *Photo `json:"author_photo"` // Post author photo + Date int32 `json:"date"` // Point in time (Unix timestamp) when the post was created; 0 if unknown + PageBlocks []PageBlock `json:"page_blocks"` // Post content + Caption RichText `json:"caption"` // Post caption +} + +// MessageType return the string telegram-type of PageBlockEmbeddedPost +func (pageBlockEmbeddedPost *PageBlockEmbeddedPost) MessageType() string { + return "pageBlockEmbeddedPost" +} + +// NewPageBlockEmbeddedPost creates a new PageBlockEmbeddedPost +// +// @param uRL Web page URL +// @param author Post author +// @param authorPhoto Post author photo +// @param date Point in time (Unix timestamp) when the post was created; 0 if unknown +// @param pageBlocks Post content +// @param caption Post caption +func NewPageBlockEmbeddedPost(uRL string, author string, authorPhoto *Photo, date int32, pageBlocks []PageBlock, caption RichText) *PageBlockEmbeddedPost { + pageBlockEmbeddedPostTemp := PageBlockEmbeddedPost{ + tdCommon: tdCommon{Type: "pageBlockEmbeddedPost"}, + URL: uRL, + Author: author, + AuthorPhoto: authorPhoto, + Date: date, + PageBlocks: pageBlocks, + Caption: caption, + } + + return &pageBlockEmbeddedPostTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockEmbeddedPost *PageBlockEmbeddedPost) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + URL string `json:"url"` // Web page URL + Author string `json:"author"` // Post author + AuthorPhoto *Photo `json:"author_photo"` // Post author photo + Date int32 `json:"date"` // Point in time (Unix timestamp) when the post was created; 0 if unknown + PageBlocks []PageBlock `json:"page_blocks"` // Post content + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockEmbeddedPost.tdCommon = tempObj.tdCommon + pageBlockEmbeddedPost.URL = tempObj.URL + pageBlockEmbeddedPost.Author = tempObj.Author + pageBlockEmbeddedPost.AuthorPhoto = tempObj.AuthorPhoto + pageBlockEmbeddedPost.Date = tempObj.Date + pageBlockEmbeddedPost.PageBlocks = tempObj.PageBlocks + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockEmbeddedPost.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockEmbeddedPost *PageBlockEmbeddedPost) GetPageBlockEnum() PageBlockEnum { + return PageBlockEmbeddedPostType +} + +// PageBlockCollage A collage +type PageBlockCollage struct { + tdCommon + PageBlocks []PageBlock `json:"page_blocks"` // Collage item contents + Caption RichText `json:"caption"` // Block caption +} + +// MessageType return the string telegram-type of PageBlockCollage +func (pageBlockCollage *PageBlockCollage) MessageType() string { + return "pageBlockCollage" +} + +// NewPageBlockCollage creates a new PageBlockCollage +// +// @param pageBlocks Collage item contents +// @param caption Block caption +func NewPageBlockCollage(pageBlocks []PageBlock, caption RichText) *PageBlockCollage { + pageBlockCollageTemp := PageBlockCollage{ + tdCommon: tdCommon{Type: "pageBlockCollage"}, + PageBlocks: pageBlocks, + Caption: caption, + } + + return &pageBlockCollageTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockCollage *PageBlockCollage) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + PageBlocks []PageBlock `json:"page_blocks"` // Collage item contents + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockCollage.tdCommon = tempObj.tdCommon + pageBlockCollage.PageBlocks = tempObj.PageBlocks + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockCollage.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockCollage *PageBlockCollage) GetPageBlockEnum() PageBlockEnum { + return PageBlockCollageType +} + +// PageBlockSlideshow A slideshow +type PageBlockSlideshow struct { + tdCommon + PageBlocks []PageBlock `json:"page_blocks"` // Slideshow item contents + Caption RichText `json:"caption"` // Block caption +} + +// MessageType return the string telegram-type of PageBlockSlideshow +func (pageBlockSlideshow *PageBlockSlideshow) MessageType() string { + return "pageBlockSlideshow" +} + +// NewPageBlockSlideshow creates a new PageBlockSlideshow +// +// @param pageBlocks Slideshow item contents +// @param caption Block caption +func NewPageBlockSlideshow(pageBlocks []PageBlock, caption RichText) *PageBlockSlideshow { + pageBlockSlideshowTemp := PageBlockSlideshow{ + tdCommon: tdCommon{Type: "pageBlockSlideshow"}, + PageBlocks: pageBlocks, + Caption: caption, + } + + return &pageBlockSlideshowTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockSlideshow *PageBlockSlideshow) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + PageBlocks []PageBlock `json:"page_blocks"` // Slideshow item contents + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockSlideshow.tdCommon = tempObj.tdCommon + pageBlockSlideshow.PageBlocks = tempObj.PageBlocks + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockSlideshow.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockSlideshow *PageBlockSlideshow) GetPageBlockEnum() PageBlockEnum { + return PageBlockSlideshowType +} + +// PageBlockChatLink A link to a chat +type PageBlockChatLink struct { + tdCommon + Title string `json:"title"` // Chat title + Photo *ChatPhoto `json:"photo"` // Chat photo; may be null + Username string `json:"username"` // Chat username, by which all other information about the chat should be resolved +} + +// MessageType return the string telegram-type of PageBlockChatLink +func (pageBlockChatLink *PageBlockChatLink) MessageType() string { + return "pageBlockChatLink" +} + +// NewPageBlockChatLink creates a new PageBlockChatLink +// +// @param title Chat title +// @param photo Chat photo; may be null +// @param username Chat username, by which all other information about the chat should be resolved +func NewPageBlockChatLink(title string, photo *ChatPhoto, username string) *PageBlockChatLink { + pageBlockChatLinkTemp := PageBlockChatLink{ + tdCommon: tdCommon{Type: "pageBlockChatLink"}, + Title: title, + Photo: photo, + Username: username, + } + + return &pageBlockChatLinkTemp +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockChatLink *PageBlockChatLink) GetPageBlockEnum() PageBlockEnum { + return PageBlockChatLinkType +} + +// WebPageInstantView Describes an instant view page for a web page +type WebPageInstantView struct { + tdCommon + PageBlocks []PageBlock `json:"page_blocks"` // Content of the web page + IsFull bool `json:"is_full"` // True, if the instant view contains the full page. A network request might be needed to get the full web page instant view +} + +// MessageType return the string telegram-type of WebPageInstantView +func (webPageInstantView *WebPageInstantView) MessageType() string { + return "webPageInstantView" +} + +// NewWebPageInstantView creates a new WebPageInstantView +// +// @param pageBlocks Content of the web page +// @param isFull True, if the instant view contains the full page. A network request might be needed to get the full web page instant view +func NewWebPageInstantView(pageBlocks []PageBlock, isFull bool) *WebPageInstantView { + webPageInstantViewTemp := WebPageInstantView{ + tdCommon: tdCommon{Type: "webPageInstantView"}, + PageBlocks: pageBlocks, + IsFull: isFull, + } + + return &webPageInstantViewTemp +} + +// WebPage Describes a web page preview +type WebPage struct { + tdCommon + URL string `json:"url"` // Original URL of the link + DisplayURL string `json:"display_url"` // URL to display + Type string `json:"type"` // Type of the web page. Can be: article, photo, audio, video, document, profile, app, or something else + SiteName string `json:"site_name"` // Short name of the site (e.g., Google Docs, App Store) + Title string `json:"title"` // Title of the content + Description string `json:"description"` // + Photo *Photo `json:"photo"` // Image representing the content; may be null + EmbedURL string `json:"embed_url"` // URL to show in the embedded preview + EmbedType string `json:"embed_type"` // MIME type of the embedded preview, (e.g., text/html or video/mp4) + EmbedWidth int32 `json:"embed_width"` // Width of the embedded preview + EmbedHeight int32 `json:"embed_height"` // Height of the embedded preview + Duration int32 `json:"duration"` // Duration of the content, in seconds + Author string `json:"author"` // Author of the content + Animation *Animation `json:"animation"` // Preview of the content as an animation, if available; may be null + Audio *Audio `json:"audio"` // Preview of the content as an audio file, if available; may be null + Document *Document `json:"document"` // Preview of the content as a document, if available (currently only available for small PDF files and ZIP archives); may be null + Sticker *Sticker `json:"sticker"` // Preview of the content as a sticker for small WEBP files, if available; may be null + Video *Video `json:"video"` // Preview of the content as a video, if available; may be null + VideoNote *VideoNote `json:"video_note"` // Preview of the content as a video note, if available; may be null + VoiceNote *VoiceNote `json:"voice_note"` // Preview of the content as a voice note, if available; may be null + HasInstantView bool `json:"has_instant_view"` // True, if the web page has an instant view +} + +// MessageType return the string telegram-type of WebPage +func (webPage *WebPage) MessageType() string { + return "webPage" +} + +// NewWebPage creates a new WebPage +// +// @param uRL Original URL of the link +// @param displayURL URL to display +// @param typeParam Type of the web page. Can be: article, photo, audio, video, document, profile, app, or something else +// @param siteName Short name of the site (e.g., Google Docs, App Store) +// @param title Title of the content +// @param description +// @param photo Image representing the content; may be null +// @param embedURL URL to show in the embedded preview +// @param embedType MIME type of the embedded preview, (e.g., text/html or video/mp4) +// @param embedWidth Width of the embedded preview +// @param embedHeight Height of the embedded preview +// @param duration Duration of the content, in seconds +// @param author Author of the content +// @param animation Preview of the content as an animation, if available; may be null +// @param audio Preview of the content as an audio file, if available; may be null +// @param document Preview of the content as a document, if available (currently only available for small PDF files and ZIP archives); may be null +// @param sticker Preview of the content as a sticker for small WEBP files, if available; may be null +// @param video Preview of the content as a video, if available; may be null +// @param videoNote Preview of the content as a video note, if available; may be null +// @param voiceNote Preview of the content as a voice note, if available; may be null +// @param hasInstantView True, if the web page has an instant view +func NewWebPage(uRL string, displayURL string, typeParam string, siteName string, title string, description string, photo *Photo, embedURL string, embedType string, embedWidth int32, embedHeight int32, duration int32, author string, animation *Animation, audio *Audio, document *Document, sticker *Sticker, video *Video, videoNote *VideoNote, voiceNote *VoiceNote, hasInstantView bool) *WebPage { + webPageTemp := WebPage{ + tdCommon: tdCommon{Type: "webPage"}, + URL: uRL, + DisplayURL: displayURL, + Type: typeParam, + SiteName: siteName, + Title: title, + Description: description, + Photo: photo, + EmbedURL: embedURL, + EmbedType: embedType, + EmbedWidth: embedWidth, + EmbedHeight: embedHeight, + Duration: duration, + Author: author, + Animation: animation, + Audio: audio, + Document: document, + Sticker: sticker, + Video: video, + VideoNote: videoNote, + VoiceNote: voiceNote, + HasInstantView: hasInstantView, + } + + return &webPageTemp +} + +// Address Describes an address +type Address struct { + tdCommon + CountryCode string `json:"country_code"` // A two-letter ISO 3166-1 alpha-2 country code + State string `json:"state"` // State, if applicable + City string `json:"city"` // City + StreetLine1 string `json:"street_line1"` // First line of the address + StreetLine2 string `json:"street_line2"` // Second line of the address + PostalCode string `json:"postal_code"` // Address postal code +} + +// MessageType return the string telegram-type of Address +func (address *Address) MessageType() string { + return "address" +} + +// NewAddress creates a new Address +// +// @param countryCode A two-letter ISO 3166-1 alpha-2 country code +// @param state State, if applicable +// @param city City +// @param streetLine1 First line of the address +// @param streetLine2 Second line of the address +// @param postalCode Address postal code +func NewAddress(countryCode string, state string, city string, streetLine1 string, streetLine2 string, postalCode string) *Address { + addressTemp := Address{ + tdCommon: tdCommon{Type: "address"}, + CountryCode: countryCode, + State: state, + City: city, + StreetLine1: streetLine1, + StreetLine2: streetLine2, + PostalCode: postalCode, + } + + return &addressTemp +} + +// LabeledPricePart Portion of the price of a product (e.g., "delivery cost", "tax amount") +type LabeledPricePart struct { + tdCommon + Label string `json:"label"` // Label for this portion of the product price + Amount int64 `json:"amount"` // Currency amount in minimal quantity of the currency +} + +// MessageType return the string telegram-type of LabeledPricePart +func (labeledPricePart *LabeledPricePart) MessageType() string { + return "labeledPricePart" +} + +// NewLabeledPricePart creates a new LabeledPricePart +// +// @param label Label for this portion of the product price +// @param amount Currency amount in minimal quantity of the currency +func NewLabeledPricePart(label string, amount int64) *LabeledPricePart { + labeledPricePartTemp := LabeledPricePart{ + tdCommon: tdCommon{Type: "labeledPricePart"}, + Label: label, + Amount: amount, + } + + return &labeledPricePartTemp +} + +// Invoice Product invoice +type Invoice struct { + tdCommon + Currency string `json:"currency"` // ISO 4217 currency code + PriceParts []LabeledPricePart `json:"price_parts"` // A list of objects used to calculate the total price of the product + IsTest bool `json:"is_test"` // True, if the payment is a test payment + NeedName bool `json:"need_name"` // True, if the user's name is needed for payment + NeedPhoneNumber bool `json:"need_phone_number"` // True, if the user's phone number is needed for payment + NeedEmailAddress bool `json:"need_email_address"` // True, if the user's email address is needed for payment + NeedShippingAddress bool `json:"need_shipping_address"` // True, if the user's shipping address is needed for payment + SendPhoneNumberToProvider bool `json:"send_phone_number_to_provider"` // True, if the user's phone number will be sent to the provider + SendEmailAddressToProvider bool `json:"send_email_address_to_provider"` // True, if the user's email address will be sent to the provider + IsFlexible bool `json:"is_flexible"` // True, if the total price depends on the shipping method +} + +// MessageType return the string telegram-type of Invoice +func (invoice *Invoice) MessageType() string { + return "invoice" +} + +// NewInvoice creates a new Invoice +// +// @param currency ISO 4217 currency code +// @param priceParts A list of objects used to calculate the total price of the product +// @param isTest True, if the payment is a test payment +// @param needName True, if the user's name is needed for payment +// @param needPhoneNumber True, if the user's phone number is needed for payment +// @param needEmailAddress True, if the user's email address is needed for payment +// @param needShippingAddress True, if the user's shipping address is needed for payment +// @param sendPhoneNumberToProvider True, if the user's phone number will be sent to the provider +// @param sendEmailAddressToProvider True, if the user's email address will be sent to the provider +// @param isFlexible True, if the total price depends on the shipping method +func NewInvoice(currency string, priceParts []LabeledPricePart, isTest bool, needName bool, needPhoneNumber bool, needEmailAddress bool, needShippingAddress bool, sendPhoneNumberToProvider bool, sendEmailAddressToProvider bool, isFlexible bool) *Invoice { + invoiceTemp := Invoice{ + tdCommon: tdCommon{Type: "invoice"}, + Currency: currency, + PriceParts: priceParts, + IsTest: isTest, + NeedName: needName, + NeedPhoneNumber: needPhoneNumber, + NeedEmailAddress: needEmailAddress, + NeedShippingAddress: needShippingAddress, + SendPhoneNumberToProvider: sendPhoneNumberToProvider, + SendEmailAddressToProvider: sendEmailAddressToProvider, + IsFlexible: isFlexible, + } + + return &invoiceTemp +} + +// OrderInfo Order information +type OrderInfo struct { + tdCommon + Name string `json:"name"` // Name of the user + PhoneNumber string `json:"phone_number"` // Phone number of the user + EmailAddress string `json:"email_address"` // Email address of the user + ShippingAddress *Address `json:"shipping_address"` // Shipping address for this order; may be null +} + +// MessageType return the string telegram-type of OrderInfo +func (orderInfo *OrderInfo) MessageType() string { + return "orderInfo" +} + +// NewOrderInfo creates a new OrderInfo +// +// @param name Name of the user +// @param phoneNumber Phone number of the user +// @param emailAddress Email address of the user +// @param shippingAddress Shipping address for this order; may be null +func NewOrderInfo(name string, phoneNumber string, emailAddress string, shippingAddress *Address) *OrderInfo { + orderInfoTemp := OrderInfo{ + tdCommon: tdCommon{Type: "orderInfo"}, + Name: name, + PhoneNumber: phoneNumber, + EmailAddress: emailAddress, + ShippingAddress: shippingAddress, + } + + return &orderInfoTemp +} + +// ShippingOption One shipping option +type ShippingOption struct { + tdCommon + ID string `json:"id"` // Shipping option identifier + Title string `json:"title"` // Option title + PriceParts []LabeledPricePart `json:"price_parts"` // A list of objects used to calculate the total shipping costs +} + +// MessageType return the string telegram-type of ShippingOption +func (shippingOption *ShippingOption) MessageType() string { + return "shippingOption" +} + +// NewShippingOption creates a new ShippingOption +// +// @param iD Shipping option identifier +// @param title Option title +// @param priceParts A list of objects used to calculate the total shipping costs +func NewShippingOption(iD string, title string, priceParts []LabeledPricePart) *ShippingOption { + shippingOptionTemp := ShippingOption{ + tdCommon: tdCommon{Type: "shippingOption"}, + ID: iD, + Title: title, + PriceParts: priceParts, + } + + return &shippingOptionTemp +} + +// SavedCredentials Contains information about saved card credentials +type SavedCredentials struct { + tdCommon + ID string `json:"id"` // Unique identifier of the saved credentials + Title string `json:"title"` // Title of the saved credentials +} + +// MessageType return the string telegram-type of SavedCredentials +func (savedCredentials *SavedCredentials) MessageType() string { + return "savedCredentials" +} + +// NewSavedCredentials creates a new SavedCredentials +// +// @param iD Unique identifier of the saved credentials +// @param title Title of the saved credentials +func NewSavedCredentials(iD string, title string) *SavedCredentials { + savedCredentialsTemp := SavedCredentials{ + tdCommon: tdCommon{Type: "savedCredentials"}, + ID: iD, + Title: title, + } + + return &savedCredentialsTemp +} + +// InputCredentialsSaved Applies if a user chooses some previously saved payment credentials. To use their previously saved credentials, the user must have a valid temporary password +type InputCredentialsSaved struct { + tdCommon + SavedCredentialsID string `json:"saved_credentials_id"` // Identifier of the saved credentials +} + +// MessageType return the string telegram-type of InputCredentialsSaved +func (inputCredentialsSaved *InputCredentialsSaved) MessageType() string { + return "inputCredentialsSaved" +} + +// NewInputCredentialsSaved creates a new InputCredentialsSaved +// +// @param savedCredentialsID Identifier of the saved credentials +func NewInputCredentialsSaved(savedCredentialsID string) *InputCredentialsSaved { + inputCredentialsSavedTemp := InputCredentialsSaved{ + tdCommon: tdCommon{Type: "inputCredentialsSaved"}, + SavedCredentialsID: savedCredentialsID, + } + + return &inputCredentialsSavedTemp +} + +// GetInputCredentialsEnum return the enum type of this object +func (inputCredentialsSaved *InputCredentialsSaved) GetInputCredentialsEnum() InputCredentialsEnum { + return InputCredentialsSavedType +} + +// InputCredentialsNew Applies if a user enters new credentials on a payment provider website +type InputCredentialsNew struct { + tdCommon + Data string `json:"data"` // Contains JSON-encoded data with a credential identifier from the payment provider + AllowSave bool `json:"allow_save"` // True, if the credential identifier can be saved on the server side +} + +// MessageType return the string telegram-type of InputCredentialsNew +func (inputCredentialsNew *InputCredentialsNew) MessageType() string { + return "inputCredentialsNew" +} + +// NewInputCredentialsNew creates a new InputCredentialsNew +// +// @param data Contains JSON-encoded data with a credential identifier from the payment provider +// @param allowSave True, if the credential identifier can be saved on the server side +func NewInputCredentialsNew(data string, allowSave bool) *InputCredentialsNew { + inputCredentialsNewTemp := InputCredentialsNew{ + tdCommon: tdCommon{Type: "inputCredentialsNew"}, + Data: data, + AllowSave: allowSave, + } + + return &inputCredentialsNewTemp +} + +// GetInputCredentialsEnum return the enum type of this object +func (inputCredentialsNew *InputCredentialsNew) GetInputCredentialsEnum() InputCredentialsEnum { + return InputCredentialsNewType +} + +// InputCredentialsAndroidPay Applies if a user enters new credentials using Android Pay +type InputCredentialsAndroidPay struct { + tdCommon + Data string `json:"data"` // JSON-encoded data with the credential identifier +} + +// MessageType return the string telegram-type of InputCredentialsAndroidPay +func (inputCredentialsAndroidPay *InputCredentialsAndroidPay) MessageType() string { + return "inputCredentialsAndroidPay" +} + +// NewInputCredentialsAndroidPay creates a new InputCredentialsAndroidPay +// +// @param data JSON-encoded data with the credential identifier +func NewInputCredentialsAndroidPay(data string) *InputCredentialsAndroidPay { + inputCredentialsAndroidPayTemp := InputCredentialsAndroidPay{ + tdCommon: tdCommon{Type: "inputCredentialsAndroidPay"}, + Data: data, + } + + return &inputCredentialsAndroidPayTemp +} + +// GetInputCredentialsEnum return the enum type of this object +func (inputCredentialsAndroidPay *InputCredentialsAndroidPay) GetInputCredentialsEnum() InputCredentialsEnum { + return InputCredentialsAndroidPayType +} + +// InputCredentialsApplePay Applies if a user enters new credentials using Apple Pay +type InputCredentialsApplePay struct { + tdCommon + Data string `json:"data"` // JSON-encoded data with the credential identifier +} + +// MessageType return the string telegram-type of InputCredentialsApplePay +func (inputCredentialsApplePay *InputCredentialsApplePay) MessageType() string { + return "inputCredentialsApplePay" +} + +// NewInputCredentialsApplePay creates a new InputCredentialsApplePay +// +// @param data JSON-encoded data with the credential identifier +func NewInputCredentialsApplePay(data string) *InputCredentialsApplePay { + inputCredentialsApplePayTemp := InputCredentialsApplePay{ + tdCommon: tdCommon{Type: "inputCredentialsApplePay"}, + Data: data, + } + + return &inputCredentialsApplePayTemp +} + +// GetInputCredentialsEnum return the enum type of this object +func (inputCredentialsApplePay *InputCredentialsApplePay) GetInputCredentialsEnum() InputCredentialsEnum { + return InputCredentialsApplePayType +} + +// PaymentsProviderStripe Stripe payment provider +type PaymentsProviderStripe struct { + tdCommon + PublishableKey string `json:"publishable_key"` // Stripe API publishable key + NeedCountry bool `json:"need_country"` // True, if the user country must be provided + NeedPostalCode bool `json:"need_postal_code"` // True, if the user ZIP/postal code must be provided + NeedCardholderName bool `json:"need_cardholder_name"` // True, if the cardholder name must be provided +} + +// MessageType return the string telegram-type of PaymentsProviderStripe +func (paymentsProviderStripe *PaymentsProviderStripe) MessageType() string { + return "paymentsProviderStripe" +} + +// NewPaymentsProviderStripe creates a new PaymentsProviderStripe +// +// @param publishableKey Stripe API publishable key +// @param needCountry True, if the user country must be provided +// @param needPostalCode True, if the user ZIP/postal code must be provided +// @param needCardholderName True, if the cardholder name must be provided +func NewPaymentsProviderStripe(publishableKey string, needCountry bool, needPostalCode bool, needCardholderName bool) *PaymentsProviderStripe { + paymentsProviderStripeTemp := PaymentsProviderStripe{ + tdCommon: tdCommon{Type: "paymentsProviderStripe"}, + PublishableKey: publishableKey, + NeedCountry: needCountry, + NeedPostalCode: needPostalCode, + NeedCardholderName: needCardholderName, + } + + return &paymentsProviderStripeTemp +} + +// PaymentForm Contains information about an invoice payment form +type PaymentForm struct { + tdCommon + Invoice *Invoice `json:"invoice"` // Full information of the invoice + URL string `json:"url"` // Payment form URL + PaymentsProvider *PaymentsProviderStripe `json:"payments_provider"` // Contains information about the payment provider, if available, to support it natively without the need for opening the URL; may be null + SavedOrderInfo *OrderInfo `json:"saved_order_info"` // Saved server-side order information; may be null + SavedCredentials *SavedCredentials `json:"saved_credentials"` // Contains information about saved card credentials; may be null + CanSaveCredentials bool `json:"can_save_credentials"` // True, if the user can choose to save credentials + NeedPassword bool `json:"need_password"` // True, if the user will be able to save credentials protected by a password they set up +} + +// MessageType return the string telegram-type of PaymentForm +func (paymentForm *PaymentForm) MessageType() string { + return "paymentForm" +} + +// NewPaymentForm creates a new PaymentForm +// +// @param invoice Full information of the invoice +// @param uRL Payment form URL +// @param paymentsProvider Contains information about the payment provider, if available, to support it natively without the need for opening the URL; may be null +// @param savedOrderInfo Saved server-side order information; may be null +// @param savedCredentials Contains information about saved card credentials; may be null +// @param canSaveCredentials True, if the user can choose to save credentials +// @param needPassword True, if the user will be able to save credentials protected by a password they set up +func NewPaymentForm(invoice *Invoice, uRL string, paymentsProvider *PaymentsProviderStripe, savedOrderInfo *OrderInfo, savedCredentials *SavedCredentials, canSaveCredentials bool, needPassword bool) *PaymentForm { + paymentFormTemp := PaymentForm{ + tdCommon: tdCommon{Type: "paymentForm"}, + Invoice: invoice, + URL: uRL, + PaymentsProvider: paymentsProvider, + SavedOrderInfo: savedOrderInfo, + SavedCredentials: savedCredentials, + CanSaveCredentials: canSaveCredentials, + NeedPassword: needPassword, + } + + return &paymentFormTemp +} + +// ValidatedOrderInfo Contains a temporary identifier of validated order information, which is stored for one hour. Also contains the available shipping options +type ValidatedOrderInfo struct { + tdCommon + OrderInfoID string `json:"order_info_id"` // Temporary identifier of the order information + ShippingOptions []ShippingOption `json:"shipping_options"` // Available shipping options +} + +// MessageType return the string telegram-type of ValidatedOrderInfo +func (validatedOrderInfo *ValidatedOrderInfo) MessageType() string { + return "validatedOrderInfo" +} + +// NewValidatedOrderInfo creates a new ValidatedOrderInfo +// +// @param orderInfoID Temporary identifier of the order information +// @param shippingOptions Available shipping options +func NewValidatedOrderInfo(orderInfoID string, shippingOptions []ShippingOption) *ValidatedOrderInfo { + validatedOrderInfoTemp := ValidatedOrderInfo{ + tdCommon: tdCommon{Type: "validatedOrderInfo"}, + OrderInfoID: orderInfoID, + ShippingOptions: shippingOptions, + } + + return &validatedOrderInfoTemp +} + +// PaymentResult Contains the result of a payment request +type PaymentResult struct { + tdCommon + Success bool `json:"success"` // True, if the payment request was successful; otherwise the verification_url will be not empty + VerificationURL string `json:"verification_url"` // URL for additional payment credentials verification +} + +// MessageType return the string telegram-type of PaymentResult +func (paymentResult *PaymentResult) MessageType() string { + return "paymentResult" +} + +// NewPaymentResult creates a new PaymentResult +// +// @param success True, if the payment request was successful; otherwise the verification_url will be not empty +// @param verificationURL URL for additional payment credentials verification +func NewPaymentResult(success bool, verificationURL string) *PaymentResult { + paymentResultTemp := PaymentResult{ + tdCommon: tdCommon{Type: "paymentResult"}, + Success: success, + VerificationURL: verificationURL, + } + + return &paymentResultTemp +} + +// PaymentReceipt Contains information about a successful payment +type PaymentReceipt struct { + tdCommon + Date int32 `json:"date"` // Point in time (Unix timestamp) when the payment was made + PaymentsProviderUserID int32 `json:"payments_provider_user_id"` // User identifier of the payment provider bot + Invoice *Invoice `json:"invoice"` // Contains information about the invoice + OrderInfo *OrderInfo `json:"order_info"` // Contains order information; may be null + ShippingOption *ShippingOption `json:"shipping_option"` // Chosen shipping option; may be null + CredentialsTitle string `json:"credentials_title"` // Title of the saved credentials +} + +// MessageType return the string telegram-type of PaymentReceipt +func (paymentReceipt *PaymentReceipt) MessageType() string { + return "paymentReceipt" +} + +// NewPaymentReceipt creates a new PaymentReceipt +// +// @param date Point in time (Unix timestamp) when the payment was made +// @param paymentsProviderUserID User identifier of the payment provider bot +// @param invoice Contains information about the invoice +// @param orderInfo Contains order information; may be null +// @param shippingOption Chosen shipping option; may be null +// @param credentialsTitle Title of the saved credentials +func NewPaymentReceipt(date int32, paymentsProviderUserID int32, invoice *Invoice, orderInfo *OrderInfo, shippingOption *ShippingOption, credentialsTitle string) *PaymentReceipt { + paymentReceiptTemp := PaymentReceipt{ + tdCommon: tdCommon{Type: "paymentReceipt"}, + Date: date, + PaymentsProviderUserID: paymentsProviderUserID, + Invoice: invoice, + OrderInfo: orderInfo, + ShippingOption: shippingOption, + CredentialsTitle: credentialsTitle, + } + + return &paymentReceiptTemp +} + +// DatedFile File with the date it was uploaded +type DatedFile struct { + tdCommon + File *File `json:"file"` // The file + Date int32 `json:"date"` // Point in time (Unix timestamp) when the file was uploaded +} + +// MessageType return the string telegram-type of DatedFile +func (datedFile *DatedFile) MessageType() string { + return "datedFile" +} + +// NewDatedFile creates a new DatedFile +// +// @param file The file +// @param date Point in time (Unix timestamp) when the file was uploaded +func NewDatedFile(file *File, date int32) *DatedFile { + datedFileTemp := DatedFile{ + tdCommon: tdCommon{Type: "datedFile"}, + File: file, + Date: date, + } + + return &datedFileTemp +} + +// PassportElementTypePersonalDetails A Telegram Passport element containing the user's personal details +type PassportElementTypePersonalDetails struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypePersonalDetails +func (passportElementTypePersonalDetails *PassportElementTypePersonalDetails) MessageType() string { + return "passportElementTypePersonalDetails" +} + +// NewPassportElementTypePersonalDetails creates a new PassportElementTypePersonalDetails +// +func NewPassportElementTypePersonalDetails() *PassportElementTypePersonalDetails { + passportElementTypePersonalDetailsTemp := PassportElementTypePersonalDetails{ + tdCommon: tdCommon{Type: "passportElementTypePersonalDetails"}, + } + + return &passportElementTypePersonalDetailsTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypePersonalDetails *PassportElementTypePersonalDetails) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypePersonalDetailsType +} + +// PassportElementTypePassport A Telegram Passport element containing the user's passport +type PassportElementTypePassport struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypePassport +func (passportElementTypePassport *PassportElementTypePassport) MessageType() string { + return "passportElementTypePassport" +} + +// NewPassportElementTypePassport creates a new PassportElementTypePassport +// +func NewPassportElementTypePassport() *PassportElementTypePassport { + passportElementTypePassportTemp := PassportElementTypePassport{ + tdCommon: tdCommon{Type: "passportElementTypePassport"}, + } + + return &passportElementTypePassportTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypePassport *PassportElementTypePassport) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypePassportType +} + +// PassportElementTypeDriverLicense A Telegram Passport element containing the user's driver license +type PassportElementTypeDriverLicense struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeDriverLicense +func (passportElementTypeDriverLicense *PassportElementTypeDriverLicense) MessageType() string { + return "passportElementTypeDriverLicense" +} + +// NewPassportElementTypeDriverLicense creates a new PassportElementTypeDriverLicense +// +func NewPassportElementTypeDriverLicense() *PassportElementTypeDriverLicense { + passportElementTypeDriverLicenseTemp := PassportElementTypeDriverLicense{ + tdCommon: tdCommon{Type: "passportElementTypeDriverLicense"}, + } + + return &passportElementTypeDriverLicenseTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeDriverLicense *PassportElementTypeDriverLicense) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeDriverLicenseType +} + +// PassportElementTypeIDentityCard A Telegram Passport element containing the user's identity card +type PassportElementTypeIDentityCard struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeIDentityCard +func (passportElementTypeIDentityCard *PassportElementTypeIDentityCard) MessageType() string { + return "passportElementTypeIdentityCard" +} + +// NewPassportElementTypeIDentityCard creates a new PassportElementTypeIDentityCard +// +func NewPassportElementTypeIDentityCard() *PassportElementTypeIDentityCard { + passportElementTypeIDentityCardTemp := PassportElementTypeIDentityCard{ + tdCommon: tdCommon{Type: "passportElementTypeIdentityCard"}, + } + + return &passportElementTypeIDentityCardTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeIDentityCard *PassportElementTypeIDentityCard) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeIDentityCardType +} + +// PassportElementTypeInternalPassport A Telegram Passport element containing the user's internal passport +type PassportElementTypeInternalPassport struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeInternalPassport +func (passportElementTypeInternalPassport *PassportElementTypeInternalPassport) MessageType() string { + return "passportElementTypeInternalPassport" +} + +// NewPassportElementTypeInternalPassport creates a new PassportElementTypeInternalPassport +// +func NewPassportElementTypeInternalPassport() *PassportElementTypeInternalPassport { + passportElementTypeInternalPassportTemp := PassportElementTypeInternalPassport{ + tdCommon: tdCommon{Type: "passportElementTypeInternalPassport"}, + } + + return &passportElementTypeInternalPassportTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeInternalPassport *PassportElementTypeInternalPassport) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeInternalPassportType +} + +// PassportElementTypeAddress A Telegram Passport element containing the user's address +type PassportElementTypeAddress struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeAddress +func (passportElementTypeAddress *PassportElementTypeAddress) MessageType() string { + return "passportElementTypeAddress" +} + +// NewPassportElementTypeAddress creates a new PassportElementTypeAddress +// +func NewPassportElementTypeAddress() *PassportElementTypeAddress { + passportElementTypeAddressTemp := PassportElementTypeAddress{ + tdCommon: tdCommon{Type: "passportElementTypeAddress"}, + } + + return &passportElementTypeAddressTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeAddress *PassportElementTypeAddress) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeAddressType +} + +// PassportElementTypeUtilityBill A Telegram Passport element containing the user's utility bill +type PassportElementTypeUtilityBill struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeUtilityBill +func (passportElementTypeUtilityBill *PassportElementTypeUtilityBill) MessageType() string { + return "passportElementTypeUtilityBill" +} + +// NewPassportElementTypeUtilityBill creates a new PassportElementTypeUtilityBill +// +func NewPassportElementTypeUtilityBill() *PassportElementTypeUtilityBill { + passportElementTypeUtilityBillTemp := PassportElementTypeUtilityBill{ + tdCommon: tdCommon{Type: "passportElementTypeUtilityBill"}, + } + + return &passportElementTypeUtilityBillTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeUtilityBill *PassportElementTypeUtilityBill) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeUtilityBillType +} + +// PassportElementTypeBankStatement A Telegram Passport element containing the user's bank statement +type PassportElementTypeBankStatement struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeBankStatement +func (passportElementTypeBankStatement *PassportElementTypeBankStatement) MessageType() string { + return "passportElementTypeBankStatement" +} + +// NewPassportElementTypeBankStatement creates a new PassportElementTypeBankStatement +// +func NewPassportElementTypeBankStatement() *PassportElementTypeBankStatement { + passportElementTypeBankStatementTemp := PassportElementTypeBankStatement{ + tdCommon: tdCommon{Type: "passportElementTypeBankStatement"}, + } + + return &passportElementTypeBankStatementTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeBankStatement *PassportElementTypeBankStatement) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeBankStatementType +} + +// PassportElementTypeRentalAgreement A Telegram Passport element containing the user's rental agreement +type PassportElementTypeRentalAgreement struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeRentalAgreement +func (passportElementTypeRentalAgreement *PassportElementTypeRentalAgreement) MessageType() string { + return "passportElementTypeRentalAgreement" +} + +// NewPassportElementTypeRentalAgreement creates a new PassportElementTypeRentalAgreement +// +func NewPassportElementTypeRentalAgreement() *PassportElementTypeRentalAgreement { + passportElementTypeRentalAgreementTemp := PassportElementTypeRentalAgreement{ + tdCommon: tdCommon{Type: "passportElementTypeRentalAgreement"}, + } + + return &passportElementTypeRentalAgreementTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeRentalAgreement *PassportElementTypeRentalAgreement) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeRentalAgreementType +} + +// PassportElementTypePassportRegistration A Telegram Passport element containing the registration page of the user's passport +type PassportElementTypePassportRegistration struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypePassportRegistration +func (passportElementTypePassportRegistration *PassportElementTypePassportRegistration) MessageType() string { + return "passportElementTypePassportRegistration" +} + +// NewPassportElementTypePassportRegistration creates a new PassportElementTypePassportRegistration +// +func NewPassportElementTypePassportRegistration() *PassportElementTypePassportRegistration { + passportElementTypePassportRegistrationTemp := PassportElementTypePassportRegistration{ + tdCommon: tdCommon{Type: "passportElementTypePassportRegistration"}, + } + + return &passportElementTypePassportRegistrationTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypePassportRegistration *PassportElementTypePassportRegistration) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypePassportRegistrationType +} + +// PassportElementTypeTemporaryRegistration A Telegram Passport element containing the user's temporary registration +type PassportElementTypeTemporaryRegistration struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeTemporaryRegistration +func (passportElementTypeTemporaryRegistration *PassportElementTypeTemporaryRegistration) MessageType() string { + return "passportElementTypeTemporaryRegistration" +} + +// NewPassportElementTypeTemporaryRegistration creates a new PassportElementTypeTemporaryRegistration +// +func NewPassportElementTypeTemporaryRegistration() *PassportElementTypeTemporaryRegistration { + passportElementTypeTemporaryRegistrationTemp := PassportElementTypeTemporaryRegistration{ + tdCommon: tdCommon{Type: "passportElementTypeTemporaryRegistration"}, + } + + return &passportElementTypeTemporaryRegistrationTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeTemporaryRegistration *PassportElementTypeTemporaryRegistration) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeTemporaryRegistrationType +} + +// PassportElementTypePhoneNumber A Telegram Passport element containing the user's phone number +type PassportElementTypePhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypePhoneNumber +func (passportElementTypePhoneNumber *PassportElementTypePhoneNumber) MessageType() string { + return "passportElementTypePhoneNumber" +} + +// NewPassportElementTypePhoneNumber creates a new PassportElementTypePhoneNumber +// +func NewPassportElementTypePhoneNumber() *PassportElementTypePhoneNumber { + passportElementTypePhoneNumberTemp := PassportElementTypePhoneNumber{ + tdCommon: tdCommon{Type: "passportElementTypePhoneNumber"}, + } + + return &passportElementTypePhoneNumberTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypePhoneNumber *PassportElementTypePhoneNumber) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypePhoneNumberType +} + +// PassportElementTypeEmailAddress A Telegram Passport element containing the user's email address +type PassportElementTypeEmailAddress struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementTypeEmailAddress +func (passportElementTypeEmailAddress *PassportElementTypeEmailAddress) MessageType() string { + return "passportElementTypeEmailAddress" +} + +// NewPassportElementTypeEmailAddress creates a new PassportElementTypeEmailAddress +// +func NewPassportElementTypeEmailAddress() *PassportElementTypeEmailAddress { + passportElementTypeEmailAddressTemp := PassportElementTypeEmailAddress{ + tdCommon: tdCommon{Type: "passportElementTypeEmailAddress"}, + } + + return &passportElementTypeEmailAddressTemp +} + +// GetPassportElementTypeEnum return the enum type of this object +func (passportElementTypeEmailAddress *PassportElementTypeEmailAddress) GetPassportElementTypeEnum() PassportElementTypeEnum { + return PassportElementTypeEmailAddressType +} + +// Date Represents a date according to the Gregorian calendar +type Date struct { + tdCommon + Day int32 `json:"day"` // Day of the month, 1-31 + Month int32 `json:"month"` // Month, 1-12 + Year int32 `json:"year"` // Year, 1-9999 +} + +// MessageType return the string telegram-type of Date +func (date *Date) MessageType() string { + return "date" +} + +// NewDate creates a new Date +// +// @param day Day of the month, 1-31 +// @param month Month, 1-12 +// @param year Year, 1-9999 +func NewDate(day int32, month int32, year int32) *Date { + dateTemp := Date{ + tdCommon: tdCommon{Type: "date"}, + Day: day, + Month: month, + Year: year, + } + + return &dateTemp +} + +// PersonalDetails Contains the user's personal details +type PersonalDetails struct { + tdCommon + FirstName string `json:"first_name"` // First name of the user written in English; 1-255 characters + MiddleName string `json:"middle_name"` // Middle name of the user written in English; 0-255 characters + LastName string `json:"last_name"` // Last name of the user written in English; 1-255 characters + NativeFirstName string `json:"native_first_name"` // Native first name of the user; 1-255 characters + NativeMiddleName string `json:"native_middle_name"` // Native middle name of the user; 0-255 characters + NativeLastName string `json:"native_last_name"` // Native last name of the user; 1-255 characters + Birthdate *Date `json:"birthdate"` // Birthdate of the user + Gender string `json:"gender"` // Gender of the user, "male" or "female" + CountryCode string `json:"country_code"` // A two-letter ISO 3166-1 alpha-2 country code of the user's country + ResidenceCountryCode string `json:"residence_country_code"` // A two-letter ISO 3166-1 alpha-2 country code of the user's residence country +} + +// MessageType return the string telegram-type of PersonalDetails +func (personalDetails *PersonalDetails) MessageType() string { + return "personalDetails" +} + +// NewPersonalDetails creates a new PersonalDetails +// +// @param firstName First name of the user written in English; 1-255 characters +// @param middleName Middle name of the user written in English; 0-255 characters +// @param lastName Last name of the user written in English; 1-255 characters +// @param nativeFirstName Native first name of the user; 1-255 characters +// @param nativeMiddleName Native middle name of the user; 0-255 characters +// @param nativeLastName Native last name of the user; 1-255 characters +// @param birthdate Birthdate of the user +// @param gender Gender of the user, "male" or "female" +// @param countryCode A two-letter ISO 3166-1 alpha-2 country code of the user's country +// @param residenceCountryCode A two-letter ISO 3166-1 alpha-2 country code of the user's residence country +func NewPersonalDetails(firstName string, middleName string, lastName string, nativeFirstName string, nativeMiddleName string, nativeLastName string, birthdate *Date, gender string, countryCode string, residenceCountryCode string) *PersonalDetails { + personalDetailsTemp := PersonalDetails{ + tdCommon: tdCommon{Type: "personalDetails"}, + FirstName: firstName, + MiddleName: middleName, + LastName: lastName, + NativeFirstName: nativeFirstName, + NativeMiddleName: nativeMiddleName, + NativeLastName: nativeLastName, + Birthdate: birthdate, + Gender: gender, + CountryCode: countryCode, + ResidenceCountryCode: residenceCountryCode, + } + + return &personalDetailsTemp +} + +// IDentityDocument An identity document +type IDentityDocument struct { + tdCommon + Number string `json:"number"` // Document number; 1-24 characters + ExpiryDate *Date `json:"expiry_date"` // Document expiry date; may be null + FrontSide *DatedFile `json:"front_side"` // Front side of the document + ReverseSide *DatedFile `json:"reverse_side"` // Reverse side of the document; only for driver license and identity card + Selfie *DatedFile `json:"selfie"` // Selfie with the document; may be null + Translation []DatedFile `json:"translation"` // List of files containing a certified English translation of the document +} + +// MessageType return the string telegram-type of IDentityDocument +func (iDentityDocument *IDentityDocument) MessageType() string { + return "identityDocument" +} + +// NewIDentityDocument creates a new IDentityDocument +// +// @param number Document number; 1-24 characters +// @param expiryDate Document expiry date; may be null +// @param frontSide Front side of the document +// @param reverseSide Reverse side of the document; only for driver license and identity card +// @param selfie Selfie with the document; may be null +// @param translation List of files containing a certified English translation of the document +func NewIDentityDocument(number string, expiryDate *Date, frontSide *DatedFile, reverseSide *DatedFile, selfie *DatedFile, translation []DatedFile) *IDentityDocument { + iDentityDocumentTemp := IDentityDocument{ + tdCommon: tdCommon{Type: "identityDocument"}, + Number: number, + ExpiryDate: expiryDate, + FrontSide: frontSide, + ReverseSide: reverseSide, + Selfie: selfie, + Translation: translation, + } + + return &iDentityDocumentTemp +} + +// InputIDentityDocument An identity document to be saved to Telegram Passport +type InputIDentityDocument struct { + tdCommon + Number string `json:"number"` // Document number; 1-24 characters + ExpiryDate *Date `json:"expiry_date"` // Document expiry date, if available + FrontSide InputFile `json:"front_side"` // Front side of the document + ReverseSide InputFile `json:"reverse_side"` // Reverse side of the document; only for driver license and identity card + Selfie InputFile `json:"selfie"` // Selfie with the document, if available + Translation []InputFile `json:"translation"` // List of files containing a certified English translation of the document +} + +// MessageType return the string telegram-type of InputIDentityDocument +func (inputIDentityDocument *InputIDentityDocument) MessageType() string { + return "inputIdentityDocument" +} + +// NewInputIDentityDocument creates a new InputIDentityDocument +// +// @param number Document number; 1-24 characters +// @param expiryDate Document expiry date, if available +// @param frontSide Front side of the document +// @param reverseSide Reverse side of the document; only for driver license and identity card +// @param selfie Selfie with the document, if available +// @param translation List of files containing a certified English translation of the document +func NewInputIDentityDocument(number string, expiryDate *Date, frontSide InputFile, reverseSide InputFile, selfie InputFile, translation []InputFile) *InputIDentityDocument { + inputIDentityDocumentTemp := InputIDentityDocument{ + tdCommon: tdCommon{Type: "inputIdentityDocument"}, + Number: number, + ExpiryDate: expiryDate, + FrontSide: frontSide, + ReverseSide: reverseSide, + Selfie: selfie, + Translation: translation, + } + + return &inputIDentityDocumentTemp +} + +// UnmarshalJSON unmarshal to json +func (inputIDentityDocument *InputIDentityDocument) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Number string `json:"number"` // Document number; 1-24 characters + ExpiryDate *Date `json:"expiry_date"` // Document expiry date, if available + Translation []InputFile `json:"translation"` // List of files containing a certified English translation of the document + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputIDentityDocument.tdCommon = tempObj.tdCommon + inputIDentityDocument.Number = tempObj.Number + inputIDentityDocument.ExpiryDate = tempObj.ExpiryDate + inputIDentityDocument.Translation = tempObj.Translation + + fieldFrontSide, _ := unmarshalInputFile(objMap["front_side"]) + inputIDentityDocument.FrontSide = fieldFrontSide + + fieldReverseSide, _ := unmarshalInputFile(objMap["reverse_side"]) + inputIDentityDocument.ReverseSide = fieldReverseSide + + fieldSelfie, _ := unmarshalInputFile(objMap["selfie"]) + inputIDentityDocument.Selfie = fieldSelfie + + return nil +} + +// PersonalDocument A personal document, containing some information about a user +type PersonalDocument struct { + tdCommon + Files []DatedFile `json:"files"` // List of files containing the pages of the document + Translation []DatedFile `json:"translation"` // List of files containing a certified English translation of the document +} + +// MessageType return the string telegram-type of PersonalDocument +func (personalDocument *PersonalDocument) MessageType() string { + return "personalDocument" +} + +// NewPersonalDocument creates a new PersonalDocument +// +// @param files List of files containing the pages of the document +// @param translation List of files containing a certified English translation of the document +func NewPersonalDocument(files []DatedFile, translation []DatedFile) *PersonalDocument { + personalDocumentTemp := PersonalDocument{ + tdCommon: tdCommon{Type: "personalDocument"}, + Files: files, + Translation: translation, + } + + return &personalDocumentTemp +} + +// InputPersonalDocument A personal document to be saved to Telegram Passport +type InputPersonalDocument struct { + tdCommon + Files []InputFile `json:"files"` // List of files containing the pages of the document + Translation []InputFile `json:"translation"` // List of files containing a certified English translation of the document +} + +// MessageType return the string telegram-type of InputPersonalDocument +func (inputPersonalDocument *InputPersonalDocument) MessageType() string { + return "inputPersonalDocument" +} + +// NewInputPersonalDocument creates a new InputPersonalDocument +// +// @param files List of files containing the pages of the document +// @param translation List of files containing a certified English translation of the document +func NewInputPersonalDocument(files []InputFile, translation []InputFile) *InputPersonalDocument { + inputPersonalDocumentTemp := InputPersonalDocument{ + tdCommon: tdCommon{Type: "inputPersonalDocument"}, + Files: files, + Translation: translation, + } + + return &inputPersonalDocumentTemp +} + +// PassportElementPersonalDetails A Telegram Passport element containing the user's personal details +type PassportElementPersonalDetails struct { + tdCommon + PersonalDetails *PersonalDetails `json:"personal_details"` // Personal details of the user +} + +// MessageType return the string telegram-type of PassportElementPersonalDetails +func (passportElementPersonalDetails *PassportElementPersonalDetails) MessageType() string { + return "passportElementPersonalDetails" +} + +// NewPassportElementPersonalDetails creates a new PassportElementPersonalDetails +// +// @param personalDetails Personal details of the user +func NewPassportElementPersonalDetails(personalDetails *PersonalDetails) *PassportElementPersonalDetails { + passportElementPersonalDetailsTemp := PassportElementPersonalDetails{ + tdCommon: tdCommon{Type: "passportElementPersonalDetails"}, + PersonalDetails: personalDetails, + } + + return &passportElementPersonalDetailsTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementPersonalDetails *PassportElementPersonalDetails) GetPassportElementEnum() PassportElementEnum { + return PassportElementPersonalDetailsType +} + +// PassportElementPassport A Telegram Passport element containing the user's passport +type PassportElementPassport struct { + tdCommon + Passport *IDentityDocument `json:"passport"` // Passport +} + +// MessageType return the string telegram-type of PassportElementPassport +func (passportElementPassport *PassportElementPassport) MessageType() string { + return "passportElementPassport" +} + +// NewPassportElementPassport creates a new PassportElementPassport +// +// @param passport Passport +func NewPassportElementPassport(passport *IDentityDocument) *PassportElementPassport { + passportElementPassportTemp := PassportElementPassport{ + tdCommon: tdCommon{Type: "passportElementPassport"}, + Passport: passport, + } + + return &passportElementPassportTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementPassport *PassportElementPassport) GetPassportElementEnum() PassportElementEnum { + return PassportElementPassportType +} + +// PassportElementDriverLicense A Telegram Passport element containing the user's driver license +type PassportElementDriverLicense struct { + tdCommon + DriverLicense *IDentityDocument `json:"driver_license"` // Driver license +} + +// MessageType return the string telegram-type of PassportElementDriverLicense +func (passportElementDriverLicense *PassportElementDriverLicense) MessageType() string { + return "passportElementDriverLicense" +} + +// NewPassportElementDriverLicense creates a new PassportElementDriverLicense +// +// @param driverLicense Driver license +func NewPassportElementDriverLicense(driverLicense *IDentityDocument) *PassportElementDriverLicense { + passportElementDriverLicenseTemp := PassportElementDriverLicense{ + tdCommon: tdCommon{Type: "passportElementDriverLicense"}, + DriverLicense: driverLicense, + } + + return &passportElementDriverLicenseTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementDriverLicense *PassportElementDriverLicense) GetPassportElementEnum() PassportElementEnum { + return PassportElementDriverLicenseType +} + +// PassportElementIDentityCard A Telegram Passport element containing the user's identity card +type PassportElementIDentityCard struct { + tdCommon + IDentityCard *IDentityDocument `json:"identity_card"` // Identity card +} + +// MessageType return the string telegram-type of PassportElementIDentityCard +func (passportElementIDentityCard *PassportElementIDentityCard) MessageType() string { + return "passportElementIdentityCard" +} + +// NewPassportElementIDentityCard creates a new PassportElementIDentityCard +// +// @param iDentityCard Identity card +func NewPassportElementIDentityCard(iDentityCard *IDentityDocument) *PassportElementIDentityCard { + passportElementIDentityCardTemp := PassportElementIDentityCard{ + tdCommon: tdCommon{Type: "passportElementIdentityCard"}, + IDentityCard: iDentityCard, + } + + return &passportElementIDentityCardTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementIDentityCard *PassportElementIDentityCard) GetPassportElementEnum() PassportElementEnum { + return PassportElementIDentityCardType +} + +// PassportElementInternalPassport A Telegram Passport element containing the user's internal passport +type PassportElementInternalPassport struct { + tdCommon + InternalPassport *IDentityDocument `json:"internal_passport"` // Internal passport +} + +// MessageType return the string telegram-type of PassportElementInternalPassport +func (passportElementInternalPassport *PassportElementInternalPassport) MessageType() string { + return "passportElementInternalPassport" +} + +// NewPassportElementInternalPassport creates a new PassportElementInternalPassport +// +// @param internalPassport Internal passport +func NewPassportElementInternalPassport(internalPassport *IDentityDocument) *PassportElementInternalPassport { + passportElementInternalPassportTemp := PassportElementInternalPassport{ + tdCommon: tdCommon{Type: "passportElementInternalPassport"}, + InternalPassport: internalPassport, + } + + return &passportElementInternalPassportTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementInternalPassport *PassportElementInternalPassport) GetPassportElementEnum() PassportElementEnum { + return PassportElementInternalPassportType +} + +// PassportElementAddress A Telegram Passport element containing the user's address +type PassportElementAddress struct { + tdCommon + Address *Address `json:"address"` // Address +} + +// MessageType return the string telegram-type of PassportElementAddress +func (passportElementAddress *PassportElementAddress) MessageType() string { + return "passportElementAddress" +} + +// NewPassportElementAddress creates a new PassportElementAddress +// +// @param address Address +func NewPassportElementAddress(address *Address) *PassportElementAddress { + passportElementAddressTemp := PassportElementAddress{ + tdCommon: tdCommon{Type: "passportElementAddress"}, + Address: address, + } + + return &passportElementAddressTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementAddress *PassportElementAddress) GetPassportElementEnum() PassportElementEnum { + return PassportElementAddressType +} + +// PassportElementUtilityBill A Telegram Passport element containing the user's utility bill +type PassportElementUtilityBill struct { + tdCommon + UtilityBill *PersonalDocument `json:"utility_bill"` // Utility bill +} + +// MessageType return the string telegram-type of PassportElementUtilityBill +func (passportElementUtilityBill *PassportElementUtilityBill) MessageType() string { + return "passportElementUtilityBill" +} + +// NewPassportElementUtilityBill creates a new PassportElementUtilityBill +// +// @param utilityBill Utility bill +func NewPassportElementUtilityBill(utilityBill *PersonalDocument) *PassportElementUtilityBill { + passportElementUtilityBillTemp := PassportElementUtilityBill{ + tdCommon: tdCommon{Type: "passportElementUtilityBill"}, + UtilityBill: utilityBill, + } + + return &passportElementUtilityBillTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementUtilityBill *PassportElementUtilityBill) GetPassportElementEnum() PassportElementEnum { + return PassportElementUtilityBillType +} + +// PassportElementBankStatement A Telegram Passport element containing the user's bank statement +type PassportElementBankStatement struct { + tdCommon + BankStatement *PersonalDocument `json:"bank_statement"` // Bank statement +} + +// MessageType return the string telegram-type of PassportElementBankStatement +func (passportElementBankStatement *PassportElementBankStatement) MessageType() string { + return "passportElementBankStatement" +} + +// NewPassportElementBankStatement creates a new PassportElementBankStatement +// +// @param bankStatement Bank statement +func NewPassportElementBankStatement(bankStatement *PersonalDocument) *PassportElementBankStatement { + passportElementBankStatementTemp := PassportElementBankStatement{ + tdCommon: tdCommon{Type: "passportElementBankStatement"}, + BankStatement: bankStatement, + } + + return &passportElementBankStatementTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementBankStatement *PassportElementBankStatement) GetPassportElementEnum() PassportElementEnum { + return PassportElementBankStatementType +} + +// PassportElementRentalAgreement A Telegram Passport element containing the user's rental agreement +type PassportElementRentalAgreement struct { + tdCommon + RentalAgreement *PersonalDocument `json:"rental_agreement"` // Rental agreement +} + +// MessageType return the string telegram-type of PassportElementRentalAgreement +func (passportElementRentalAgreement *PassportElementRentalAgreement) MessageType() string { + return "passportElementRentalAgreement" +} + +// NewPassportElementRentalAgreement creates a new PassportElementRentalAgreement +// +// @param rentalAgreement Rental agreement +func NewPassportElementRentalAgreement(rentalAgreement *PersonalDocument) *PassportElementRentalAgreement { + passportElementRentalAgreementTemp := PassportElementRentalAgreement{ + tdCommon: tdCommon{Type: "passportElementRentalAgreement"}, + RentalAgreement: rentalAgreement, + } + + return &passportElementRentalAgreementTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementRentalAgreement *PassportElementRentalAgreement) GetPassportElementEnum() PassportElementEnum { + return PassportElementRentalAgreementType +} + +// PassportElementPassportRegistration A Telegram Passport element containing the user's passport registration pages +type PassportElementPassportRegistration struct { + tdCommon + PassportRegistration *PersonalDocument `json:"passport_registration"` // Passport registration pages +} + +// MessageType return the string telegram-type of PassportElementPassportRegistration +func (passportElementPassportRegistration *PassportElementPassportRegistration) MessageType() string { + return "passportElementPassportRegistration" +} + +// NewPassportElementPassportRegistration creates a new PassportElementPassportRegistration +// +// @param passportRegistration Passport registration pages +func NewPassportElementPassportRegistration(passportRegistration *PersonalDocument) *PassportElementPassportRegistration { + passportElementPassportRegistrationTemp := PassportElementPassportRegistration{ + tdCommon: tdCommon{Type: "passportElementPassportRegistration"}, + PassportRegistration: passportRegistration, + } + + return &passportElementPassportRegistrationTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementPassportRegistration *PassportElementPassportRegistration) GetPassportElementEnum() PassportElementEnum { + return PassportElementPassportRegistrationType +} + +// PassportElementTemporaryRegistration A Telegram Passport element containing the user's temporary registration +type PassportElementTemporaryRegistration struct { + tdCommon + TemporaryRegistration *PersonalDocument `json:"temporary_registration"` // Temporary registration +} + +// MessageType return the string telegram-type of PassportElementTemporaryRegistration +func (passportElementTemporaryRegistration *PassportElementTemporaryRegistration) MessageType() string { + return "passportElementTemporaryRegistration" +} + +// NewPassportElementTemporaryRegistration creates a new PassportElementTemporaryRegistration +// +// @param temporaryRegistration Temporary registration +func NewPassportElementTemporaryRegistration(temporaryRegistration *PersonalDocument) *PassportElementTemporaryRegistration { + passportElementTemporaryRegistrationTemp := PassportElementTemporaryRegistration{ + tdCommon: tdCommon{Type: "passportElementTemporaryRegistration"}, + TemporaryRegistration: temporaryRegistration, + } + + return &passportElementTemporaryRegistrationTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementTemporaryRegistration *PassportElementTemporaryRegistration) GetPassportElementEnum() PassportElementEnum { + return PassportElementTemporaryRegistrationType +} + +// PassportElementPhoneNumber A Telegram Passport element containing the user's phone number +type PassportElementPhoneNumber struct { + tdCommon + PhoneNumber string `json:"phone_number"` // Phone number +} + +// MessageType return the string telegram-type of PassportElementPhoneNumber +func (passportElementPhoneNumber *PassportElementPhoneNumber) MessageType() string { + return "passportElementPhoneNumber" +} + +// NewPassportElementPhoneNumber creates a new PassportElementPhoneNumber +// +// @param phoneNumber Phone number +func NewPassportElementPhoneNumber(phoneNumber string) *PassportElementPhoneNumber { + passportElementPhoneNumberTemp := PassportElementPhoneNumber{ + tdCommon: tdCommon{Type: "passportElementPhoneNumber"}, + PhoneNumber: phoneNumber, + } + + return &passportElementPhoneNumberTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementPhoneNumber *PassportElementPhoneNumber) GetPassportElementEnum() PassportElementEnum { + return PassportElementPhoneNumberType +} + +// PassportElementEmailAddress A Telegram Passport element containing the user's email address +type PassportElementEmailAddress struct { + tdCommon + EmailAddress string `json:"email_address"` // Email address +} + +// MessageType return the string telegram-type of PassportElementEmailAddress +func (passportElementEmailAddress *PassportElementEmailAddress) MessageType() string { + return "passportElementEmailAddress" +} + +// NewPassportElementEmailAddress creates a new PassportElementEmailAddress +// +// @param emailAddress Email address +func NewPassportElementEmailAddress(emailAddress string) *PassportElementEmailAddress { + passportElementEmailAddressTemp := PassportElementEmailAddress{ + tdCommon: tdCommon{Type: "passportElementEmailAddress"}, + EmailAddress: emailAddress, + } + + return &passportElementEmailAddressTemp +} + +// GetPassportElementEnum return the enum type of this object +func (passportElementEmailAddress *PassportElementEmailAddress) GetPassportElementEnum() PassportElementEnum { + return PassportElementEmailAddressType +} + +// InputPassportElementPersonalDetails A Telegram Passport element to be saved containing the user's personal details +type InputPassportElementPersonalDetails struct { + tdCommon + PersonalDetails *PersonalDetails `json:"personal_details"` // Personal details of the user +} + +// MessageType return the string telegram-type of InputPassportElementPersonalDetails +func (inputPassportElementPersonalDetails *InputPassportElementPersonalDetails) MessageType() string { + return "inputPassportElementPersonalDetails" +} + +// NewInputPassportElementPersonalDetails creates a new InputPassportElementPersonalDetails +// +// @param personalDetails Personal details of the user +func NewInputPassportElementPersonalDetails(personalDetails *PersonalDetails) *InputPassportElementPersonalDetails { + inputPassportElementPersonalDetailsTemp := InputPassportElementPersonalDetails{ + tdCommon: tdCommon{Type: "inputPassportElementPersonalDetails"}, + PersonalDetails: personalDetails, + } + + return &inputPassportElementPersonalDetailsTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementPersonalDetails *InputPassportElementPersonalDetails) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementPersonalDetailsType +} + +// InputPassportElementPassport A Telegram Passport element to be saved containing the user's passport +type InputPassportElementPassport struct { + tdCommon + Passport *InputIDentityDocument `json:"passport"` // The passport to be saved +} + +// MessageType return the string telegram-type of InputPassportElementPassport +func (inputPassportElementPassport *InputPassportElementPassport) MessageType() string { + return "inputPassportElementPassport" +} + +// NewInputPassportElementPassport creates a new InputPassportElementPassport +// +// @param passport The passport to be saved +func NewInputPassportElementPassport(passport *InputIDentityDocument) *InputPassportElementPassport { + inputPassportElementPassportTemp := InputPassportElementPassport{ + tdCommon: tdCommon{Type: "inputPassportElementPassport"}, + Passport: passport, + } + + return &inputPassportElementPassportTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementPassport *InputPassportElementPassport) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementPassportType +} + +// InputPassportElementDriverLicense A Telegram Passport element to be saved containing the user's driver license +type InputPassportElementDriverLicense struct { + tdCommon + DriverLicense *InputIDentityDocument `json:"driver_license"` // The driver license to be saved +} + +// MessageType return the string telegram-type of InputPassportElementDriverLicense +func (inputPassportElementDriverLicense *InputPassportElementDriverLicense) MessageType() string { + return "inputPassportElementDriverLicense" +} + +// NewInputPassportElementDriverLicense creates a new InputPassportElementDriverLicense +// +// @param driverLicense The driver license to be saved +func NewInputPassportElementDriverLicense(driverLicense *InputIDentityDocument) *InputPassportElementDriverLicense { + inputPassportElementDriverLicenseTemp := InputPassportElementDriverLicense{ + tdCommon: tdCommon{Type: "inputPassportElementDriverLicense"}, + DriverLicense: driverLicense, + } + + return &inputPassportElementDriverLicenseTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementDriverLicense *InputPassportElementDriverLicense) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementDriverLicenseType +} + +// InputPassportElementIDentityCard A Telegram Passport element to be saved containing the user's identity card +type InputPassportElementIDentityCard struct { + tdCommon + IDentityCard *InputIDentityDocument `json:"identity_card"` // The identity card to be saved +} + +// MessageType return the string telegram-type of InputPassportElementIDentityCard +func (inputPassportElementIDentityCard *InputPassportElementIDentityCard) MessageType() string { + return "inputPassportElementIdentityCard" +} + +// NewInputPassportElementIDentityCard creates a new InputPassportElementIDentityCard +// +// @param iDentityCard The identity card to be saved +func NewInputPassportElementIDentityCard(iDentityCard *InputIDentityDocument) *InputPassportElementIDentityCard { + inputPassportElementIDentityCardTemp := InputPassportElementIDentityCard{ + tdCommon: tdCommon{Type: "inputPassportElementIdentityCard"}, + IDentityCard: iDentityCard, + } + + return &inputPassportElementIDentityCardTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementIDentityCard *InputPassportElementIDentityCard) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementIDentityCardType +} + +// InputPassportElementInternalPassport A Telegram Passport element to be saved containing the user's internal passport +type InputPassportElementInternalPassport struct { + tdCommon + InternalPassport *InputIDentityDocument `json:"internal_passport"` // The internal passport to be saved +} + +// MessageType return the string telegram-type of InputPassportElementInternalPassport +func (inputPassportElementInternalPassport *InputPassportElementInternalPassport) MessageType() string { + return "inputPassportElementInternalPassport" +} + +// NewInputPassportElementInternalPassport creates a new InputPassportElementInternalPassport +// +// @param internalPassport The internal passport to be saved +func NewInputPassportElementInternalPassport(internalPassport *InputIDentityDocument) *InputPassportElementInternalPassport { + inputPassportElementInternalPassportTemp := InputPassportElementInternalPassport{ + tdCommon: tdCommon{Type: "inputPassportElementInternalPassport"}, + InternalPassport: internalPassport, + } + + return &inputPassportElementInternalPassportTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementInternalPassport *InputPassportElementInternalPassport) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementInternalPassportType +} + +// InputPassportElementAddress A Telegram Passport element to be saved containing the user's address +type InputPassportElementAddress struct { + tdCommon + Address *Address `json:"address"` // The address to be saved +} + +// MessageType return the string telegram-type of InputPassportElementAddress +func (inputPassportElementAddress *InputPassportElementAddress) MessageType() string { + return "inputPassportElementAddress" +} + +// NewInputPassportElementAddress creates a new InputPassportElementAddress +// +// @param address The address to be saved +func NewInputPassportElementAddress(address *Address) *InputPassportElementAddress { + inputPassportElementAddressTemp := InputPassportElementAddress{ + tdCommon: tdCommon{Type: "inputPassportElementAddress"}, + Address: address, + } + + return &inputPassportElementAddressTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementAddress *InputPassportElementAddress) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementAddressType +} + +// InputPassportElementUtilityBill A Telegram Passport element to be saved containing the user's utility bill +type InputPassportElementUtilityBill struct { + tdCommon + UtilityBill *InputPersonalDocument `json:"utility_bill"` // The utility bill to be saved +} + +// MessageType return the string telegram-type of InputPassportElementUtilityBill +func (inputPassportElementUtilityBill *InputPassportElementUtilityBill) MessageType() string { + return "inputPassportElementUtilityBill" +} + +// NewInputPassportElementUtilityBill creates a new InputPassportElementUtilityBill +// +// @param utilityBill The utility bill to be saved +func NewInputPassportElementUtilityBill(utilityBill *InputPersonalDocument) *InputPassportElementUtilityBill { + inputPassportElementUtilityBillTemp := InputPassportElementUtilityBill{ + tdCommon: tdCommon{Type: "inputPassportElementUtilityBill"}, + UtilityBill: utilityBill, + } + + return &inputPassportElementUtilityBillTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementUtilityBill *InputPassportElementUtilityBill) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementUtilityBillType +} + +// InputPassportElementBankStatement A Telegram Passport element to be saved containing the user's bank statement +type InputPassportElementBankStatement struct { + tdCommon + BankStatement *InputPersonalDocument `json:"bank_statement"` // The bank statement to be saved +} + +// MessageType return the string telegram-type of InputPassportElementBankStatement +func (inputPassportElementBankStatement *InputPassportElementBankStatement) MessageType() string { + return "inputPassportElementBankStatement" +} + +// NewInputPassportElementBankStatement creates a new InputPassportElementBankStatement +// +// @param bankStatement The bank statement to be saved +func NewInputPassportElementBankStatement(bankStatement *InputPersonalDocument) *InputPassportElementBankStatement { + inputPassportElementBankStatementTemp := InputPassportElementBankStatement{ + tdCommon: tdCommon{Type: "inputPassportElementBankStatement"}, + BankStatement: bankStatement, + } + + return &inputPassportElementBankStatementTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementBankStatement *InputPassportElementBankStatement) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementBankStatementType +} + +// InputPassportElementRentalAgreement A Telegram Passport element to be saved containing the user's rental agreement +type InputPassportElementRentalAgreement struct { + tdCommon + RentalAgreement *InputPersonalDocument `json:"rental_agreement"` // The rental agreement to be saved +} + +// MessageType return the string telegram-type of InputPassportElementRentalAgreement +func (inputPassportElementRentalAgreement *InputPassportElementRentalAgreement) MessageType() string { + return "inputPassportElementRentalAgreement" +} + +// NewInputPassportElementRentalAgreement creates a new InputPassportElementRentalAgreement +// +// @param rentalAgreement The rental agreement to be saved +func NewInputPassportElementRentalAgreement(rentalAgreement *InputPersonalDocument) *InputPassportElementRentalAgreement { + inputPassportElementRentalAgreementTemp := InputPassportElementRentalAgreement{ + tdCommon: tdCommon{Type: "inputPassportElementRentalAgreement"}, + RentalAgreement: rentalAgreement, + } + + return &inputPassportElementRentalAgreementTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementRentalAgreement *InputPassportElementRentalAgreement) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementRentalAgreementType +} + +// InputPassportElementPassportRegistration A Telegram Passport element to be saved containing the user's passport registration +type InputPassportElementPassportRegistration struct { + tdCommon + PassportRegistration *InputPersonalDocument `json:"passport_registration"` // The passport registration page to be saved +} + +// MessageType return the string telegram-type of InputPassportElementPassportRegistration +func (inputPassportElementPassportRegistration *InputPassportElementPassportRegistration) MessageType() string { + return "inputPassportElementPassportRegistration" +} + +// NewInputPassportElementPassportRegistration creates a new InputPassportElementPassportRegistration +// +// @param passportRegistration The passport registration page to be saved +func NewInputPassportElementPassportRegistration(passportRegistration *InputPersonalDocument) *InputPassportElementPassportRegistration { + inputPassportElementPassportRegistrationTemp := InputPassportElementPassportRegistration{ + tdCommon: tdCommon{Type: "inputPassportElementPassportRegistration"}, + PassportRegistration: passportRegistration, + } + + return &inputPassportElementPassportRegistrationTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementPassportRegistration *InputPassportElementPassportRegistration) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementPassportRegistrationType +} + +// InputPassportElementTemporaryRegistration A Telegram Passport element to be saved containing the user's temporary registration +type InputPassportElementTemporaryRegistration struct { + tdCommon + TemporaryRegistration *InputPersonalDocument `json:"temporary_registration"` // The temporary registration document to be saved +} + +// MessageType return the string telegram-type of InputPassportElementTemporaryRegistration +func (inputPassportElementTemporaryRegistration *InputPassportElementTemporaryRegistration) MessageType() string { + return "inputPassportElementTemporaryRegistration" +} + +// NewInputPassportElementTemporaryRegistration creates a new InputPassportElementTemporaryRegistration +// +// @param temporaryRegistration The temporary registration document to be saved +func NewInputPassportElementTemporaryRegistration(temporaryRegistration *InputPersonalDocument) *InputPassportElementTemporaryRegistration { + inputPassportElementTemporaryRegistrationTemp := InputPassportElementTemporaryRegistration{ + tdCommon: tdCommon{Type: "inputPassportElementTemporaryRegistration"}, + TemporaryRegistration: temporaryRegistration, + } + + return &inputPassportElementTemporaryRegistrationTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementTemporaryRegistration *InputPassportElementTemporaryRegistration) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementTemporaryRegistrationType +} + +// InputPassportElementPhoneNumber A Telegram Passport element to be saved containing the user's phone number +type InputPassportElementPhoneNumber struct { + tdCommon + PhoneNumber string `json:"phone_number"` // The phone number to be saved +} + +// MessageType return the string telegram-type of InputPassportElementPhoneNumber +func (inputPassportElementPhoneNumber *InputPassportElementPhoneNumber) MessageType() string { + return "inputPassportElementPhoneNumber" +} + +// NewInputPassportElementPhoneNumber creates a new InputPassportElementPhoneNumber +// +// @param phoneNumber The phone number to be saved +func NewInputPassportElementPhoneNumber(phoneNumber string) *InputPassportElementPhoneNumber { + inputPassportElementPhoneNumberTemp := InputPassportElementPhoneNumber{ + tdCommon: tdCommon{Type: "inputPassportElementPhoneNumber"}, + PhoneNumber: phoneNumber, + } + + return &inputPassportElementPhoneNumberTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementPhoneNumber *InputPassportElementPhoneNumber) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementPhoneNumberType +} + +// InputPassportElementEmailAddress A Telegram Passport element to be saved containing the user's email address +type InputPassportElementEmailAddress struct { + tdCommon + EmailAddress string `json:"email_address"` // The email address to be saved +} + +// MessageType return the string telegram-type of InputPassportElementEmailAddress +func (inputPassportElementEmailAddress *InputPassportElementEmailAddress) MessageType() string { + return "inputPassportElementEmailAddress" +} + +// NewInputPassportElementEmailAddress creates a new InputPassportElementEmailAddress +// +// @param emailAddress The email address to be saved +func NewInputPassportElementEmailAddress(emailAddress string) *InputPassportElementEmailAddress { + inputPassportElementEmailAddressTemp := InputPassportElementEmailAddress{ + tdCommon: tdCommon{Type: "inputPassportElementEmailAddress"}, + EmailAddress: emailAddress, + } + + return &inputPassportElementEmailAddressTemp +} + +// GetInputPassportElementEnum return the enum type of this object +func (inputPassportElementEmailAddress *InputPassportElementEmailAddress) GetInputPassportElementEnum() InputPassportElementEnum { + return InputPassportElementEmailAddressType +} + +// PassportElements Contains information about saved Telegram Passport elements +type PassportElements struct { + tdCommon + Elements []PassportElement `json:"elements"` // Telegram Passport elements +} + +// MessageType return the string telegram-type of PassportElements +func (passportElements *PassportElements) MessageType() string { + return "passportElements" +} + +// NewPassportElements creates a new PassportElements +// +// @param elements Telegram Passport elements +func NewPassportElements(elements []PassportElement) *PassportElements { + passportElementsTemp := PassportElements{ + tdCommon: tdCommon{Type: "passportElements"}, + Elements: elements, + } + + return &passportElementsTemp +} + +// PassportElementErrorSourceUnspecified The element contains an error in an unspecified place. The error will be considered resolved when new data is added +type PassportElementErrorSourceUnspecified struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceUnspecified +func (passportElementErrorSourceUnspecified *PassportElementErrorSourceUnspecified) MessageType() string { + return "passportElementErrorSourceUnspecified" +} + +// NewPassportElementErrorSourceUnspecified creates a new PassportElementErrorSourceUnspecified +// +func NewPassportElementErrorSourceUnspecified() *PassportElementErrorSourceUnspecified { + passportElementErrorSourceUnspecifiedTemp := PassportElementErrorSourceUnspecified{ + tdCommon: tdCommon{Type: "passportElementErrorSourceUnspecified"}, + } + + return &passportElementErrorSourceUnspecifiedTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceUnspecified *PassportElementErrorSourceUnspecified) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceUnspecifiedType +} + +// PassportElementErrorSourceDataField One of the data fields contains an error. The error will be considered resolved when the value of the field changes +type PassportElementErrorSourceDataField struct { + tdCommon + FieldName string `json:"field_name"` // Field name +} + +// MessageType return the string telegram-type of PassportElementErrorSourceDataField +func (passportElementErrorSourceDataField *PassportElementErrorSourceDataField) MessageType() string { + return "passportElementErrorSourceDataField" +} + +// NewPassportElementErrorSourceDataField creates a new PassportElementErrorSourceDataField +// +// @param fieldName Field name +func NewPassportElementErrorSourceDataField(fieldName string) *PassportElementErrorSourceDataField { + passportElementErrorSourceDataFieldTemp := PassportElementErrorSourceDataField{ + tdCommon: tdCommon{Type: "passportElementErrorSourceDataField"}, + FieldName: fieldName, + } + + return &passportElementErrorSourceDataFieldTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceDataField *PassportElementErrorSourceDataField) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceDataFieldType +} + +// PassportElementErrorSourceFrontSide The front side of the document contains an error. The error will be considered resolved when the file with the front side changes +type PassportElementErrorSourceFrontSide struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceFrontSide +func (passportElementErrorSourceFrontSide *PassportElementErrorSourceFrontSide) MessageType() string { + return "passportElementErrorSourceFrontSide" +} + +// NewPassportElementErrorSourceFrontSide creates a new PassportElementErrorSourceFrontSide +// +func NewPassportElementErrorSourceFrontSide() *PassportElementErrorSourceFrontSide { + passportElementErrorSourceFrontSideTemp := PassportElementErrorSourceFrontSide{ + tdCommon: tdCommon{Type: "passportElementErrorSourceFrontSide"}, + } + + return &passportElementErrorSourceFrontSideTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceFrontSide *PassportElementErrorSourceFrontSide) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceFrontSideType +} + +// PassportElementErrorSourceReverseSide The reverse side of the document contains an error. The error will be considered resolved when the file with the reverse side changes +type PassportElementErrorSourceReverseSide struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceReverseSide +func (passportElementErrorSourceReverseSide *PassportElementErrorSourceReverseSide) MessageType() string { + return "passportElementErrorSourceReverseSide" +} + +// NewPassportElementErrorSourceReverseSide creates a new PassportElementErrorSourceReverseSide +// +func NewPassportElementErrorSourceReverseSide() *PassportElementErrorSourceReverseSide { + passportElementErrorSourceReverseSideTemp := PassportElementErrorSourceReverseSide{ + tdCommon: tdCommon{Type: "passportElementErrorSourceReverseSide"}, + } + + return &passportElementErrorSourceReverseSideTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceReverseSide *PassportElementErrorSourceReverseSide) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceReverseSideType +} + +// PassportElementErrorSourceSelfie The selfie with the document contains an error. The error will be considered resolved when the file with the selfie changes +type PassportElementErrorSourceSelfie struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceSelfie +func (passportElementErrorSourceSelfie *PassportElementErrorSourceSelfie) MessageType() string { + return "passportElementErrorSourceSelfie" +} + +// NewPassportElementErrorSourceSelfie creates a new PassportElementErrorSourceSelfie +// +func NewPassportElementErrorSourceSelfie() *PassportElementErrorSourceSelfie { + passportElementErrorSourceSelfieTemp := PassportElementErrorSourceSelfie{ + tdCommon: tdCommon{Type: "passportElementErrorSourceSelfie"}, + } + + return &passportElementErrorSourceSelfieTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceSelfie *PassportElementErrorSourceSelfie) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceSelfieType +} + +// PassportElementErrorSourceTranslationFile One of files with the translation of the document contains an error. The error will be considered resolved when the file changes +type PassportElementErrorSourceTranslationFile struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceTranslationFile +func (passportElementErrorSourceTranslationFile *PassportElementErrorSourceTranslationFile) MessageType() string { + return "passportElementErrorSourceTranslationFile" +} + +// NewPassportElementErrorSourceTranslationFile creates a new PassportElementErrorSourceTranslationFile +// +func NewPassportElementErrorSourceTranslationFile() *PassportElementErrorSourceTranslationFile { + passportElementErrorSourceTranslationFileTemp := PassportElementErrorSourceTranslationFile{ + tdCommon: tdCommon{Type: "passportElementErrorSourceTranslationFile"}, + } + + return &passportElementErrorSourceTranslationFileTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceTranslationFile *PassportElementErrorSourceTranslationFile) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceTranslationFileType +} + +// PassportElementErrorSourceTranslationFiles The translation of the document contains an error. The error will be considered resolved when the list of translation files changes +type PassportElementErrorSourceTranslationFiles struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceTranslationFiles +func (passportElementErrorSourceTranslationFiles *PassportElementErrorSourceTranslationFiles) MessageType() string { + return "passportElementErrorSourceTranslationFiles" +} + +// NewPassportElementErrorSourceTranslationFiles creates a new PassportElementErrorSourceTranslationFiles +// +func NewPassportElementErrorSourceTranslationFiles() *PassportElementErrorSourceTranslationFiles { + passportElementErrorSourceTranslationFilesTemp := PassportElementErrorSourceTranslationFiles{ + tdCommon: tdCommon{Type: "passportElementErrorSourceTranslationFiles"}, + } + + return &passportElementErrorSourceTranslationFilesTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceTranslationFiles *PassportElementErrorSourceTranslationFiles) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceTranslationFilesType +} + +// PassportElementErrorSourceFile The file contains an error. The error will be considered resolved when the file changes +type PassportElementErrorSourceFile struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceFile +func (passportElementErrorSourceFile *PassportElementErrorSourceFile) MessageType() string { + return "passportElementErrorSourceFile" +} + +// NewPassportElementErrorSourceFile creates a new PassportElementErrorSourceFile +// +func NewPassportElementErrorSourceFile() *PassportElementErrorSourceFile { + passportElementErrorSourceFileTemp := PassportElementErrorSourceFile{ + tdCommon: tdCommon{Type: "passportElementErrorSourceFile"}, + } + + return &passportElementErrorSourceFileTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceFile *PassportElementErrorSourceFile) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceFileType +} + +// PassportElementErrorSourceFiles The list of attached files contains an error. The error will be considered resolved when the list of files changes +type PassportElementErrorSourceFiles struct { + tdCommon +} + +// MessageType return the string telegram-type of PassportElementErrorSourceFiles +func (passportElementErrorSourceFiles *PassportElementErrorSourceFiles) MessageType() string { + return "passportElementErrorSourceFiles" +} + +// NewPassportElementErrorSourceFiles creates a new PassportElementErrorSourceFiles +// +func NewPassportElementErrorSourceFiles() *PassportElementErrorSourceFiles { + passportElementErrorSourceFilesTemp := PassportElementErrorSourceFiles{ + tdCommon: tdCommon{Type: "passportElementErrorSourceFiles"}, + } + + return &passportElementErrorSourceFilesTemp +} + +// GetPassportElementErrorSourceEnum return the enum type of this object +func (passportElementErrorSourceFiles *PassportElementErrorSourceFiles) GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum { + return PassportElementErrorSourceFilesType +} + +// PassportElementError Contains the description of an error in a Telegram Passport element +type PassportElementError struct { + tdCommon + Type PassportElementType `json:"type"` // Type of the Telegram Passport element which has the error + Message string `json:"message"` // Error message + Source PassportElementErrorSource `json:"source"` // Error source +} + +// MessageType return the string telegram-type of PassportElementError +func (passportElementError *PassportElementError) MessageType() string { + return "passportElementError" +} + +// NewPassportElementError creates a new PassportElementError +// +// @param typeParam Type of the Telegram Passport element which has the error +// @param message Error message +// @param source Error source +func NewPassportElementError(typeParam PassportElementType, message string, source PassportElementErrorSource) *PassportElementError { + passportElementErrorTemp := PassportElementError{ + tdCommon: tdCommon{Type: "passportElementError"}, + Type: typeParam, + Message: message, + Source: source, + } + + return &passportElementErrorTemp +} + +// UnmarshalJSON unmarshal to json +func (passportElementError *PassportElementError) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Message string `json:"message"` // Error message + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + passportElementError.tdCommon = tempObj.tdCommon + passportElementError.Message = tempObj.Message + + fieldType, _ := unmarshalPassportElementType(objMap["type"]) + passportElementError.Type = fieldType + + fieldSource, _ := unmarshalPassportElementErrorSource(objMap["source"]) + passportElementError.Source = fieldSource + + return nil +} + +// PassportSuitableElement Contains information about a Telegram Passport element that was requested by a service +type PassportSuitableElement struct { + tdCommon + Type PassportElementType `json:"type"` // Type of the element + IsSelfieRequired bool `json:"is_selfie_required"` // True, if a selfie is required with the identity document + IsTranslationRequired bool `json:"is_translation_required"` // True, if a certified English translation is required with the document + IsNativeNameRequired bool `json:"is_native_name_required"` // True, if personal details must include the user's name in the language of their country of residence +} + +// MessageType return the string telegram-type of PassportSuitableElement +func (passportSuitableElement *PassportSuitableElement) MessageType() string { + return "passportSuitableElement" +} + +// NewPassportSuitableElement creates a new PassportSuitableElement +// +// @param typeParam Type of the element +// @param isSelfieRequired True, if a selfie is required with the identity document +// @param isTranslationRequired True, if a certified English translation is required with the document +// @param isNativeNameRequired True, if personal details must include the user's name in the language of their country of residence +func NewPassportSuitableElement(typeParam PassportElementType, isSelfieRequired bool, isTranslationRequired bool, isNativeNameRequired bool) *PassportSuitableElement { + passportSuitableElementTemp := PassportSuitableElement{ + tdCommon: tdCommon{Type: "passportSuitableElement"}, + Type: typeParam, + IsSelfieRequired: isSelfieRequired, + IsTranslationRequired: isTranslationRequired, + IsNativeNameRequired: isNativeNameRequired, + } + + return &passportSuitableElementTemp +} + +// UnmarshalJSON unmarshal to json +func (passportSuitableElement *PassportSuitableElement) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + IsSelfieRequired bool `json:"is_selfie_required"` // True, if a selfie is required with the identity document + IsTranslationRequired bool `json:"is_translation_required"` // True, if a certified English translation is required with the document + IsNativeNameRequired bool `json:"is_native_name_required"` // True, if personal details must include the user's name in the language of their country of residence + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + passportSuitableElement.tdCommon = tempObj.tdCommon + passportSuitableElement.IsSelfieRequired = tempObj.IsSelfieRequired + passportSuitableElement.IsTranslationRequired = tempObj.IsTranslationRequired + passportSuitableElement.IsNativeNameRequired = tempObj.IsNativeNameRequired + + fieldType, _ := unmarshalPassportElementType(objMap["type"]) + passportSuitableElement.Type = fieldType + + return nil +} + +// PassportRequiredElement Contains a description of the required Telegram Passport element that was requested by a service +type PassportRequiredElement struct { + tdCommon + SuitableElements []PassportSuitableElement `json:"suitable_elements"` // List of Telegram Passport elements any of which is enough to provide +} + +// MessageType return the string telegram-type of PassportRequiredElement +func (passportRequiredElement *PassportRequiredElement) MessageType() string { + return "passportRequiredElement" +} + +// NewPassportRequiredElement creates a new PassportRequiredElement +// +// @param suitableElements List of Telegram Passport elements any of which is enough to provide +func NewPassportRequiredElement(suitableElements []PassportSuitableElement) *PassportRequiredElement { + passportRequiredElementTemp := PassportRequiredElement{ + tdCommon: tdCommon{Type: "passportRequiredElement"}, + SuitableElements: suitableElements, + } + + return &passportRequiredElementTemp +} + +// PassportAuthorizationForm Contains information about a Telegram Passport authorization form that was requested +type PassportAuthorizationForm struct { + tdCommon + ID int32 `json:"id"` // Unique identifier of the authorization form + RequiredElements []PassportRequiredElement `json:"required_elements"` // Information about the Telegram Passport elements that need to be provided to complete the form + Elements []PassportElement `json:"elements"` // Already available Telegram Passport elements + Errors []PassportElementError `json:"errors"` // Errors in the elements that are already available + PrivacyPolicyURL string `json:"privacy_policy_url"` // URL for the privacy policy of the service; can be empty +} + +// MessageType return the string telegram-type of PassportAuthorizationForm +func (passportAuthorizationForm *PassportAuthorizationForm) MessageType() string { + return "passportAuthorizationForm" +} + +// NewPassportAuthorizationForm creates a new PassportAuthorizationForm +// +// @param iD Unique identifier of the authorization form +// @param requiredElements Information about the Telegram Passport elements that need to be provided to complete the form +// @param elements Already available Telegram Passport elements +// @param errors Errors in the elements that are already available +// @param privacyPolicyURL URL for the privacy policy of the service; can be empty +func NewPassportAuthorizationForm(iD int32, requiredElements []PassportRequiredElement, elements []PassportElement, errors []PassportElementError, privacyPolicyURL string) *PassportAuthorizationForm { + passportAuthorizationFormTemp := PassportAuthorizationForm{ + tdCommon: tdCommon{Type: "passportAuthorizationForm"}, + ID: iD, + RequiredElements: requiredElements, + Elements: elements, + Errors: errors, + PrivacyPolicyURL: privacyPolicyURL, + } + + return &passportAuthorizationFormTemp +} + +// EncryptedCredentials Contains encrypted Telegram Passport data credentials +type EncryptedCredentials struct { + tdCommon + Data []byte `json:"data"` // The encrypted credentials + Hash []byte `json:"hash"` // The decrypted data hash + Secret []byte `json:"secret"` // Secret for data decryption, encrypted with the service's public key +} + +// MessageType return the string telegram-type of EncryptedCredentials +func (encryptedCredentials *EncryptedCredentials) MessageType() string { + return "encryptedCredentials" +} + +// NewEncryptedCredentials creates a new EncryptedCredentials +// +// @param data The encrypted credentials +// @param hash The decrypted data hash +// @param secret Secret for data decryption, encrypted with the service's public key +func NewEncryptedCredentials(data []byte, hash []byte, secret []byte) *EncryptedCredentials { + encryptedCredentialsTemp := EncryptedCredentials{ + tdCommon: tdCommon{Type: "encryptedCredentials"}, + Data: data, + Hash: hash, + Secret: secret, + } + + return &encryptedCredentialsTemp +} + +// EncryptedPassportElement Contains information about an encrypted Telegram Passport element; for bots only +type EncryptedPassportElement struct { + tdCommon + Type PassportElementType `json:"type"` // Type of Telegram Passport element + Data []byte `json:"data"` // Encrypted JSON-encoded data about the user + FrontSide *DatedFile `json:"front_side"` // The front side of an identity document + ReverseSide *DatedFile `json:"reverse_side"` // The reverse side of an identity document; may be null + Selfie *DatedFile `json:"selfie"` // Selfie with the document; may be null + Translation []DatedFile `json:"translation"` // List of files containing a certified English translation of the document + Files []DatedFile `json:"files"` // List of attached files + Value string `json:"value"` // Unencrypted data, phone number or email address + Hash string `json:"hash"` // Hash of the entire element +} + +// MessageType return the string telegram-type of EncryptedPassportElement +func (encryptedPassportElement *EncryptedPassportElement) MessageType() string { + return "encryptedPassportElement" +} + +// NewEncryptedPassportElement creates a new EncryptedPassportElement +// +// @param typeParam Type of Telegram Passport element +// @param data Encrypted JSON-encoded data about the user +// @param frontSide The front side of an identity document +// @param reverseSide The reverse side of an identity document; may be null +// @param selfie Selfie with the document; may be null +// @param translation List of files containing a certified English translation of the document +// @param files List of attached files +// @param value Unencrypted data, phone number or email address +// @param hash Hash of the entire element +func NewEncryptedPassportElement(typeParam PassportElementType, data []byte, frontSide *DatedFile, reverseSide *DatedFile, selfie *DatedFile, translation []DatedFile, files []DatedFile, value string, hash string) *EncryptedPassportElement { + encryptedPassportElementTemp := EncryptedPassportElement{ + tdCommon: tdCommon{Type: "encryptedPassportElement"}, + Type: typeParam, + Data: data, + FrontSide: frontSide, + ReverseSide: reverseSide, + Selfie: selfie, + Translation: translation, + Files: files, + Value: value, + Hash: hash, + } + + return &encryptedPassportElementTemp +} + +// UnmarshalJSON unmarshal to json +func (encryptedPassportElement *EncryptedPassportElement) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Data []byte `json:"data"` // Encrypted JSON-encoded data about the user + FrontSide *DatedFile `json:"front_side"` // The front side of an identity document + ReverseSide *DatedFile `json:"reverse_side"` // The reverse side of an identity document; may be null + Selfie *DatedFile `json:"selfie"` // Selfie with the document; may be null + Translation []DatedFile `json:"translation"` // List of files containing a certified English translation of the document + Files []DatedFile `json:"files"` // List of attached files + Value string `json:"value"` // Unencrypted data, phone number or email address + Hash string `json:"hash"` // Hash of the entire element + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + encryptedPassportElement.tdCommon = tempObj.tdCommon + encryptedPassportElement.Data = tempObj.Data + encryptedPassportElement.FrontSide = tempObj.FrontSide + encryptedPassportElement.ReverseSide = tempObj.ReverseSide + encryptedPassportElement.Selfie = tempObj.Selfie + encryptedPassportElement.Translation = tempObj.Translation + encryptedPassportElement.Files = tempObj.Files + encryptedPassportElement.Value = tempObj.Value + encryptedPassportElement.Hash = tempObj.Hash + + fieldType, _ := unmarshalPassportElementType(objMap["type"]) + encryptedPassportElement.Type = fieldType + + return nil +} + +// InputPassportElementErrorSourceUnspecified The element contains an error in an unspecified place. The error will be considered resolved when new data is added +type InputPassportElementErrorSourceUnspecified struct { + tdCommon + ElementHash []byte `json:"element_hash"` // Current hash of the entire element +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceUnspecified +func (inputPassportElementErrorSourceUnspecified *InputPassportElementErrorSourceUnspecified) MessageType() string { + return "inputPassportElementErrorSourceUnspecified" +} + +// NewInputPassportElementErrorSourceUnspecified creates a new InputPassportElementErrorSourceUnspecified +// +// @param elementHash Current hash of the entire element +func NewInputPassportElementErrorSourceUnspecified(elementHash []byte) *InputPassportElementErrorSourceUnspecified { + inputPassportElementErrorSourceUnspecifiedTemp := InputPassportElementErrorSourceUnspecified{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceUnspecified"}, + ElementHash: elementHash, + } + + return &inputPassportElementErrorSourceUnspecifiedTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceUnspecified *InputPassportElementErrorSourceUnspecified) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceUnspecifiedType +} + +// InputPassportElementErrorSourceDataField A data field contains an error. The error is considered resolved when the field's value changes +type InputPassportElementErrorSourceDataField struct { + tdCommon + FieldName string `json:"field_name"` // Field name + DataHash []byte `json:"data_hash"` // Current data hash +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceDataField +func (inputPassportElementErrorSourceDataField *InputPassportElementErrorSourceDataField) MessageType() string { + return "inputPassportElementErrorSourceDataField" +} + +// NewInputPassportElementErrorSourceDataField creates a new InputPassportElementErrorSourceDataField +// +// @param fieldName Field name +// @param dataHash Current data hash +func NewInputPassportElementErrorSourceDataField(fieldName string, dataHash []byte) *InputPassportElementErrorSourceDataField { + inputPassportElementErrorSourceDataFieldTemp := InputPassportElementErrorSourceDataField{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceDataField"}, + FieldName: fieldName, + DataHash: dataHash, + } + + return &inputPassportElementErrorSourceDataFieldTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceDataField *InputPassportElementErrorSourceDataField) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceDataFieldType +} + +// InputPassportElementErrorSourceFrontSide The front side of the document contains an error. The error is considered resolved when the file with the front side of the document changes +type InputPassportElementErrorSourceFrontSide struct { + tdCommon + FileHash []byte `json:"file_hash"` // Current hash of the file containing the front side +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceFrontSide +func (inputPassportElementErrorSourceFrontSide *InputPassportElementErrorSourceFrontSide) MessageType() string { + return "inputPassportElementErrorSourceFrontSide" +} + +// NewInputPassportElementErrorSourceFrontSide creates a new InputPassportElementErrorSourceFrontSide +// +// @param fileHash Current hash of the file containing the front side +func NewInputPassportElementErrorSourceFrontSide(fileHash []byte) *InputPassportElementErrorSourceFrontSide { + inputPassportElementErrorSourceFrontSideTemp := InputPassportElementErrorSourceFrontSide{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceFrontSide"}, + FileHash: fileHash, + } + + return &inputPassportElementErrorSourceFrontSideTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceFrontSide *InputPassportElementErrorSourceFrontSide) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceFrontSideType +} + +// InputPassportElementErrorSourceReverseSide The reverse side of the document contains an error. The error is considered resolved when the file with the reverse side of the document changes +type InputPassportElementErrorSourceReverseSide struct { + tdCommon + FileHash []byte `json:"file_hash"` // Current hash of the file containing the reverse side +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceReverseSide +func (inputPassportElementErrorSourceReverseSide *InputPassportElementErrorSourceReverseSide) MessageType() string { + return "inputPassportElementErrorSourceReverseSide" +} + +// NewInputPassportElementErrorSourceReverseSide creates a new InputPassportElementErrorSourceReverseSide +// +// @param fileHash Current hash of the file containing the reverse side +func NewInputPassportElementErrorSourceReverseSide(fileHash []byte) *InputPassportElementErrorSourceReverseSide { + inputPassportElementErrorSourceReverseSideTemp := InputPassportElementErrorSourceReverseSide{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceReverseSide"}, + FileHash: fileHash, + } + + return &inputPassportElementErrorSourceReverseSideTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceReverseSide *InputPassportElementErrorSourceReverseSide) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceReverseSideType +} + +// InputPassportElementErrorSourceSelfie The selfie contains an error. The error is considered resolved when the file with the selfie changes +type InputPassportElementErrorSourceSelfie struct { + tdCommon + FileHash []byte `json:"file_hash"` // Current hash of the file containing the selfie +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceSelfie +func (inputPassportElementErrorSourceSelfie *InputPassportElementErrorSourceSelfie) MessageType() string { + return "inputPassportElementErrorSourceSelfie" +} + +// NewInputPassportElementErrorSourceSelfie creates a new InputPassportElementErrorSourceSelfie +// +// @param fileHash Current hash of the file containing the selfie +func NewInputPassportElementErrorSourceSelfie(fileHash []byte) *InputPassportElementErrorSourceSelfie { + inputPassportElementErrorSourceSelfieTemp := InputPassportElementErrorSourceSelfie{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceSelfie"}, + FileHash: fileHash, + } + + return &inputPassportElementErrorSourceSelfieTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceSelfie *InputPassportElementErrorSourceSelfie) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceSelfieType +} + +// InputPassportElementErrorSourceTranslationFile One of the files containing the translation of the document contains an error. The error is considered resolved when the file with the translation changes +type InputPassportElementErrorSourceTranslationFile struct { + tdCommon + FileHash []byte `json:"file_hash"` // Current hash of the file containing the translation +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceTranslationFile +func (inputPassportElementErrorSourceTranslationFile *InputPassportElementErrorSourceTranslationFile) MessageType() string { + return "inputPassportElementErrorSourceTranslationFile" +} + +// NewInputPassportElementErrorSourceTranslationFile creates a new InputPassportElementErrorSourceTranslationFile +// +// @param fileHash Current hash of the file containing the translation +func NewInputPassportElementErrorSourceTranslationFile(fileHash []byte) *InputPassportElementErrorSourceTranslationFile { + inputPassportElementErrorSourceTranslationFileTemp := InputPassportElementErrorSourceTranslationFile{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceTranslationFile"}, + FileHash: fileHash, + } + + return &inputPassportElementErrorSourceTranslationFileTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceTranslationFile *InputPassportElementErrorSourceTranslationFile) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceTranslationFileType +} + +// InputPassportElementErrorSourceTranslationFiles The translation of the document contains an error. The error is considered resolved when the list of files changes +type InputPassportElementErrorSourceTranslationFiles struct { + tdCommon + FileHashes [][]byte `json:"file_hashes"` // Current hashes of all files with the translation +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceTranslationFiles +func (inputPassportElementErrorSourceTranslationFiles *InputPassportElementErrorSourceTranslationFiles) MessageType() string { + return "inputPassportElementErrorSourceTranslationFiles" +} + +// NewInputPassportElementErrorSourceTranslationFiles creates a new InputPassportElementErrorSourceTranslationFiles +// +// @param fileHashes Current hashes of all files with the translation +func NewInputPassportElementErrorSourceTranslationFiles(fileHashes [][]byte) *InputPassportElementErrorSourceTranslationFiles { + inputPassportElementErrorSourceTranslationFilesTemp := InputPassportElementErrorSourceTranslationFiles{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceTranslationFiles"}, + FileHashes: fileHashes, + } + + return &inputPassportElementErrorSourceTranslationFilesTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceTranslationFiles *InputPassportElementErrorSourceTranslationFiles) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceTranslationFilesType +} + +// InputPassportElementErrorSourceFile The file contains an error. The error is considered resolved when the file changes +type InputPassportElementErrorSourceFile struct { + tdCommon + FileHash []byte `json:"file_hash"` // Current hash of the file which has the error +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceFile +func (inputPassportElementErrorSourceFile *InputPassportElementErrorSourceFile) MessageType() string { + return "inputPassportElementErrorSourceFile" +} + +// NewInputPassportElementErrorSourceFile creates a new InputPassportElementErrorSourceFile +// +// @param fileHash Current hash of the file which has the error +func NewInputPassportElementErrorSourceFile(fileHash []byte) *InputPassportElementErrorSourceFile { + inputPassportElementErrorSourceFileTemp := InputPassportElementErrorSourceFile{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceFile"}, + FileHash: fileHash, + } + + return &inputPassportElementErrorSourceFileTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceFile *InputPassportElementErrorSourceFile) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceFileType +} + +// InputPassportElementErrorSourceFiles The list of attached files contains an error. The error is considered resolved when the file list changes +type InputPassportElementErrorSourceFiles struct { + tdCommon + FileHashes [][]byte `json:"file_hashes"` // Current hashes of all attached files +} + +// MessageType return the string telegram-type of InputPassportElementErrorSourceFiles +func (inputPassportElementErrorSourceFiles *InputPassportElementErrorSourceFiles) MessageType() string { + return "inputPassportElementErrorSourceFiles" +} + +// NewInputPassportElementErrorSourceFiles creates a new InputPassportElementErrorSourceFiles +// +// @param fileHashes Current hashes of all attached files +func NewInputPassportElementErrorSourceFiles(fileHashes [][]byte) *InputPassportElementErrorSourceFiles { + inputPassportElementErrorSourceFilesTemp := InputPassportElementErrorSourceFiles{ + tdCommon: tdCommon{Type: "inputPassportElementErrorSourceFiles"}, + FileHashes: fileHashes, + } + + return &inputPassportElementErrorSourceFilesTemp +} + +// GetInputPassportElementErrorSourceEnum return the enum type of this object +func (inputPassportElementErrorSourceFiles *InputPassportElementErrorSourceFiles) GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum { + return InputPassportElementErrorSourceFilesType +} + +// InputPassportElementError Contains the description of an error in a Telegram Passport element; for bots only +type InputPassportElementError struct { + tdCommon + Type PassportElementType `json:"type"` // Type of Telegram Passport element that has the error + Message string `json:"message"` // Error message + Source InputPassportElementErrorSource `json:"source"` // Error source +} + +// MessageType return the string telegram-type of InputPassportElementError +func (inputPassportElementError *InputPassportElementError) MessageType() string { + return "inputPassportElementError" +} + +// NewInputPassportElementError creates a new InputPassportElementError +// +// @param typeParam Type of Telegram Passport element that has the error +// @param message Error message +// @param source Error source +func NewInputPassportElementError(typeParam PassportElementType, message string, source InputPassportElementErrorSource) *InputPassportElementError { + inputPassportElementErrorTemp := InputPassportElementError{ + tdCommon: tdCommon{Type: "inputPassportElementError"}, + Type: typeParam, + Message: message, + Source: source, + } + + return &inputPassportElementErrorTemp +} + +// UnmarshalJSON unmarshal to json +func (inputPassportElementError *InputPassportElementError) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Message string `json:"message"` // Error message + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputPassportElementError.tdCommon = tempObj.tdCommon + inputPassportElementError.Message = tempObj.Message + + fieldType, _ := unmarshalPassportElementType(objMap["type"]) + inputPassportElementError.Type = fieldType + + fieldSource, _ := unmarshalInputPassportElementErrorSource(objMap["source"]) + inputPassportElementError.Source = fieldSource + + return nil +} + +// MessageText A text message +type MessageText struct { + tdCommon + Text *FormattedText `json:"text"` // Text of the message + WebPage *WebPage `json:"web_page"` // A preview of the web page that's mentioned in the text; may be null +} + +// MessageType return the string telegram-type of MessageText +func (messageText *MessageText) MessageType() string { + return "messageText" +} + +// NewMessageText creates a new MessageText +// +// @param text Text of the message +// @param webPage A preview of the web page that's mentioned in the text; may be null +func NewMessageText(text *FormattedText, webPage *WebPage) *MessageText { + messageTextTemp := MessageText{ + tdCommon: tdCommon{Type: "messageText"}, + Text: text, + WebPage: webPage, + } + + return &messageTextTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageText *MessageText) GetMessageContentEnum() MessageContentEnum { + return MessageTextType +} + +// MessageAnimation An animation message (GIF-style). +type MessageAnimation struct { + tdCommon + Animation *Animation `json:"animation"` // Message content + Caption *FormattedText `json:"caption"` // Animation caption + IsSecret bool `json:"is_secret"` // True, if the animation thumbnail must be blurred and the animation must be shown only while tapped +} + +// MessageType return the string telegram-type of MessageAnimation +func (messageAnimation *MessageAnimation) MessageType() string { + return "messageAnimation" +} + +// NewMessageAnimation creates a new MessageAnimation +// +// @param animation Message content +// @param caption Animation caption +// @param isSecret True, if the animation thumbnail must be blurred and the animation must be shown only while tapped +func NewMessageAnimation(animation *Animation, caption *FormattedText, isSecret bool) *MessageAnimation { + messageAnimationTemp := MessageAnimation{ + tdCommon: tdCommon{Type: "messageAnimation"}, + Animation: animation, + Caption: caption, + IsSecret: isSecret, + } + + return &messageAnimationTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageAnimation *MessageAnimation) GetMessageContentEnum() MessageContentEnum { + return MessageAnimationType +} + +// MessageAudio An audio message +type MessageAudio struct { + tdCommon + Audio *Audio `json:"audio"` // Message content + Caption *FormattedText `json:"caption"` // Audio caption +} + +// MessageType return the string telegram-type of MessageAudio +func (messageAudio *MessageAudio) MessageType() string { + return "messageAudio" +} + +// NewMessageAudio creates a new MessageAudio +// +// @param audio Message content +// @param caption Audio caption +func NewMessageAudio(audio *Audio, caption *FormattedText) *MessageAudio { + messageAudioTemp := MessageAudio{ + tdCommon: tdCommon{Type: "messageAudio"}, + Audio: audio, + Caption: caption, + } + + return &messageAudioTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageAudio *MessageAudio) GetMessageContentEnum() MessageContentEnum { + return MessageAudioType +} + +// MessageDocument A document message (general file) +type MessageDocument struct { + tdCommon + Document *Document `json:"document"` // Message content + Caption *FormattedText `json:"caption"` // Document caption +} + +// MessageType return the string telegram-type of MessageDocument +func (messageDocument *MessageDocument) MessageType() string { + return "messageDocument" +} + +// NewMessageDocument creates a new MessageDocument +// +// @param document Message content +// @param caption Document caption +func NewMessageDocument(document *Document, caption *FormattedText) *MessageDocument { + messageDocumentTemp := MessageDocument{ + tdCommon: tdCommon{Type: "messageDocument"}, + Document: document, + Caption: caption, + } + + return &messageDocumentTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageDocument *MessageDocument) GetMessageContentEnum() MessageContentEnum { + return MessageDocumentType +} + +// MessagePhoto A photo message +type MessagePhoto struct { + tdCommon + Photo *Photo `json:"photo"` // Message content + Caption *FormattedText `json:"caption"` // Photo caption + IsSecret bool `json:"is_secret"` // True, if the photo must be blurred and must be shown only while tapped +} + +// MessageType return the string telegram-type of MessagePhoto +func (messagePhoto *MessagePhoto) MessageType() string { + return "messagePhoto" +} + +// NewMessagePhoto creates a new MessagePhoto +// +// @param photo Message content +// @param caption Photo caption +// @param isSecret True, if the photo must be blurred and must be shown only while tapped +func NewMessagePhoto(photo *Photo, caption *FormattedText, isSecret bool) *MessagePhoto { + messagePhotoTemp := MessagePhoto{ + tdCommon: tdCommon{Type: "messagePhoto"}, + Photo: photo, + Caption: caption, + IsSecret: isSecret, + } + + return &messagePhotoTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messagePhoto *MessagePhoto) GetMessageContentEnum() MessageContentEnum { + return MessagePhotoType +} + +// MessageExpiredPhoto An expired photo message (self-destructed after TTL has elapsed) +type MessageExpiredPhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageExpiredPhoto +func (messageExpiredPhoto *MessageExpiredPhoto) MessageType() string { + return "messageExpiredPhoto" +} + +// NewMessageExpiredPhoto creates a new MessageExpiredPhoto +// +func NewMessageExpiredPhoto() *MessageExpiredPhoto { + messageExpiredPhotoTemp := MessageExpiredPhoto{ + tdCommon: tdCommon{Type: "messageExpiredPhoto"}, + } + + return &messageExpiredPhotoTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageExpiredPhoto *MessageExpiredPhoto) GetMessageContentEnum() MessageContentEnum { + return MessageExpiredPhotoType +} + +// MessageSticker A sticker message +type MessageSticker struct { + tdCommon + Sticker *Sticker `json:"sticker"` // Message content +} + +// MessageType return the string telegram-type of MessageSticker +func (messageSticker *MessageSticker) MessageType() string { + return "messageSticker" +} + +// NewMessageSticker creates a new MessageSticker +// +// @param sticker Message content +func NewMessageSticker(sticker *Sticker) *MessageSticker { + messageStickerTemp := MessageSticker{ + tdCommon: tdCommon{Type: "messageSticker"}, + Sticker: sticker, + } + + return &messageStickerTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageSticker *MessageSticker) GetMessageContentEnum() MessageContentEnum { + return MessageStickerType +} + +// MessageVideo A video message +type MessageVideo struct { + tdCommon + Video *Video `json:"video"` // Message content + Caption *FormattedText `json:"caption"` // Video caption + IsSecret bool `json:"is_secret"` // True, if the video thumbnail must be blurred and the video must be shown only while tapped +} + +// MessageType return the string telegram-type of MessageVideo +func (messageVideo *MessageVideo) MessageType() string { + return "messageVideo" +} + +// NewMessageVideo creates a new MessageVideo +// +// @param video Message content +// @param caption Video caption +// @param isSecret True, if the video thumbnail must be blurred and the video must be shown only while tapped +func NewMessageVideo(video *Video, caption *FormattedText, isSecret bool) *MessageVideo { + messageVideoTemp := MessageVideo{ + tdCommon: tdCommon{Type: "messageVideo"}, + Video: video, + Caption: caption, + IsSecret: isSecret, + } + + return &messageVideoTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageVideo *MessageVideo) GetMessageContentEnum() MessageContentEnum { + return MessageVideoType +} + +// MessageExpiredVideo An expired video message (self-destructed after TTL has elapsed) +type MessageExpiredVideo struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageExpiredVideo +func (messageExpiredVideo *MessageExpiredVideo) MessageType() string { + return "messageExpiredVideo" +} + +// NewMessageExpiredVideo creates a new MessageExpiredVideo +// +func NewMessageExpiredVideo() *MessageExpiredVideo { + messageExpiredVideoTemp := MessageExpiredVideo{ + tdCommon: tdCommon{Type: "messageExpiredVideo"}, + } + + return &messageExpiredVideoTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageExpiredVideo *MessageExpiredVideo) GetMessageContentEnum() MessageContentEnum { + return MessageExpiredVideoType +} + +// MessageVideoNote A video note message +type MessageVideoNote struct { + tdCommon + VideoNote *VideoNote `json:"video_note"` // Message content + IsViewed bool `json:"is_viewed"` // True, if at least one of the recipients has viewed the video note + IsSecret bool `json:"is_secret"` // True, if the video note thumbnail must be blurred and the video note must be shown only while tapped +} + +// MessageType return the string telegram-type of MessageVideoNote +func (messageVideoNote *MessageVideoNote) MessageType() string { + return "messageVideoNote" +} + +// NewMessageVideoNote creates a new MessageVideoNote +// +// @param videoNote Message content +// @param isViewed True, if at least one of the recipients has viewed the video note +// @param isSecret True, if the video note thumbnail must be blurred and the video note must be shown only while tapped +func NewMessageVideoNote(videoNote *VideoNote, isViewed bool, isSecret bool) *MessageVideoNote { + messageVideoNoteTemp := MessageVideoNote{ + tdCommon: tdCommon{Type: "messageVideoNote"}, + VideoNote: videoNote, + IsViewed: isViewed, + IsSecret: isSecret, + } + + return &messageVideoNoteTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageVideoNote *MessageVideoNote) GetMessageContentEnum() MessageContentEnum { + return MessageVideoNoteType +} + +// MessageVoiceNote A voice note message +type MessageVoiceNote struct { + tdCommon + VoiceNote *VoiceNote `json:"voice_note"` // Message content + Caption *FormattedText `json:"caption"` // Voice note caption + IsListened bool `json:"is_listened"` // True, if at least one of the recipients has listened to the voice note +} + +// MessageType return the string telegram-type of MessageVoiceNote +func (messageVoiceNote *MessageVoiceNote) MessageType() string { + return "messageVoiceNote" +} + +// NewMessageVoiceNote creates a new MessageVoiceNote +// +// @param voiceNote Message content +// @param caption Voice note caption +// @param isListened True, if at least one of the recipients has listened to the voice note +func NewMessageVoiceNote(voiceNote *VoiceNote, caption *FormattedText, isListened bool) *MessageVoiceNote { + messageVoiceNoteTemp := MessageVoiceNote{ + tdCommon: tdCommon{Type: "messageVoiceNote"}, + VoiceNote: voiceNote, + Caption: caption, + IsListened: isListened, + } + + return &messageVoiceNoteTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageVoiceNote *MessageVoiceNote) GetMessageContentEnum() MessageContentEnum { + return MessageVoiceNoteType +} + +// MessageLocation A message with a location +type MessageLocation struct { + tdCommon + Location *Location `json:"location"` // Message content + LivePeriod int32 `json:"live_period"` // Time relative to the message sent date until which the location can be updated, in seconds + ExpiresIn int32 `json:"expires_in"` // Left time for which the location can be updated, in seconds. updateMessageContent is not sent when this field changes +} + +// MessageType return the string telegram-type of MessageLocation +func (messageLocation *MessageLocation) MessageType() string { + return "messageLocation" +} + +// NewMessageLocation creates a new MessageLocation +// +// @param location Message content +// @param livePeriod Time relative to the message sent date until which the location can be updated, in seconds +// @param expiresIn Left time for which the location can be updated, in seconds. updateMessageContent is not sent when this field changes +func NewMessageLocation(location *Location, livePeriod int32, expiresIn int32) *MessageLocation { + messageLocationTemp := MessageLocation{ + tdCommon: tdCommon{Type: "messageLocation"}, + Location: location, + LivePeriod: livePeriod, + ExpiresIn: expiresIn, + } + + return &messageLocationTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageLocation *MessageLocation) GetMessageContentEnum() MessageContentEnum { + return MessageLocationType +} + +// MessageVenue A message with information about a venue +type MessageVenue struct { + tdCommon + Venue *Venue `json:"venue"` // Message content +} + +// MessageType return the string telegram-type of MessageVenue +func (messageVenue *MessageVenue) MessageType() string { + return "messageVenue" +} + +// NewMessageVenue creates a new MessageVenue +// +// @param venue Message content +func NewMessageVenue(venue *Venue) *MessageVenue { + messageVenueTemp := MessageVenue{ + tdCommon: tdCommon{Type: "messageVenue"}, + Venue: venue, + } + + return &messageVenueTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageVenue *MessageVenue) GetMessageContentEnum() MessageContentEnum { + return MessageVenueType +} + +// MessageContact A message with a user contact +type MessageContact struct { + tdCommon + Contact *Contact `json:"contact"` // Message content +} + +// MessageType return the string telegram-type of MessageContact +func (messageContact *MessageContact) MessageType() string { + return "messageContact" +} + +// NewMessageContact creates a new MessageContact +// +// @param contact Message content +func NewMessageContact(contact *Contact) *MessageContact { + messageContactTemp := MessageContact{ + tdCommon: tdCommon{Type: "messageContact"}, + Contact: contact, + } + + return &messageContactTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageContact *MessageContact) GetMessageContentEnum() MessageContentEnum { + return MessageContactType +} + +// MessageGame A message with a game +type MessageGame struct { + tdCommon + Game *Game `json:"game"` // Game +} + +// MessageType return the string telegram-type of MessageGame +func (messageGame *MessageGame) MessageType() string { + return "messageGame" +} + +// NewMessageGame creates a new MessageGame +// +// @param game Game +func NewMessageGame(game *Game) *MessageGame { + messageGameTemp := MessageGame{ + tdCommon: tdCommon{Type: "messageGame"}, + Game: game, + } + + return &messageGameTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageGame *MessageGame) GetMessageContentEnum() MessageContentEnum { + return MessageGameType +} + +// MessageInvoice A message with an invoice from a bot +type MessageInvoice struct { + tdCommon + Title string `json:"title"` // Product title + Description string `json:"description"` // + Photo *Photo `json:"photo"` // Product photo; may be null + Currency string `json:"currency"` // Currency for the product price + TotalAmount int64 `json:"total_amount"` // Product total price in the minimal quantity of the currency + StartParameter string `json:"start_parameter"` // Unique invoice bot start_parameter. To share an invoice use the URL https://t.me/{bot_username}?start={start_parameter} + IsTest bool `json:"is_test"` // True, if the invoice is a test invoice + NeedShippingAddress bool `json:"need_shipping_address"` // True, if the shipping address should be specified + ReceiptMessageID int64 `json:"receipt_message_id"` // The identifier of the message with the receipt, after the product has been purchased +} + +// MessageType return the string telegram-type of MessageInvoice +func (messageInvoice *MessageInvoice) MessageType() string { + return "messageInvoice" +} + +// NewMessageInvoice creates a new MessageInvoice +// +// @param title Product title +// @param description +// @param photo Product photo; may be null +// @param currency Currency for the product price +// @param totalAmount Product total price in the minimal quantity of the currency +// @param startParameter Unique invoice bot start_parameter. To share an invoice use the URL https://t.me/{bot_username}?start={start_parameter} +// @param isTest True, if the invoice is a test invoice +// @param needShippingAddress True, if the shipping address should be specified +// @param receiptMessageID The identifier of the message with the receipt, after the product has been purchased +func NewMessageInvoice(title string, description string, photo *Photo, currency string, totalAmount int64, startParameter string, isTest bool, needShippingAddress bool, receiptMessageID int64) *MessageInvoice { + messageInvoiceTemp := MessageInvoice{ + tdCommon: tdCommon{Type: "messageInvoice"}, + Title: title, + Description: description, + Photo: photo, + Currency: currency, + TotalAmount: totalAmount, + StartParameter: startParameter, + IsTest: isTest, + NeedShippingAddress: needShippingAddress, + ReceiptMessageID: receiptMessageID, + } + + return &messageInvoiceTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageInvoice *MessageInvoice) GetMessageContentEnum() MessageContentEnum { + return MessageInvoiceType +} + +// MessageCall A message with information about an ended call +type MessageCall struct { + tdCommon + DiscardReason CallDiscardReason `json:"discard_reason"` // Reason why the call was discarded + Duration int32 `json:"duration"` // Call duration, in seconds +} + +// MessageType return the string telegram-type of MessageCall +func (messageCall *MessageCall) MessageType() string { + return "messageCall" +} + +// NewMessageCall creates a new MessageCall +// +// @param discardReason Reason why the call was discarded +// @param duration Call duration, in seconds +func NewMessageCall(discardReason CallDiscardReason, duration int32) *MessageCall { + messageCallTemp := MessageCall{ + tdCommon: tdCommon{Type: "messageCall"}, + DiscardReason: discardReason, + Duration: duration, + } + + return &messageCallTemp +} + +// UnmarshalJSON unmarshal to json +func (messageCall *MessageCall) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Duration int32 `json:"duration"` // Call duration, in seconds + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + messageCall.tdCommon = tempObj.tdCommon + messageCall.Duration = tempObj.Duration + + fieldDiscardReason, _ := unmarshalCallDiscardReason(objMap["discard_reason"]) + messageCall.DiscardReason = fieldDiscardReason + + return nil +} + +// GetMessageContentEnum return the enum type of this object +func (messageCall *MessageCall) GetMessageContentEnum() MessageContentEnum { + return MessageCallType +} + +// MessageBasicGroupChatCreate A newly created basic group +type MessageBasicGroupChatCreate struct { + tdCommon + Title string `json:"title"` // Title of the basic group + MemberUserIDs []int32 `json:"member_user_ids"` // User identifiers of members in the basic group +} + +// MessageType return the string telegram-type of MessageBasicGroupChatCreate +func (messageBasicGroupChatCreate *MessageBasicGroupChatCreate) MessageType() string { + return "messageBasicGroupChatCreate" +} + +// NewMessageBasicGroupChatCreate creates a new MessageBasicGroupChatCreate +// +// @param title Title of the basic group +// @param memberUserIDs User identifiers of members in the basic group +func NewMessageBasicGroupChatCreate(title string, memberUserIDs []int32) *MessageBasicGroupChatCreate { + messageBasicGroupChatCreateTemp := MessageBasicGroupChatCreate{ + tdCommon: tdCommon{Type: "messageBasicGroupChatCreate"}, + Title: title, + MemberUserIDs: memberUserIDs, + } + + return &messageBasicGroupChatCreateTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageBasicGroupChatCreate *MessageBasicGroupChatCreate) GetMessageContentEnum() MessageContentEnum { + return MessageBasicGroupChatCreateType +} + +// MessageSupergroupChatCreate A newly created supergroup or channel +type MessageSupergroupChatCreate struct { + tdCommon + Title string `json:"title"` // Title of the supergroup or channel +} + +// MessageType return the string telegram-type of MessageSupergroupChatCreate +func (messageSupergroupChatCreate *MessageSupergroupChatCreate) MessageType() string { + return "messageSupergroupChatCreate" +} + +// NewMessageSupergroupChatCreate creates a new MessageSupergroupChatCreate +// +// @param title Title of the supergroup or channel +func NewMessageSupergroupChatCreate(title string) *MessageSupergroupChatCreate { + messageSupergroupChatCreateTemp := MessageSupergroupChatCreate{ + tdCommon: tdCommon{Type: "messageSupergroupChatCreate"}, + Title: title, + } + + return &messageSupergroupChatCreateTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageSupergroupChatCreate *MessageSupergroupChatCreate) GetMessageContentEnum() MessageContentEnum { + return MessageSupergroupChatCreateType +} + +// MessageChatChangeTitle An updated chat title +type MessageChatChangeTitle struct { + tdCommon + Title string `json:"title"` // New chat title +} + +// MessageType return the string telegram-type of MessageChatChangeTitle +func (messageChatChangeTitle *MessageChatChangeTitle) MessageType() string { + return "messageChatChangeTitle" +} + +// NewMessageChatChangeTitle creates a new MessageChatChangeTitle +// +// @param title New chat title +func NewMessageChatChangeTitle(title string) *MessageChatChangeTitle { + messageChatChangeTitleTemp := MessageChatChangeTitle{ + tdCommon: tdCommon{Type: "messageChatChangeTitle"}, + Title: title, + } + + return &messageChatChangeTitleTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatChangeTitle *MessageChatChangeTitle) GetMessageContentEnum() MessageContentEnum { + return MessageChatChangeTitleType +} + +// MessageChatChangePhoto An updated chat photo +type MessageChatChangePhoto struct { + tdCommon + Photo *Photo `json:"photo"` // New chat photo +} + +// MessageType return the string telegram-type of MessageChatChangePhoto +func (messageChatChangePhoto *MessageChatChangePhoto) MessageType() string { + return "messageChatChangePhoto" +} + +// NewMessageChatChangePhoto creates a new MessageChatChangePhoto +// +// @param photo New chat photo +func NewMessageChatChangePhoto(photo *Photo) *MessageChatChangePhoto { + messageChatChangePhotoTemp := MessageChatChangePhoto{ + tdCommon: tdCommon{Type: "messageChatChangePhoto"}, + Photo: photo, + } + + return &messageChatChangePhotoTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatChangePhoto *MessageChatChangePhoto) GetMessageContentEnum() MessageContentEnum { + return MessageChatChangePhotoType +} + +// MessageChatDeletePhoto A deleted chat photo +type MessageChatDeletePhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageChatDeletePhoto +func (messageChatDeletePhoto *MessageChatDeletePhoto) MessageType() string { + return "messageChatDeletePhoto" +} + +// NewMessageChatDeletePhoto creates a new MessageChatDeletePhoto +// +func NewMessageChatDeletePhoto() *MessageChatDeletePhoto { + messageChatDeletePhotoTemp := MessageChatDeletePhoto{ + tdCommon: tdCommon{Type: "messageChatDeletePhoto"}, + } + + return &messageChatDeletePhotoTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatDeletePhoto *MessageChatDeletePhoto) GetMessageContentEnum() MessageContentEnum { + return MessageChatDeletePhotoType +} + +// MessageChatAddMembers New chat members were added +type MessageChatAddMembers struct { + tdCommon + MemberUserIDs []int32 `json:"member_user_ids"` // User identifiers of the new members +} + +// MessageType return the string telegram-type of MessageChatAddMembers +func (messageChatAddMembers *MessageChatAddMembers) MessageType() string { + return "messageChatAddMembers" +} + +// NewMessageChatAddMembers creates a new MessageChatAddMembers +// +// @param memberUserIDs User identifiers of the new members +func NewMessageChatAddMembers(memberUserIDs []int32) *MessageChatAddMembers { + messageChatAddMembersTemp := MessageChatAddMembers{ + tdCommon: tdCommon{Type: "messageChatAddMembers"}, + MemberUserIDs: memberUserIDs, + } + + return &messageChatAddMembersTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatAddMembers *MessageChatAddMembers) GetMessageContentEnum() MessageContentEnum { + return MessageChatAddMembersType +} + +// MessageChatJoinByLink A new member joined the chat by invite link +type MessageChatJoinByLink struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageChatJoinByLink +func (messageChatJoinByLink *MessageChatJoinByLink) MessageType() string { + return "messageChatJoinByLink" +} + +// NewMessageChatJoinByLink creates a new MessageChatJoinByLink +// +func NewMessageChatJoinByLink() *MessageChatJoinByLink { + messageChatJoinByLinkTemp := MessageChatJoinByLink{ + tdCommon: tdCommon{Type: "messageChatJoinByLink"}, + } + + return &messageChatJoinByLinkTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatJoinByLink *MessageChatJoinByLink) GetMessageContentEnum() MessageContentEnum { + return MessageChatJoinByLinkType +} + +// MessageChatDeleteMember A chat member was deleted +type MessageChatDeleteMember struct { + tdCommon + UserID int32 `json:"user_id"` // User identifier of the deleted chat member +} + +// MessageType return the string telegram-type of MessageChatDeleteMember +func (messageChatDeleteMember *MessageChatDeleteMember) MessageType() string { + return "messageChatDeleteMember" +} + +// NewMessageChatDeleteMember creates a new MessageChatDeleteMember +// +// @param userID User identifier of the deleted chat member +func NewMessageChatDeleteMember(userID int32) *MessageChatDeleteMember { + messageChatDeleteMemberTemp := MessageChatDeleteMember{ + tdCommon: tdCommon{Type: "messageChatDeleteMember"}, + UserID: userID, + } + + return &messageChatDeleteMemberTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatDeleteMember *MessageChatDeleteMember) GetMessageContentEnum() MessageContentEnum { + return MessageChatDeleteMemberType +} + +// MessageChatUpgradeTo A basic group was upgraded to a supergroup and was deactivated as the result +type MessageChatUpgradeTo struct { + tdCommon + SupergroupID int32 `json:"supergroup_id"` // Identifier of the supergroup to which the basic group was upgraded +} + +// MessageType return the string telegram-type of MessageChatUpgradeTo +func (messageChatUpgradeTo *MessageChatUpgradeTo) MessageType() string { + return "messageChatUpgradeTo" +} + +// NewMessageChatUpgradeTo creates a new MessageChatUpgradeTo +// +// @param supergroupID Identifier of the supergroup to which the basic group was upgraded +func NewMessageChatUpgradeTo(supergroupID int32) *MessageChatUpgradeTo { + messageChatUpgradeToTemp := MessageChatUpgradeTo{ + tdCommon: tdCommon{Type: "messageChatUpgradeTo"}, + SupergroupID: supergroupID, + } + + return &messageChatUpgradeToTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatUpgradeTo *MessageChatUpgradeTo) GetMessageContentEnum() MessageContentEnum { + return MessageChatUpgradeToType +} + +// MessageChatUpgradeFrom A supergroup has been created from a basic group +type MessageChatUpgradeFrom struct { + tdCommon + Title string `json:"title"` // Title of the newly created supergroup + BasicGroupID int32 `json:"basic_group_id"` // The identifier of the original basic group +} + +// MessageType return the string telegram-type of MessageChatUpgradeFrom +func (messageChatUpgradeFrom *MessageChatUpgradeFrom) MessageType() string { + return "messageChatUpgradeFrom" +} + +// NewMessageChatUpgradeFrom creates a new MessageChatUpgradeFrom +// +// @param title Title of the newly created supergroup +// @param basicGroupID The identifier of the original basic group +func NewMessageChatUpgradeFrom(title string, basicGroupID int32) *MessageChatUpgradeFrom { + messageChatUpgradeFromTemp := MessageChatUpgradeFrom{ + tdCommon: tdCommon{Type: "messageChatUpgradeFrom"}, + Title: title, + BasicGroupID: basicGroupID, + } + + return &messageChatUpgradeFromTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatUpgradeFrom *MessageChatUpgradeFrom) GetMessageContentEnum() MessageContentEnum { + return MessageChatUpgradeFromType +} + +// MessagePinMessage A message has been pinned +type MessagePinMessage struct { + tdCommon + MessageID int64 `json:"message_id"` // Identifier of the pinned message, can be an identifier of a deleted message +} + +// MessageType return the string telegram-type of MessagePinMessage +func (messagePinMessage *MessagePinMessage) MessageType() string { + return "messagePinMessage" +} + +// NewMessagePinMessage creates a new MessagePinMessage +// +// @param messageID Identifier of the pinned message, can be an identifier of a deleted message +func NewMessagePinMessage(messageID int64) *MessagePinMessage { + messagePinMessageTemp := MessagePinMessage{ + tdCommon: tdCommon{Type: "messagePinMessage"}, + MessageID: messageID, + } + + return &messagePinMessageTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messagePinMessage *MessagePinMessage) GetMessageContentEnum() MessageContentEnum { + return MessagePinMessageType +} + +// MessageScreenshotTaken A screenshot of a message in the chat has been taken +type MessageScreenshotTaken struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageScreenshotTaken +func (messageScreenshotTaken *MessageScreenshotTaken) MessageType() string { + return "messageScreenshotTaken" +} + +// NewMessageScreenshotTaken creates a new MessageScreenshotTaken +// +func NewMessageScreenshotTaken() *MessageScreenshotTaken { + messageScreenshotTakenTemp := MessageScreenshotTaken{ + tdCommon: tdCommon{Type: "messageScreenshotTaken"}, + } + + return &messageScreenshotTakenTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageScreenshotTaken *MessageScreenshotTaken) GetMessageContentEnum() MessageContentEnum { + return MessageScreenshotTakenType +} + +// MessageChatSetTTL The TTL (Time To Live) setting messages in a secret chat has been changed +type MessageChatSetTTL struct { + tdCommon + TTL int32 `json:"ttl"` // New TTL +} + +// MessageType return the string telegram-type of MessageChatSetTTL +func (messageChatSetTTL *MessageChatSetTTL) MessageType() string { + return "messageChatSetTtl" +} + +// NewMessageChatSetTTL creates a new MessageChatSetTTL +// +// @param tTL New TTL +func NewMessageChatSetTTL(tTL int32) *MessageChatSetTTL { + messageChatSetTTLTemp := MessageChatSetTTL{ + tdCommon: tdCommon{Type: "messageChatSetTtl"}, + TTL: tTL, + } + + return &messageChatSetTTLTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatSetTTL *MessageChatSetTTL) GetMessageContentEnum() MessageContentEnum { + return MessageChatSetTTLType +} + +// MessageCustomServiceAction A non-standard action has happened in the chat +type MessageCustomServiceAction struct { + tdCommon + Text string `json:"text"` // Message text to be shown in the chat +} + +// MessageType return the string telegram-type of MessageCustomServiceAction +func (messageCustomServiceAction *MessageCustomServiceAction) MessageType() string { + return "messageCustomServiceAction" +} + +// NewMessageCustomServiceAction creates a new MessageCustomServiceAction +// +// @param text Message text to be shown in the chat +func NewMessageCustomServiceAction(text string) *MessageCustomServiceAction { + messageCustomServiceActionTemp := MessageCustomServiceAction{ + tdCommon: tdCommon{Type: "messageCustomServiceAction"}, + Text: text, + } + + return &messageCustomServiceActionTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageCustomServiceAction *MessageCustomServiceAction) GetMessageContentEnum() MessageContentEnum { + return MessageCustomServiceActionType +} + +// MessageGameScore A new high score was achieved in a game +type MessageGameScore struct { + tdCommon + GameMessageID int64 `json:"game_message_id"` // Identifier of the message with the game, can be an identifier of a deleted message + GameID JSONInt64 `json:"game_id"` // Identifier of the game, may be different from the games presented in the message with the game + Score int32 `json:"score"` // New score +} + +// MessageType return the string telegram-type of MessageGameScore +func (messageGameScore *MessageGameScore) MessageType() string { + return "messageGameScore" +} + +// NewMessageGameScore creates a new MessageGameScore +// +// @param gameMessageID Identifier of the message with the game, can be an identifier of a deleted message +// @param gameID Identifier of the game, may be different from the games presented in the message with the game +// @param score New score +func NewMessageGameScore(gameMessageID int64, gameID JSONInt64, score int32) *MessageGameScore { + messageGameScoreTemp := MessageGameScore{ + tdCommon: tdCommon{Type: "messageGameScore"}, + GameMessageID: gameMessageID, + GameID: gameID, + Score: score, + } + + return &messageGameScoreTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageGameScore *MessageGameScore) GetMessageContentEnum() MessageContentEnum { + return MessageGameScoreType +} + +// MessagePaymentSuccessful A payment has been completed +type MessagePaymentSuccessful struct { + tdCommon + InvoiceMessageID int64 `json:"invoice_message_id"` // Identifier of the message with the corresponding invoice; can be an identifier of a deleted message + Currency string `json:"currency"` // Currency for the price of the product + TotalAmount int64 `json:"total_amount"` // Total price for the product, in the minimal quantity of the currency +} + +// MessageType return the string telegram-type of MessagePaymentSuccessful +func (messagePaymentSuccessful *MessagePaymentSuccessful) MessageType() string { + return "messagePaymentSuccessful" +} + +// NewMessagePaymentSuccessful creates a new MessagePaymentSuccessful +// +// @param invoiceMessageID Identifier of the message with the corresponding invoice; can be an identifier of a deleted message +// @param currency Currency for the price of the product +// @param totalAmount Total price for the product, in the minimal quantity of the currency +func NewMessagePaymentSuccessful(invoiceMessageID int64, currency string, totalAmount int64) *MessagePaymentSuccessful { + messagePaymentSuccessfulTemp := MessagePaymentSuccessful{ + tdCommon: tdCommon{Type: "messagePaymentSuccessful"}, + InvoiceMessageID: invoiceMessageID, + Currency: currency, + TotalAmount: totalAmount, + } + + return &messagePaymentSuccessfulTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messagePaymentSuccessful *MessagePaymentSuccessful) GetMessageContentEnum() MessageContentEnum { + return MessagePaymentSuccessfulType +} + +// MessagePaymentSuccessfulBot A payment has been completed; for bots only +type MessagePaymentSuccessfulBot struct { + tdCommon + InvoiceMessageID int64 `json:"invoice_message_id"` // Identifier of the message with the corresponding invoice; can be an identifier of a deleted message + Currency string `json:"currency"` // Currency for price of the product + TotalAmount int64 `json:"total_amount"` // Total price for the product, in the minimal quantity of the currency + InvoicePayload []byte `json:"invoice_payload"` // Invoice payload + ShippingOptionID string `json:"shipping_option_id"` // Identifier of the shipping option chosen by the user; may be empty if not applicable + OrderInfo *OrderInfo `json:"order_info"` // Information about the order; may be null + TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` // Telegram payment identifier + ProviderPaymentChargeID string `json:"provider_payment_charge_id"` // Provider payment identifier +} + +// MessageType return the string telegram-type of MessagePaymentSuccessfulBot +func (messagePaymentSuccessfulBot *MessagePaymentSuccessfulBot) MessageType() string { + return "messagePaymentSuccessfulBot" +} + +// NewMessagePaymentSuccessfulBot creates a new MessagePaymentSuccessfulBot +// +// @param invoiceMessageID Identifier of the message with the corresponding invoice; can be an identifier of a deleted message +// @param currency Currency for price of the product +// @param totalAmount Total price for the product, in the minimal quantity of the currency +// @param invoicePayload Invoice payload +// @param shippingOptionID Identifier of the shipping option chosen by the user; may be empty if not applicable +// @param orderInfo Information about the order; may be null +// @param telegramPaymentChargeID Telegram payment identifier +// @param providerPaymentChargeID Provider payment identifier +func NewMessagePaymentSuccessfulBot(invoiceMessageID int64, currency string, totalAmount int64, invoicePayload []byte, shippingOptionID string, orderInfo *OrderInfo, telegramPaymentChargeID string, providerPaymentChargeID string) *MessagePaymentSuccessfulBot { + messagePaymentSuccessfulBotTemp := MessagePaymentSuccessfulBot{ + tdCommon: tdCommon{Type: "messagePaymentSuccessfulBot"}, + InvoiceMessageID: invoiceMessageID, + Currency: currency, + TotalAmount: totalAmount, + InvoicePayload: invoicePayload, + ShippingOptionID: shippingOptionID, + OrderInfo: orderInfo, + TelegramPaymentChargeID: telegramPaymentChargeID, + ProviderPaymentChargeID: providerPaymentChargeID, + } + + return &messagePaymentSuccessfulBotTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messagePaymentSuccessfulBot *MessagePaymentSuccessfulBot) GetMessageContentEnum() MessageContentEnum { + return MessagePaymentSuccessfulBotType +} + +// MessageContactRegistered A contact has registered with Telegram +type MessageContactRegistered struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageContactRegistered +func (messageContactRegistered *MessageContactRegistered) MessageType() string { + return "messageContactRegistered" +} + +// NewMessageContactRegistered creates a new MessageContactRegistered +// +func NewMessageContactRegistered() *MessageContactRegistered { + messageContactRegisteredTemp := MessageContactRegistered{ + tdCommon: tdCommon{Type: "messageContactRegistered"}, + } + + return &messageContactRegisteredTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageContactRegistered *MessageContactRegistered) GetMessageContentEnum() MessageContentEnum { + return MessageContactRegisteredType +} + +// MessageWebsiteConnected The current user has connected a website by logging in using Telegram Login Widget on it +type MessageWebsiteConnected struct { + tdCommon + DomainName string `json:"domain_name"` // Domain name of the connected website +} + +// MessageType return the string telegram-type of MessageWebsiteConnected +func (messageWebsiteConnected *MessageWebsiteConnected) MessageType() string { + return "messageWebsiteConnected" +} + +// NewMessageWebsiteConnected creates a new MessageWebsiteConnected +// +// @param domainName Domain name of the connected website +func NewMessageWebsiteConnected(domainName string) *MessageWebsiteConnected { + messageWebsiteConnectedTemp := MessageWebsiteConnected{ + tdCommon: tdCommon{Type: "messageWebsiteConnected"}, + DomainName: domainName, + } + + return &messageWebsiteConnectedTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageWebsiteConnected *MessageWebsiteConnected) GetMessageContentEnum() MessageContentEnum { + return MessageWebsiteConnectedType +} + +// MessagePassportDataSent Telegram Passport data has been sent +type MessagePassportDataSent struct { + tdCommon + Types []PassportElementType `json:"types"` // List of Telegram Passport element types sent +} + +// MessageType return the string telegram-type of MessagePassportDataSent +func (messagePassportDataSent *MessagePassportDataSent) MessageType() string { + return "messagePassportDataSent" +} + +// NewMessagePassportDataSent creates a new MessagePassportDataSent +// +// @param typeParams List of Telegram Passport element types sent +func NewMessagePassportDataSent(typeParams []PassportElementType) *MessagePassportDataSent { + messagePassportDataSentTemp := MessagePassportDataSent{ + tdCommon: tdCommon{Type: "messagePassportDataSent"}, + Types: typeParams, + } + + return &messagePassportDataSentTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messagePassportDataSent *MessagePassportDataSent) GetMessageContentEnum() MessageContentEnum { + return MessagePassportDataSentType +} + +// MessagePassportDataReceived Telegram Passport data has been received; for bots only +type MessagePassportDataReceived struct { + tdCommon + Elements []EncryptedPassportElement `json:"elements"` // List of received Telegram Passport elements + Credentials *EncryptedCredentials `json:"credentials"` // Encrypted data credentials +} + +// MessageType return the string telegram-type of MessagePassportDataReceived +func (messagePassportDataReceived *MessagePassportDataReceived) MessageType() string { + return "messagePassportDataReceived" +} + +// NewMessagePassportDataReceived creates a new MessagePassportDataReceived +// +// @param elements List of received Telegram Passport elements +// @param credentials Encrypted data credentials +func NewMessagePassportDataReceived(elements []EncryptedPassportElement, credentials *EncryptedCredentials) *MessagePassportDataReceived { + messagePassportDataReceivedTemp := MessagePassportDataReceived{ + tdCommon: tdCommon{Type: "messagePassportDataReceived"}, + Elements: elements, + Credentials: credentials, + } + + return &messagePassportDataReceivedTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messagePassportDataReceived *MessagePassportDataReceived) GetMessageContentEnum() MessageContentEnum { + return MessagePassportDataReceivedType +} + +// MessageUnsupported Message content that is not supported by the client +type MessageUnsupported struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageUnsupported +func (messageUnsupported *MessageUnsupported) MessageType() string { + return "messageUnsupported" +} + +// NewMessageUnsupported creates a new MessageUnsupported +// +func NewMessageUnsupported() *MessageUnsupported { + messageUnsupportedTemp := MessageUnsupported{ + tdCommon: tdCommon{Type: "messageUnsupported"}, + } + + return &messageUnsupportedTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageUnsupported *MessageUnsupported) GetMessageContentEnum() MessageContentEnum { + return MessageUnsupportedType +} + +// TextEntityTypeMention A mention of a user by their username +type TextEntityTypeMention struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeMention +func (textEntityTypeMention *TextEntityTypeMention) MessageType() string { + return "textEntityTypeMention" +} + +// NewTextEntityTypeMention creates a new TextEntityTypeMention +// +func NewTextEntityTypeMention() *TextEntityTypeMention { + textEntityTypeMentionTemp := TextEntityTypeMention{ + tdCommon: tdCommon{Type: "textEntityTypeMention"}, + } + + return &textEntityTypeMentionTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeMention *TextEntityTypeMention) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeMentionType +} + +// TextEntityTypeHashtag A hashtag text, beginning with "#" +type TextEntityTypeHashtag struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeHashtag +func (textEntityTypeHashtag *TextEntityTypeHashtag) MessageType() string { + return "textEntityTypeHashtag" +} + +// NewTextEntityTypeHashtag creates a new TextEntityTypeHashtag +// +func NewTextEntityTypeHashtag() *TextEntityTypeHashtag { + textEntityTypeHashtagTemp := TextEntityTypeHashtag{ + tdCommon: tdCommon{Type: "textEntityTypeHashtag"}, + } + + return &textEntityTypeHashtagTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeHashtag *TextEntityTypeHashtag) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeHashtagType +} + +// TextEntityTypeCashtag A cashtag text, beginning with "$" and consisting of capital english letters (i.e. "$USD") +type TextEntityTypeCashtag struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeCashtag +func (textEntityTypeCashtag *TextEntityTypeCashtag) MessageType() string { + return "textEntityTypeCashtag" +} + +// NewTextEntityTypeCashtag creates a new TextEntityTypeCashtag +// +func NewTextEntityTypeCashtag() *TextEntityTypeCashtag { + textEntityTypeCashtagTemp := TextEntityTypeCashtag{ + tdCommon: tdCommon{Type: "textEntityTypeCashtag"}, + } + + return &textEntityTypeCashtagTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeCashtag *TextEntityTypeCashtag) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeCashtagType +} + +// TextEntityTypeBotCommand A bot command, beginning with "/". This shouldn't be highlighted if there are no bots in the chat +type TextEntityTypeBotCommand struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeBotCommand +func (textEntityTypeBotCommand *TextEntityTypeBotCommand) MessageType() string { + return "textEntityTypeBotCommand" +} + +// NewTextEntityTypeBotCommand creates a new TextEntityTypeBotCommand +// +func NewTextEntityTypeBotCommand() *TextEntityTypeBotCommand { + textEntityTypeBotCommandTemp := TextEntityTypeBotCommand{ + tdCommon: tdCommon{Type: "textEntityTypeBotCommand"}, + } + + return &textEntityTypeBotCommandTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeBotCommand *TextEntityTypeBotCommand) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeBotCommandType +} + +// TextEntityTypeURL An HTTP URL +type TextEntityTypeURL struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeURL +func (textEntityTypeURL *TextEntityTypeURL) MessageType() string { + return "textEntityTypeUrl" +} + +// NewTextEntityTypeURL creates a new TextEntityTypeURL +// +func NewTextEntityTypeURL() *TextEntityTypeURL { + textEntityTypeURLTemp := TextEntityTypeURL{ + tdCommon: tdCommon{Type: "textEntityTypeUrl"}, + } + + return &textEntityTypeURLTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeURL *TextEntityTypeURL) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeURLType +} + +// TextEntityTypeEmailAddress An email address +type TextEntityTypeEmailAddress struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeEmailAddress +func (textEntityTypeEmailAddress *TextEntityTypeEmailAddress) MessageType() string { + return "textEntityTypeEmailAddress" +} + +// NewTextEntityTypeEmailAddress creates a new TextEntityTypeEmailAddress +// +func NewTextEntityTypeEmailAddress() *TextEntityTypeEmailAddress { + textEntityTypeEmailAddressTemp := TextEntityTypeEmailAddress{ + tdCommon: tdCommon{Type: "textEntityTypeEmailAddress"}, + } + + return &textEntityTypeEmailAddressTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeEmailAddress *TextEntityTypeEmailAddress) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeEmailAddressType +} + +// TextEntityTypeBold A bold text +type TextEntityTypeBold struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeBold +func (textEntityTypeBold *TextEntityTypeBold) MessageType() string { + return "textEntityTypeBold" +} + +// NewTextEntityTypeBold creates a new TextEntityTypeBold +// +func NewTextEntityTypeBold() *TextEntityTypeBold { + textEntityTypeBoldTemp := TextEntityTypeBold{ + tdCommon: tdCommon{Type: "textEntityTypeBold"}, + } + + return &textEntityTypeBoldTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeBold *TextEntityTypeBold) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeBoldType +} + +// TextEntityTypeItalic An italic text +type TextEntityTypeItalic struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeItalic +func (textEntityTypeItalic *TextEntityTypeItalic) MessageType() string { + return "textEntityTypeItalic" +} + +// NewTextEntityTypeItalic creates a new TextEntityTypeItalic +// +func NewTextEntityTypeItalic() *TextEntityTypeItalic { + textEntityTypeItalicTemp := TextEntityTypeItalic{ + tdCommon: tdCommon{Type: "textEntityTypeItalic"}, + } + + return &textEntityTypeItalicTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeItalic *TextEntityTypeItalic) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeItalicType +} + +// TextEntityTypeCode Text that must be formatted as if inside a code HTML tag +type TextEntityTypeCode struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeCode +func (textEntityTypeCode *TextEntityTypeCode) MessageType() string { + return "textEntityTypeCode" +} + +// NewTextEntityTypeCode creates a new TextEntityTypeCode +// +func NewTextEntityTypeCode() *TextEntityTypeCode { + textEntityTypeCodeTemp := TextEntityTypeCode{ + tdCommon: tdCommon{Type: "textEntityTypeCode"}, + } + + return &textEntityTypeCodeTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeCode *TextEntityTypeCode) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeCodeType +} + +// TextEntityTypePre Text that must be formatted as if inside a pre HTML tag +type TextEntityTypePre struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypePre +func (textEntityTypePre *TextEntityTypePre) MessageType() string { + return "textEntityTypePre" +} + +// NewTextEntityTypePre creates a new TextEntityTypePre +// +func NewTextEntityTypePre() *TextEntityTypePre { + textEntityTypePreTemp := TextEntityTypePre{ + tdCommon: tdCommon{Type: "textEntityTypePre"}, + } + + return &textEntityTypePreTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypePre *TextEntityTypePre) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypePreType +} + +// TextEntityTypePreCode Text that must be formatted as if inside pre, and code HTML tags +type TextEntityTypePreCode struct { + tdCommon + Language string `json:"language"` // Programming language of the code; as defined by the sender +} + +// MessageType return the string telegram-type of TextEntityTypePreCode +func (textEntityTypePreCode *TextEntityTypePreCode) MessageType() string { + return "textEntityTypePreCode" +} + +// NewTextEntityTypePreCode creates a new TextEntityTypePreCode +// +// @param language Programming language of the code; as defined by the sender +func NewTextEntityTypePreCode(language string) *TextEntityTypePreCode { + textEntityTypePreCodeTemp := TextEntityTypePreCode{ + tdCommon: tdCommon{Type: "textEntityTypePreCode"}, + Language: language, + } + + return &textEntityTypePreCodeTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypePreCode *TextEntityTypePreCode) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypePreCodeType +} + +// TextEntityTypeTextURL A text description shown instead of a raw URL +type TextEntityTypeTextURL struct { + tdCommon + URL string `json:"url"` // HTTP or tg:// URL to be opened when the link is clicked +} + +// MessageType return the string telegram-type of TextEntityTypeTextURL +func (textEntityTypeTextURL *TextEntityTypeTextURL) MessageType() string { + return "textEntityTypeTextUrl" +} + +// NewTextEntityTypeTextURL creates a new TextEntityTypeTextURL +// +// @param uRL HTTP or tg:// URL to be opened when the link is clicked +func NewTextEntityTypeTextURL(uRL string) *TextEntityTypeTextURL { + textEntityTypeTextURLTemp := TextEntityTypeTextURL{ + tdCommon: tdCommon{Type: "textEntityTypeTextUrl"}, + URL: uRL, + } + + return &textEntityTypeTextURLTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeTextURL *TextEntityTypeTextURL) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeTextURLType +} + +// TextEntityTypeMentionName A text shows instead of a raw mention of the user (e.g., when the user has no username) +type TextEntityTypeMentionName struct { + tdCommon + UserID int32 `json:"user_id"` // Identifier of the mentioned user +} + +// MessageType return the string telegram-type of TextEntityTypeMentionName +func (textEntityTypeMentionName *TextEntityTypeMentionName) MessageType() string { + return "textEntityTypeMentionName" +} + +// NewTextEntityTypeMentionName creates a new TextEntityTypeMentionName +// +// @param userID Identifier of the mentioned user +func NewTextEntityTypeMentionName(userID int32) *TextEntityTypeMentionName { + textEntityTypeMentionNameTemp := TextEntityTypeMentionName{ + tdCommon: tdCommon{Type: "textEntityTypeMentionName"}, + UserID: userID, + } + + return &textEntityTypeMentionNameTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeMentionName *TextEntityTypeMentionName) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeMentionNameType +} + +// TextEntityTypePhoneNumber A phone number +type TextEntityTypePhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypePhoneNumber +func (textEntityTypePhoneNumber *TextEntityTypePhoneNumber) MessageType() string { + return "textEntityTypePhoneNumber" +} + +// NewTextEntityTypePhoneNumber creates a new TextEntityTypePhoneNumber +// +func NewTextEntityTypePhoneNumber() *TextEntityTypePhoneNumber { + textEntityTypePhoneNumberTemp := TextEntityTypePhoneNumber{ + tdCommon: tdCommon{Type: "textEntityTypePhoneNumber"}, + } + + return &textEntityTypePhoneNumberTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypePhoneNumber *TextEntityTypePhoneNumber) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypePhoneNumberType +} + +// InputThumbnail A thumbnail to be sent along with a file; should be in JPEG or WEBP format for stickers, and less than 200 kB in size +type InputThumbnail struct { + tdCommon + Thumbnail InputFile `json:"thumbnail"` // Thumbnail file to send. Sending thumbnails by file_id is currently not supported + Width int32 `json:"width"` // Thumbnail width, usually shouldn't exceed 90. Use 0 if unknown + Height int32 `json:"height"` // Thumbnail height, usually shouldn't exceed 90. Use 0 if unknown +} + +// MessageType return the string telegram-type of InputThumbnail +func (inputThumbnail *InputThumbnail) MessageType() string { + return "inputThumbnail" +} + +// NewInputThumbnail creates a new InputThumbnail +// +// @param thumbnail Thumbnail file to send. Sending thumbnails by file_id is currently not supported +// @param width Thumbnail width, usually shouldn't exceed 90. Use 0 if unknown +// @param height Thumbnail height, usually shouldn't exceed 90. Use 0 if unknown +func NewInputThumbnail(thumbnail InputFile, width int32, height int32) *InputThumbnail { + inputThumbnailTemp := InputThumbnail{ + tdCommon: tdCommon{Type: "inputThumbnail"}, + Thumbnail: thumbnail, + Width: width, + Height: height, + } + + return &inputThumbnailTemp +} + +// UnmarshalJSON unmarshal to json +func (inputThumbnail *InputThumbnail) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Width int32 `json:"width"` // Thumbnail width, usually shouldn't exceed 90. Use 0 if unknown + Height int32 `json:"height"` // Thumbnail height, usually shouldn't exceed 90. Use 0 if unknown + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputThumbnail.tdCommon = tempObj.tdCommon + inputThumbnail.Width = tempObj.Width + inputThumbnail.Height = tempObj.Height + + fieldThumbnail, _ := unmarshalInputFile(objMap["thumbnail"]) + inputThumbnail.Thumbnail = fieldThumbnail + + return nil +} + +// InputMessageText A text message +type InputMessageText struct { + tdCommon + Text *FormattedText `json:"text"` // Formatted text to be sent; 1-GetOption("message_text_length_max") characters. Only Bold, Italic, Code, Pre, PreCode and TextUrl entities are allowed to be specified manually + DisableWebPagePreview bool `json:"disable_web_page_preview"` // True, if rich web page previews for URLs in the message text should be disabled + ClearDraft bool `json:"clear_draft"` // True, if a chat message draft should be deleted +} + +// MessageType return the string telegram-type of InputMessageText +func (inputMessageText *InputMessageText) MessageType() string { + return "inputMessageText" +} + +// NewInputMessageText creates a new InputMessageText +// +// @param text Formatted text to be sent; 1-GetOption("message_text_length_max") characters. Only Bold, Italic, Code, Pre, PreCode and TextUrl entities are allowed to be specified manually +// @param disableWebPagePreview True, if rich web page previews for URLs in the message text should be disabled +// @param clearDraft True, if a chat message draft should be deleted +func NewInputMessageText(text *FormattedText, disableWebPagePreview bool, clearDraft bool) *InputMessageText { + inputMessageTextTemp := InputMessageText{ + tdCommon: tdCommon{Type: "inputMessageText"}, + Text: text, + DisableWebPagePreview: disableWebPagePreview, + ClearDraft: clearDraft, + } + + return &inputMessageTextTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageText *InputMessageText) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageTextType +} + +// InputMessageAnimation An animation message (GIF-style). +type InputMessageAnimation struct { + tdCommon + Animation InputFile `json:"animation"` // Animation file to be sent + Thumbnail *InputThumbnail `json:"thumbnail"` // Animation thumbnail, if available + Duration int32 `json:"duration"` // Duration of the animation, in seconds + Width int32 `json:"width"` // Width of the animation; may be replaced by the server + Height int32 `json:"height"` // Height of the animation; may be replaced by the server + Caption *FormattedText `json:"caption"` // Animation caption; 0-GetOption("message_caption_length_max") characters +} + +// MessageType return the string telegram-type of InputMessageAnimation +func (inputMessageAnimation *InputMessageAnimation) MessageType() string { + return "inputMessageAnimation" +} + +// NewInputMessageAnimation creates a new InputMessageAnimation +// +// @param animation Animation file to be sent +// @param thumbnail Animation thumbnail, if available +// @param duration Duration of the animation, in seconds +// @param width Width of the animation; may be replaced by the server +// @param height Height of the animation; may be replaced by the server +// @param caption Animation caption; 0-GetOption("message_caption_length_max") characters +func NewInputMessageAnimation(animation InputFile, thumbnail *InputThumbnail, duration int32, width int32, height int32, caption *FormattedText) *InputMessageAnimation { + inputMessageAnimationTemp := InputMessageAnimation{ + tdCommon: tdCommon{Type: "inputMessageAnimation"}, + Animation: animation, + Thumbnail: thumbnail, + Duration: duration, + Width: width, + Height: height, + Caption: caption, + } + + return &inputMessageAnimationTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessageAnimation *InputMessageAnimation) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Thumbnail *InputThumbnail `json:"thumbnail"` // Animation thumbnail, if available + Duration int32 `json:"duration"` // Duration of the animation, in seconds + Width int32 `json:"width"` // Width of the animation; may be replaced by the server + Height int32 `json:"height"` // Height of the animation; may be replaced by the server + Caption *FormattedText `json:"caption"` // Animation caption; 0-GetOption("message_caption_length_max") characters + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessageAnimation.tdCommon = tempObj.tdCommon + inputMessageAnimation.Thumbnail = tempObj.Thumbnail + inputMessageAnimation.Duration = tempObj.Duration + inputMessageAnimation.Width = tempObj.Width + inputMessageAnimation.Height = tempObj.Height + inputMessageAnimation.Caption = tempObj.Caption + + fieldAnimation, _ := unmarshalInputFile(objMap["animation"]) + inputMessageAnimation.Animation = fieldAnimation + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageAnimation *InputMessageAnimation) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageAnimationType +} + +// InputMessageAudio An audio message +type InputMessageAudio struct { + tdCommon + Audio InputFile `json:"audio"` // Audio file to be sent + AlbumCoverThumbnail *InputThumbnail `json:"album_cover_thumbnail"` // Thumbnail of the cover for the album, if available + Duration int32 `json:"duration"` // Duration of the audio, in seconds; may be replaced by the server + Title string `json:"title"` // Title of the audio; 0-64 characters; may be replaced by the server + Performer string `json:"performer"` // Performer of the audio; 0-64 characters, may be replaced by the server + Caption *FormattedText `json:"caption"` // Audio caption; 0-GetOption("message_caption_length_max") characters +} + +// MessageType return the string telegram-type of InputMessageAudio +func (inputMessageAudio *InputMessageAudio) MessageType() string { + return "inputMessageAudio" +} + +// NewInputMessageAudio creates a new InputMessageAudio +// +// @param audio Audio file to be sent +// @param albumCoverThumbnail Thumbnail of the cover for the album, if available +// @param duration Duration of the audio, in seconds; may be replaced by the server +// @param title Title of the audio; 0-64 characters; may be replaced by the server +// @param performer Performer of the audio; 0-64 characters, may be replaced by the server +// @param caption Audio caption; 0-GetOption("message_caption_length_max") characters +func NewInputMessageAudio(audio InputFile, albumCoverThumbnail *InputThumbnail, duration int32, title string, performer string, caption *FormattedText) *InputMessageAudio { + inputMessageAudioTemp := InputMessageAudio{ + tdCommon: tdCommon{Type: "inputMessageAudio"}, + Audio: audio, + AlbumCoverThumbnail: albumCoverThumbnail, + Duration: duration, + Title: title, + Performer: performer, + Caption: caption, + } + + return &inputMessageAudioTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessageAudio *InputMessageAudio) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + AlbumCoverThumbnail *InputThumbnail `json:"album_cover_thumbnail"` // Thumbnail of the cover for the album, if available + Duration int32 `json:"duration"` // Duration of the audio, in seconds; may be replaced by the server + Title string `json:"title"` // Title of the audio; 0-64 characters; may be replaced by the server + Performer string `json:"performer"` // Performer of the audio; 0-64 characters, may be replaced by the server + Caption *FormattedText `json:"caption"` // Audio caption; 0-GetOption("message_caption_length_max") characters + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessageAudio.tdCommon = tempObj.tdCommon + inputMessageAudio.AlbumCoverThumbnail = tempObj.AlbumCoverThumbnail + inputMessageAudio.Duration = tempObj.Duration + inputMessageAudio.Title = tempObj.Title + inputMessageAudio.Performer = tempObj.Performer + inputMessageAudio.Caption = tempObj.Caption + + fieldAudio, _ := unmarshalInputFile(objMap["audio"]) + inputMessageAudio.Audio = fieldAudio + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageAudio *InputMessageAudio) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageAudioType +} + +// InputMessageDocument A document message (general file) +type InputMessageDocument struct { + tdCommon + Document InputFile `json:"document"` // Document to be sent + Thumbnail *InputThumbnail `json:"thumbnail"` // Document thumbnail, if available + Caption *FormattedText `json:"caption"` // Document caption; 0-GetOption("message_caption_length_max") characters +} + +// MessageType return the string telegram-type of InputMessageDocument +func (inputMessageDocument *InputMessageDocument) MessageType() string { + return "inputMessageDocument" +} + +// NewInputMessageDocument creates a new InputMessageDocument +// +// @param document Document to be sent +// @param thumbnail Document thumbnail, if available +// @param caption Document caption; 0-GetOption("message_caption_length_max") characters +func NewInputMessageDocument(document InputFile, thumbnail *InputThumbnail, caption *FormattedText) *InputMessageDocument { + inputMessageDocumentTemp := InputMessageDocument{ + tdCommon: tdCommon{Type: "inputMessageDocument"}, + Document: document, + Thumbnail: thumbnail, + Caption: caption, + } + + return &inputMessageDocumentTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessageDocument *InputMessageDocument) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Thumbnail *InputThumbnail `json:"thumbnail"` // Document thumbnail, if available + Caption *FormattedText `json:"caption"` // Document caption; 0-GetOption("message_caption_length_max") characters + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessageDocument.tdCommon = tempObj.tdCommon + inputMessageDocument.Thumbnail = tempObj.Thumbnail + inputMessageDocument.Caption = tempObj.Caption + + fieldDocument, _ := unmarshalInputFile(objMap["document"]) + inputMessageDocument.Document = fieldDocument + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageDocument *InputMessageDocument) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageDocumentType +} + +// InputMessagePhoto A photo message +type InputMessagePhoto struct { + tdCommon + Photo InputFile `json:"photo"` // Photo to send + Thumbnail *InputThumbnail `json:"thumbnail"` // Photo thumbnail to be sent, this is sent to the other party in secret chats only + AddedStickerFileIDs []int32 `json:"added_sticker_file_ids"` // File identifiers of the stickers added to the photo, if applicable + Width int32 `json:"width"` // Photo width + Height int32 `json:"height"` // Photo height + Caption *FormattedText `json:"caption"` // Photo caption; 0-GetOption("message_caption_length_max") characters + TTL int32 `json:"ttl"` // Photo TTL (Time To Live), in seconds (0-60). A non-zero TTL can be specified only in private chats +} + +// MessageType return the string telegram-type of InputMessagePhoto +func (inputMessagePhoto *InputMessagePhoto) MessageType() string { + return "inputMessagePhoto" +} + +// NewInputMessagePhoto creates a new InputMessagePhoto +// +// @param photo Photo to send +// @param thumbnail Photo thumbnail to be sent, this is sent to the other party in secret chats only +// @param addedStickerFileIDs File identifiers of the stickers added to the photo, if applicable +// @param width Photo width +// @param height Photo height +// @param caption Photo caption; 0-GetOption("message_caption_length_max") characters +// @param tTL Photo TTL (Time To Live), in seconds (0-60). A non-zero TTL can be specified only in private chats +func NewInputMessagePhoto(photo InputFile, thumbnail *InputThumbnail, addedStickerFileIDs []int32, width int32, height int32, caption *FormattedText, tTL int32) *InputMessagePhoto { + inputMessagePhotoTemp := InputMessagePhoto{ + tdCommon: tdCommon{Type: "inputMessagePhoto"}, + Photo: photo, + Thumbnail: thumbnail, + AddedStickerFileIDs: addedStickerFileIDs, + Width: width, + Height: height, + Caption: caption, + TTL: tTL, + } + + return &inputMessagePhotoTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessagePhoto *InputMessagePhoto) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Thumbnail *InputThumbnail `json:"thumbnail"` // Photo thumbnail to be sent, this is sent to the other party in secret chats only + AddedStickerFileIDs []int32 `json:"added_sticker_file_ids"` // File identifiers of the stickers added to the photo, if applicable + Width int32 `json:"width"` // Photo width + Height int32 `json:"height"` // Photo height + Caption *FormattedText `json:"caption"` // Photo caption; 0-GetOption("message_caption_length_max") characters + TTL int32 `json:"ttl"` // Photo TTL (Time To Live), in seconds (0-60). A non-zero TTL can be specified only in private chats + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessagePhoto.tdCommon = tempObj.tdCommon + inputMessagePhoto.Thumbnail = tempObj.Thumbnail + inputMessagePhoto.AddedStickerFileIDs = tempObj.AddedStickerFileIDs + inputMessagePhoto.Width = tempObj.Width + inputMessagePhoto.Height = tempObj.Height + inputMessagePhoto.Caption = tempObj.Caption + inputMessagePhoto.TTL = tempObj.TTL + + fieldPhoto, _ := unmarshalInputFile(objMap["photo"]) + inputMessagePhoto.Photo = fieldPhoto + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessagePhoto *InputMessagePhoto) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessagePhotoType +} + +// InputMessageSticker A sticker message +type InputMessageSticker struct { + tdCommon + Sticker InputFile `json:"sticker"` // Sticker to be sent + Thumbnail *InputThumbnail `json:"thumbnail"` // Sticker thumbnail, if available + Width int32 `json:"width"` // Sticker width + Height int32 `json:"height"` // Sticker height +} + +// MessageType return the string telegram-type of InputMessageSticker +func (inputMessageSticker *InputMessageSticker) MessageType() string { + return "inputMessageSticker" +} + +// NewInputMessageSticker creates a new InputMessageSticker +// +// @param sticker Sticker to be sent +// @param thumbnail Sticker thumbnail, if available +// @param width Sticker width +// @param height Sticker height +func NewInputMessageSticker(sticker InputFile, thumbnail *InputThumbnail, width int32, height int32) *InputMessageSticker { + inputMessageStickerTemp := InputMessageSticker{ + tdCommon: tdCommon{Type: "inputMessageSticker"}, + Sticker: sticker, + Thumbnail: thumbnail, + Width: width, + Height: height, + } + + return &inputMessageStickerTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessageSticker *InputMessageSticker) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Thumbnail *InputThumbnail `json:"thumbnail"` // Sticker thumbnail, if available + Width int32 `json:"width"` // Sticker width + Height int32 `json:"height"` // Sticker height + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessageSticker.tdCommon = tempObj.tdCommon + inputMessageSticker.Thumbnail = tempObj.Thumbnail + inputMessageSticker.Width = tempObj.Width + inputMessageSticker.Height = tempObj.Height + + fieldSticker, _ := unmarshalInputFile(objMap["sticker"]) + inputMessageSticker.Sticker = fieldSticker + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageSticker *InputMessageSticker) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageStickerType +} + +// InputMessageVideo A video message +type InputMessageVideo struct { + tdCommon + Video InputFile `json:"video"` // Video to be sent + Thumbnail *InputThumbnail `json:"thumbnail"` // Video thumbnail, if available + AddedStickerFileIDs []int32 `json:"added_sticker_file_ids"` // File identifiers of the stickers added to the video, if applicable + Duration int32 `json:"duration"` // Duration of the video, in seconds + Width int32 `json:"width"` // Video width + Height int32 `json:"height"` // Video height + SupportsStreaming bool `json:"supports_streaming"` // True, if the video should be tried to be streamed + Caption *FormattedText `json:"caption"` // Video caption; 0-GetOption("message_caption_length_max") characters + TTL int32 `json:"ttl"` // Video TTL (Time To Live), in seconds (0-60). A non-zero TTL can be specified only in private chats +} + +// MessageType return the string telegram-type of InputMessageVideo +func (inputMessageVideo *InputMessageVideo) MessageType() string { + return "inputMessageVideo" +} + +// NewInputMessageVideo creates a new InputMessageVideo +// +// @param video Video to be sent +// @param thumbnail Video thumbnail, if available +// @param addedStickerFileIDs File identifiers of the stickers added to the video, if applicable +// @param duration Duration of the video, in seconds +// @param width Video width +// @param height Video height +// @param supportsStreaming True, if the video should be tried to be streamed +// @param caption Video caption; 0-GetOption("message_caption_length_max") characters +// @param tTL Video TTL (Time To Live), in seconds (0-60). A non-zero TTL can be specified only in private chats +func NewInputMessageVideo(video InputFile, thumbnail *InputThumbnail, addedStickerFileIDs []int32, duration int32, width int32, height int32, supportsStreaming bool, caption *FormattedText, tTL int32) *InputMessageVideo { + inputMessageVideoTemp := InputMessageVideo{ + tdCommon: tdCommon{Type: "inputMessageVideo"}, + Video: video, + Thumbnail: thumbnail, + AddedStickerFileIDs: addedStickerFileIDs, + Duration: duration, + Width: width, + Height: height, + SupportsStreaming: supportsStreaming, + Caption: caption, + TTL: tTL, + } + + return &inputMessageVideoTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessageVideo *InputMessageVideo) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Thumbnail *InputThumbnail `json:"thumbnail"` // Video thumbnail, if available + AddedStickerFileIDs []int32 `json:"added_sticker_file_ids"` // File identifiers of the stickers added to the video, if applicable + Duration int32 `json:"duration"` // Duration of the video, in seconds + Width int32 `json:"width"` // Video width + Height int32 `json:"height"` // Video height + SupportsStreaming bool `json:"supports_streaming"` // True, if the video should be tried to be streamed + Caption *FormattedText `json:"caption"` // Video caption; 0-GetOption("message_caption_length_max") characters + TTL int32 `json:"ttl"` // Video TTL (Time To Live), in seconds (0-60). A non-zero TTL can be specified only in private chats + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessageVideo.tdCommon = tempObj.tdCommon + inputMessageVideo.Thumbnail = tempObj.Thumbnail + inputMessageVideo.AddedStickerFileIDs = tempObj.AddedStickerFileIDs + inputMessageVideo.Duration = tempObj.Duration + inputMessageVideo.Width = tempObj.Width + inputMessageVideo.Height = tempObj.Height + inputMessageVideo.SupportsStreaming = tempObj.SupportsStreaming + inputMessageVideo.Caption = tempObj.Caption + inputMessageVideo.TTL = tempObj.TTL + + fieldVideo, _ := unmarshalInputFile(objMap["video"]) + inputMessageVideo.Video = fieldVideo + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageVideo *InputMessageVideo) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageVideoType +} + +// InputMessageVideoNote A video note message +type InputMessageVideoNote struct { + tdCommon + VideoNote InputFile `json:"video_note"` // Video note to be sent + Thumbnail *InputThumbnail `json:"thumbnail"` // Video thumbnail, if available + Duration int32 `json:"duration"` // Duration of the video, in seconds + Length int32 `json:"length"` // Video width and height; must be positive and not greater than 640 +} + +// MessageType return the string telegram-type of InputMessageVideoNote +func (inputMessageVideoNote *InputMessageVideoNote) MessageType() string { + return "inputMessageVideoNote" +} + +// NewInputMessageVideoNote creates a new InputMessageVideoNote +// +// @param videoNote Video note to be sent +// @param thumbnail Video thumbnail, if available +// @param duration Duration of the video, in seconds +// @param length Video width and height; must be positive and not greater than 640 +func NewInputMessageVideoNote(videoNote InputFile, thumbnail *InputThumbnail, duration int32, length int32) *InputMessageVideoNote { + inputMessageVideoNoteTemp := InputMessageVideoNote{ + tdCommon: tdCommon{Type: "inputMessageVideoNote"}, + VideoNote: videoNote, + Thumbnail: thumbnail, + Duration: duration, + Length: length, + } + + return &inputMessageVideoNoteTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessageVideoNote *InputMessageVideoNote) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Thumbnail *InputThumbnail `json:"thumbnail"` // Video thumbnail, if available + Duration int32 `json:"duration"` // Duration of the video, in seconds + Length int32 `json:"length"` // Video width and height; must be positive and not greater than 640 + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessageVideoNote.tdCommon = tempObj.tdCommon + inputMessageVideoNote.Thumbnail = tempObj.Thumbnail + inputMessageVideoNote.Duration = tempObj.Duration + inputMessageVideoNote.Length = tempObj.Length + + fieldVideoNote, _ := unmarshalInputFile(objMap["video_note"]) + inputMessageVideoNote.VideoNote = fieldVideoNote + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageVideoNote *InputMessageVideoNote) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageVideoNoteType +} + +// InputMessageVoiceNote A voice note message +type InputMessageVoiceNote struct { + tdCommon + VoiceNote InputFile `json:"voice_note"` // Voice note to be sent + Duration int32 `json:"duration"` // Duration of the voice note, in seconds + Waveform []byte `json:"waveform"` // Waveform representation of the voice note, in 5-bit format + Caption *FormattedText `json:"caption"` // Voice note caption; 0-GetOption("message_caption_length_max") characters +} + +// MessageType return the string telegram-type of InputMessageVoiceNote +func (inputMessageVoiceNote *InputMessageVoiceNote) MessageType() string { + return "inputMessageVoiceNote" +} + +// NewInputMessageVoiceNote creates a new InputMessageVoiceNote +// +// @param voiceNote Voice note to be sent +// @param duration Duration of the voice note, in seconds +// @param waveform Waveform representation of the voice note, in 5-bit format +// @param caption Voice note caption; 0-GetOption("message_caption_length_max") characters +func NewInputMessageVoiceNote(voiceNote InputFile, duration int32, waveform []byte, caption *FormattedText) *InputMessageVoiceNote { + inputMessageVoiceNoteTemp := InputMessageVoiceNote{ + tdCommon: tdCommon{Type: "inputMessageVoiceNote"}, + VoiceNote: voiceNote, + Duration: duration, + Waveform: waveform, + Caption: caption, + } + + return &inputMessageVoiceNoteTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessageVoiceNote *InputMessageVoiceNote) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Duration int32 `json:"duration"` // Duration of the voice note, in seconds + Waveform []byte `json:"waveform"` // Waveform representation of the voice note, in 5-bit format + Caption *FormattedText `json:"caption"` // Voice note caption; 0-GetOption("message_caption_length_max") characters + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessageVoiceNote.tdCommon = tempObj.tdCommon + inputMessageVoiceNote.Duration = tempObj.Duration + inputMessageVoiceNote.Waveform = tempObj.Waveform + inputMessageVoiceNote.Caption = tempObj.Caption + + fieldVoiceNote, _ := unmarshalInputFile(objMap["voice_note"]) + inputMessageVoiceNote.VoiceNote = fieldVoiceNote + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageVoiceNote *InputMessageVoiceNote) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageVoiceNoteType +} + +// InputMessageLocation A message with a location +type InputMessageLocation struct { + tdCommon + Location *Location `json:"location"` // Location to be sent + LivePeriod int32 `json:"live_period"` // Period for which the location can be updated, in seconds; should bebetween 60 and 86400 for a live location and 0 otherwise +} + +// MessageType return the string telegram-type of InputMessageLocation +func (inputMessageLocation *InputMessageLocation) MessageType() string { + return "inputMessageLocation" +} + +// NewInputMessageLocation creates a new InputMessageLocation +// +// @param location Location to be sent +// @param livePeriod Period for which the location can be updated, in seconds; should bebetween 60 and 86400 for a live location and 0 otherwise +func NewInputMessageLocation(location *Location, livePeriod int32) *InputMessageLocation { + inputMessageLocationTemp := InputMessageLocation{ + tdCommon: tdCommon{Type: "inputMessageLocation"}, + Location: location, + LivePeriod: livePeriod, + } + + return &inputMessageLocationTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageLocation *InputMessageLocation) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageLocationType +} + +// InputMessageVenue A message with information about a venue +type InputMessageVenue struct { + tdCommon + Venue *Venue `json:"venue"` // Venue to send +} + +// MessageType return the string telegram-type of InputMessageVenue +func (inputMessageVenue *InputMessageVenue) MessageType() string { + return "inputMessageVenue" +} + +// NewInputMessageVenue creates a new InputMessageVenue +// +// @param venue Venue to send +func NewInputMessageVenue(venue *Venue) *InputMessageVenue { + inputMessageVenueTemp := InputMessageVenue{ + tdCommon: tdCommon{Type: "inputMessageVenue"}, + Venue: venue, + } + + return &inputMessageVenueTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageVenue *InputMessageVenue) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageVenueType +} + +// InputMessageContact A message containing a user contact +type InputMessageContact struct { + tdCommon + Contact *Contact `json:"contact"` // Contact to send +} + +// MessageType return the string telegram-type of InputMessageContact +func (inputMessageContact *InputMessageContact) MessageType() string { + return "inputMessageContact" +} + +// NewInputMessageContact creates a new InputMessageContact +// +// @param contact Contact to send +func NewInputMessageContact(contact *Contact) *InputMessageContact { + inputMessageContactTemp := InputMessageContact{ + tdCommon: tdCommon{Type: "inputMessageContact"}, + Contact: contact, + } + + return &inputMessageContactTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageContact *InputMessageContact) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageContactType +} + +// InputMessageGame A message with a game; not supported for channels or secret chats +type InputMessageGame struct { + tdCommon + BotUserID int32 `json:"bot_user_id"` // User identifier of the bot that owns the game + GameShortName string `json:"game_short_name"` // Short name of the game +} + +// MessageType return the string telegram-type of InputMessageGame +func (inputMessageGame *InputMessageGame) MessageType() string { + return "inputMessageGame" +} + +// NewInputMessageGame creates a new InputMessageGame +// +// @param botUserID User identifier of the bot that owns the game +// @param gameShortName Short name of the game +func NewInputMessageGame(botUserID int32, gameShortName string) *InputMessageGame { + inputMessageGameTemp := InputMessageGame{ + tdCommon: tdCommon{Type: "inputMessageGame"}, + BotUserID: botUserID, + GameShortName: gameShortName, + } + + return &inputMessageGameTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageGame *InputMessageGame) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageGameType +} + +// InputMessageInvoice A message with an invoice; can be used only by bots and only in private chats +type InputMessageInvoice struct { + tdCommon + Invoice *Invoice `json:"invoice"` // Invoice + Title string `json:"title"` // Product title; 1-32 characters + Description string `json:"description"` // + PhotoURL string `json:"photo_url"` // Product photo URL; optional + PhotoSize int32 `json:"photo_size"` // Product photo size + PhotoWidth int32 `json:"photo_width"` // Product photo width + PhotoHeight int32 `json:"photo_height"` // Product photo height + Payload []byte `json:"payload"` // The invoice payload + ProviderToken string `json:"provider_token"` // Payment provider token + ProviderData string `json:"provider_data"` // JSON-encoded data about the invoice, which will be shared with the payment provider + StartParameter string `json:"start_parameter"` // Unique invoice bot start_parameter for the generation of this invoice +} + +// MessageType return the string telegram-type of InputMessageInvoice +func (inputMessageInvoice *InputMessageInvoice) MessageType() string { + return "inputMessageInvoice" +} + +// NewInputMessageInvoice creates a new InputMessageInvoice +// +// @param invoice Invoice +// @param title Product title; 1-32 characters +// @param description +// @param photoURL Product photo URL; optional +// @param photoSize Product photo size +// @param photoWidth Product photo width +// @param photoHeight Product photo height +// @param payload The invoice payload +// @param providerToken Payment provider token +// @param providerData JSON-encoded data about the invoice, which will be shared with the payment provider +// @param startParameter Unique invoice bot start_parameter for the generation of this invoice +func NewInputMessageInvoice(invoice *Invoice, title string, description string, photoURL string, photoSize int32, photoWidth int32, photoHeight int32, payload []byte, providerToken string, providerData string, startParameter string) *InputMessageInvoice { + inputMessageInvoiceTemp := InputMessageInvoice{ + tdCommon: tdCommon{Type: "inputMessageInvoice"}, + Invoice: invoice, + Title: title, + Description: description, + PhotoURL: photoURL, + PhotoSize: photoSize, + PhotoWidth: photoWidth, + PhotoHeight: photoHeight, + Payload: payload, + ProviderToken: providerToken, + ProviderData: providerData, + StartParameter: startParameter, + } + + return &inputMessageInvoiceTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageInvoice *InputMessageInvoice) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageInvoiceType +} + +// InputMessageForwarded A forwarded message +type InputMessageForwarded struct { + tdCommon + FromChatID int64 `json:"from_chat_id"` // Identifier for the chat this forwarded message came from + MessageID int64 `json:"message_id"` // Identifier of the message to forward + InGameShare bool `json:"in_game_share"` // True, if a game message should be shared within a launched game; applies only to game messages +} + +// MessageType return the string telegram-type of InputMessageForwarded +func (inputMessageForwarded *InputMessageForwarded) MessageType() string { + return "inputMessageForwarded" +} + +// NewInputMessageForwarded creates a new InputMessageForwarded +// +// @param fromChatID Identifier for the chat this forwarded message came from +// @param messageID Identifier of the message to forward +// @param inGameShare True, if a game message should be shared within a launched game; applies only to game messages +func NewInputMessageForwarded(fromChatID int64, messageID int64, inGameShare bool) *InputMessageForwarded { + inputMessageForwardedTemp := InputMessageForwarded{ + tdCommon: tdCommon{Type: "inputMessageForwarded"}, + FromChatID: fromChatID, + MessageID: messageID, + InGameShare: inGameShare, + } + + return &inputMessageForwardedTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageForwarded *InputMessageForwarded) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageForwardedType +} + +// SearchMessagesFilterEmpty Returns all found messages, no filter is applied +type SearchMessagesFilterEmpty struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterEmpty +func (searchMessagesFilterEmpty *SearchMessagesFilterEmpty) MessageType() string { + return "searchMessagesFilterEmpty" +} + +// NewSearchMessagesFilterEmpty creates a new SearchMessagesFilterEmpty +// +func NewSearchMessagesFilterEmpty() *SearchMessagesFilterEmpty { + searchMessagesFilterEmptyTemp := SearchMessagesFilterEmpty{ + tdCommon: tdCommon{Type: "searchMessagesFilterEmpty"}, + } + + return &searchMessagesFilterEmptyTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterEmpty *SearchMessagesFilterEmpty) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterEmptyType +} + +// SearchMessagesFilterAnimation Returns only animation messages +type SearchMessagesFilterAnimation struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterAnimation +func (searchMessagesFilterAnimation *SearchMessagesFilterAnimation) MessageType() string { + return "searchMessagesFilterAnimation" +} + +// NewSearchMessagesFilterAnimation creates a new SearchMessagesFilterAnimation +// +func NewSearchMessagesFilterAnimation() *SearchMessagesFilterAnimation { + searchMessagesFilterAnimationTemp := SearchMessagesFilterAnimation{ + tdCommon: tdCommon{Type: "searchMessagesFilterAnimation"}, + } + + return &searchMessagesFilterAnimationTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterAnimation *SearchMessagesFilterAnimation) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterAnimationType +} + +// SearchMessagesFilterAudio Returns only audio messages +type SearchMessagesFilterAudio struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterAudio +func (searchMessagesFilterAudio *SearchMessagesFilterAudio) MessageType() string { + return "searchMessagesFilterAudio" +} + +// NewSearchMessagesFilterAudio creates a new SearchMessagesFilterAudio +// +func NewSearchMessagesFilterAudio() *SearchMessagesFilterAudio { + searchMessagesFilterAudioTemp := SearchMessagesFilterAudio{ + tdCommon: tdCommon{Type: "searchMessagesFilterAudio"}, + } + + return &searchMessagesFilterAudioTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterAudio *SearchMessagesFilterAudio) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterAudioType +} + +// SearchMessagesFilterDocument Returns only document messages +type SearchMessagesFilterDocument struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterDocument +func (searchMessagesFilterDocument *SearchMessagesFilterDocument) MessageType() string { + return "searchMessagesFilterDocument" +} + +// NewSearchMessagesFilterDocument creates a new SearchMessagesFilterDocument +// +func NewSearchMessagesFilterDocument() *SearchMessagesFilterDocument { + searchMessagesFilterDocumentTemp := SearchMessagesFilterDocument{ + tdCommon: tdCommon{Type: "searchMessagesFilterDocument"}, + } + + return &searchMessagesFilterDocumentTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterDocument *SearchMessagesFilterDocument) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterDocumentType +} + +// SearchMessagesFilterPhoto Returns only photo messages +type SearchMessagesFilterPhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterPhoto +func (searchMessagesFilterPhoto *SearchMessagesFilterPhoto) MessageType() string { + return "searchMessagesFilterPhoto" +} + +// NewSearchMessagesFilterPhoto creates a new SearchMessagesFilterPhoto +// +func NewSearchMessagesFilterPhoto() *SearchMessagesFilterPhoto { + searchMessagesFilterPhotoTemp := SearchMessagesFilterPhoto{ + tdCommon: tdCommon{Type: "searchMessagesFilterPhoto"}, + } + + return &searchMessagesFilterPhotoTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterPhoto *SearchMessagesFilterPhoto) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterPhotoType +} + +// SearchMessagesFilterVideo Returns only video messages +type SearchMessagesFilterVideo struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterVideo +func (searchMessagesFilterVideo *SearchMessagesFilterVideo) MessageType() string { + return "searchMessagesFilterVideo" +} + +// NewSearchMessagesFilterVideo creates a new SearchMessagesFilterVideo +// +func NewSearchMessagesFilterVideo() *SearchMessagesFilterVideo { + searchMessagesFilterVideoTemp := SearchMessagesFilterVideo{ + tdCommon: tdCommon{Type: "searchMessagesFilterVideo"}, + } + + return &searchMessagesFilterVideoTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterVideo *SearchMessagesFilterVideo) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterVideoType +} + +// SearchMessagesFilterVoiceNote Returns only voice note messages +type SearchMessagesFilterVoiceNote struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterVoiceNote +func (searchMessagesFilterVoiceNote *SearchMessagesFilterVoiceNote) MessageType() string { + return "searchMessagesFilterVoiceNote" +} + +// NewSearchMessagesFilterVoiceNote creates a new SearchMessagesFilterVoiceNote +// +func NewSearchMessagesFilterVoiceNote() *SearchMessagesFilterVoiceNote { + searchMessagesFilterVoiceNoteTemp := SearchMessagesFilterVoiceNote{ + tdCommon: tdCommon{Type: "searchMessagesFilterVoiceNote"}, + } + + return &searchMessagesFilterVoiceNoteTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterVoiceNote *SearchMessagesFilterVoiceNote) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterVoiceNoteType +} + +// SearchMessagesFilterPhotoAndVideo Returns only photo and video messages +type SearchMessagesFilterPhotoAndVideo struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterPhotoAndVideo +func (searchMessagesFilterPhotoAndVideo *SearchMessagesFilterPhotoAndVideo) MessageType() string { + return "searchMessagesFilterPhotoAndVideo" +} + +// NewSearchMessagesFilterPhotoAndVideo creates a new SearchMessagesFilterPhotoAndVideo +// +func NewSearchMessagesFilterPhotoAndVideo() *SearchMessagesFilterPhotoAndVideo { + searchMessagesFilterPhotoAndVideoTemp := SearchMessagesFilterPhotoAndVideo{ + tdCommon: tdCommon{Type: "searchMessagesFilterPhotoAndVideo"}, + } + + return &searchMessagesFilterPhotoAndVideoTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterPhotoAndVideo *SearchMessagesFilterPhotoAndVideo) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterPhotoAndVideoType +} + +// SearchMessagesFilterURL Returns only messages containing URLs +type SearchMessagesFilterURL struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterURL +func (searchMessagesFilterURL *SearchMessagesFilterURL) MessageType() string { + return "searchMessagesFilterUrl" +} + +// NewSearchMessagesFilterURL creates a new SearchMessagesFilterURL +// +func NewSearchMessagesFilterURL() *SearchMessagesFilterURL { + searchMessagesFilterURLTemp := SearchMessagesFilterURL{ + tdCommon: tdCommon{Type: "searchMessagesFilterUrl"}, + } + + return &searchMessagesFilterURLTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterURL *SearchMessagesFilterURL) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterURLType +} + +// SearchMessagesFilterChatPhoto Returns only messages containing chat photos +type SearchMessagesFilterChatPhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterChatPhoto +func (searchMessagesFilterChatPhoto *SearchMessagesFilterChatPhoto) MessageType() string { + return "searchMessagesFilterChatPhoto" +} + +// NewSearchMessagesFilterChatPhoto creates a new SearchMessagesFilterChatPhoto +// +func NewSearchMessagesFilterChatPhoto() *SearchMessagesFilterChatPhoto { + searchMessagesFilterChatPhotoTemp := SearchMessagesFilterChatPhoto{ + tdCommon: tdCommon{Type: "searchMessagesFilterChatPhoto"}, + } + + return &searchMessagesFilterChatPhotoTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterChatPhoto *SearchMessagesFilterChatPhoto) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterChatPhotoType +} + +// SearchMessagesFilterCall Returns only call messages +type SearchMessagesFilterCall struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterCall +func (searchMessagesFilterCall *SearchMessagesFilterCall) MessageType() string { + return "searchMessagesFilterCall" +} + +// NewSearchMessagesFilterCall creates a new SearchMessagesFilterCall +// +func NewSearchMessagesFilterCall() *SearchMessagesFilterCall { + searchMessagesFilterCallTemp := SearchMessagesFilterCall{ + tdCommon: tdCommon{Type: "searchMessagesFilterCall"}, + } + + return &searchMessagesFilterCallTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterCall *SearchMessagesFilterCall) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterCallType +} + +// SearchMessagesFilterMissedCall Returns only incoming call messages with missed/declined discard reasons +type SearchMessagesFilterMissedCall struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterMissedCall +func (searchMessagesFilterMissedCall *SearchMessagesFilterMissedCall) MessageType() string { + return "searchMessagesFilterMissedCall" +} + +// NewSearchMessagesFilterMissedCall creates a new SearchMessagesFilterMissedCall +// +func NewSearchMessagesFilterMissedCall() *SearchMessagesFilterMissedCall { + searchMessagesFilterMissedCallTemp := SearchMessagesFilterMissedCall{ + tdCommon: tdCommon{Type: "searchMessagesFilterMissedCall"}, + } + + return &searchMessagesFilterMissedCallTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterMissedCall *SearchMessagesFilterMissedCall) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterMissedCallType +} + +// SearchMessagesFilterVideoNote Returns only video note messages +type SearchMessagesFilterVideoNote struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterVideoNote +func (searchMessagesFilterVideoNote *SearchMessagesFilterVideoNote) MessageType() string { + return "searchMessagesFilterVideoNote" +} + +// NewSearchMessagesFilterVideoNote creates a new SearchMessagesFilterVideoNote +// +func NewSearchMessagesFilterVideoNote() *SearchMessagesFilterVideoNote { + searchMessagesFilterVideoNoteTemp := SearchMessagesFilterVideoNote{ + tdCommon: tdCommon{Type: "searchMessagesFilterVideoNote"}, + } + + return &searchMessagesFilterVideoNoteTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterVideoNote *SearchMessagesFilterVideoNote) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterVideoNoteType +} + +// SearchMessagesFilterVoiceAndVideoNote Returns only voice and video note messages +type SearchMessagesFilterVoiceAndVideoNote struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterVoiceAndVideoNote +func (searchMessagesFilterVoiceAndVideoNote *SearchMessagesFilterVoiceAndVideoNote) MessageType() string { + return "searchMessagesFilterVoiceAndVideoNote" +} + +// NewSearchMessagesFilterVoiceAndVideoNote creates a new SearchMessagesFilterVoiceAndVideoNote +// +func NewSearchMessagesFilterVoiceAndVideoNote() *SearchMessagesFilterVoiceAndVideoNote { + searchMessagesFilterVoiceAndVideoNoteTemp := SearchMessagesFilterVoiceAndVideoNote{ + tdCommon: tdCommon{Type: "searchMessagesFilterVoiceAndVideoNote"}, + } + + return &searchMessagesFilterVoiceAndVideoNoteTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterVoiceAndVideoNote *SearchMessagesFilterVoiceAndVideoNote) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterVoiceAndVideoNoteType +} + +// SearchMessagesFilterMention Returns only messages with mentions of the current user, or messages that are replies to their messages +type SearchMessagesFilterMention struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterMention +func (searchMessagesFilterMention *SearchMessagesFilterMention) MessageType() string { + return "searchMessagesFilterMention" +} + +// NewSearchMessagesFilterMention creates a new SearchMessagesFilterMention +// +func NewSearchMessagesFilterMention() *SearchMessagesFilterMention { + searchMessagesFilterMentionTemp := SearchMessagesFilterMention{ + tdCommon: tdCommon{Type: "searchMessagesFilterMention"}, + } + + return &searchMessagesFilterMentionTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterMention *SearchMessagesFilterMention) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterMentionType +} + +// SearchMessagesFilterUnreadMention Returns only messages with unread mentions of the current user or messages that are replies to their messages. When using this filter the results can't be additionally filtered by a query or by the sending user +type SearchMessagesFilterUnreadMention struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterUnreadMention +func (searchMessagesFilterUnreadMention *SearchMessagesFilterUnreadMention) MessageType() string { + return "searchMessagesFilterUnreadMention" +} + +// NewSearchMessagesFilterUnreadMention creates a new SearchMessagesFilterUnreadMention +// +func NewSearchMessagesFilterUnreadMention() *SearchMessagesFilterUnreadMention { + searchMessagesFilterUnreadMentionTemp := SearchMessagesFilterUnreadMention{ + tdCommon: tdCommon{Type: "searchMessagesFilterUnreadMention"}, + } + + return &searchMessagesFilterUnreadMentionTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterUnreadMention *SearchMessagesFilterUnreadMention) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterUnreadMentionType +} + +// ChatActionTyping The user is typing a message +type ChatActionTyping struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionTyping +func (chatActionTyping *ChatActionTyping) MessageType() string { + return "chatActionTyping" +} + +// NewChatActionTyping creates a new ChatActionTyping +// +func NewChatActionTyping() *ChatActionTyping { + chatActionTypingTemp := ChatActionTyping{ + tdCommon: tdCommon{Type: "chatActionTyping"}, + } + + return &chatActionTypingTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionTyping *ChatActionTyping) GetChatActionEnum() ChatActionEnum { + return ChatActionTypingType +} + +// ChatActionRecordingVideo The user is recording a video +type ChatActionRecordingVideo struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionRecordingVideo +func (chatActionRecordingVideo *ChatActionRecordingVideo) MessageType() string { + return "chatActionRecordingVideo" +} + +// NewChatActionRecordingVideo creates a new ChatActionRecordingVideo +// +func NewChatActionRecordingVideo() *ChatActionRecordingVideo { + chatActionRecordingVideoTemp := ChatActionRecordingVideo{ + tdCommon: tdCommon{Type: "chatActionRecordingVideo"}, + } + + return &chatActionRecordingVideoTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionRecordingVideo *ChatActionRecordingVideo) GetChatActionEnum() ChatActionEnum { + return ChatActionRecordingVideoType +} + +// ChatActionUploadingVideo The user is uploading a video +type ChatActionUploadingVideo struct { + tdCommon + Progress int32 `json:"progress"` // Upload progress, as a percentage +} + +// MessageType return the string telegram-type of ChatActionUploadingVideo +func (chatActionUploadingVideo *ChatActionUploadingVideo) MessageType() string { + return "chatActionUploadingVideo" +} + +// NewChatActionUploadingVideo creates a new ChatActionUploadingVideo +// +// @param progress Upload progress, as a percentage +func NewChatActionUploadingVideo(progress int32) *ChatActionUploadingVideo { + chatActionUploadingVideoTemp := ChatActionUploadingVideo{ + tdCommon: tdCommon{Type: "chatActionUploadingVideo"}, + Progress: progress, + } + + return &chatActionUploadingVideoTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionUploadingVideo *ChatActionUploadingVideo) GetChatActionEnum() ChatActionEnum { + return ChatActionUploadingVideoType +} + +// ChatActionRecordingVoiceNote The user is recording a voice note +type ChatActionRecordingVoiceNote struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionRecordingVoiceNote +func (chatActionRecordingVoiceNote *ChatActionRecordingVoiceNote) MessageType() string { + return "chatActionRecordingVoiceNote" +} + +// NewChatActionRecordingVoiceNote creates a new ChatActionRecordingVoiceNote +// +func NewChatActionRecordingVoiceNote() *ChatActionRecordingVoiceNote { + chatActionRecordingVoiceNoteTemp := ChatActionRecordingVoiceNote{ + tdCommon: tdCommon{Type: "chatActionRecordingVoiceNote"}, + } + + return &chatActionRecordingVoiceNoteTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionRecordingVoiceNote *ChatActionRecordingVoiceNote) GetChatActionEnum() ChatActionEnum { + return ChatActionRecordingVoiceNoteType +} + +// ChatActionUploadingVoiceNote The user is uploading a voice note +type ChatActionUploadingVoiceNote struct { + tdCommon + Progress int32 `json:"progress"` // Upload progress, as a percentage +} + +// MessageType return the string telegram-type of ChatActionUploadingVoiceNote +func (chatActionUploadingVoiceNote *ChatActionUploadingVoiceNote) MessageType() string { + return "chatActionUploadingVoiceNote" +} + +// NewChatActionUploadingVoiceNote creates a new ChatActionUploadingVoiceNote +// +// @param progress Upload progress, as a percentage +func NewChatActionUploadingVoiceNote(progress int32) *ChatActionUploadingVoiceNote { + chatActionUploadingVoiceNoteTemp := ChatActionUploadingVoiceNote{ + tdCommon: tdCommon{Type: "chatActionUploadingVoiceNote"}, + Progress: progress, + } + + return &chatActionUploadingVoiceNoteTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionUploadingVoiceNote *ChatActionUploadingVoiceNote) GetChatActionEnum() ChatActionEnum { + return ChatActionUploadingVoiceNoteType +} + +// ChatActionUploadingPhoto The user is uploading a photo +type ChatActionUploadingPhoto struct { + tdCommon + Progress int32 `json:"progress"` // Upload progress, as a percentage +} + +// MessageType return the string telegram-type of ChatActionUploadingPhoto +func (chatActionUploadingPhoto *ChatActionUploadingPhoto) MessageType() string { + return "chatActionUploadingPhoto" +} + +// NewChatActionUploadingPhoto creates a new ChatActionUploadingPhoto +// +// @param progress Upload progress, as a percentage +func NewChatActionUploadingPhoto(progress int32) *ChatActionUploadingPhoto { + chatActionUploadingPhotoTemp := ChatActionUploadingPhoto{ + tdCommon: tdCommon{Type: "chatActionUploadingPhoto"}, + Progress: progress, + } + + return &chatActionUploadingPhotoTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionUploadingPhoto *ChatActionUploadingPhoto) GetChatActionEnum() ChatActionEnum { + return ChatActionUploadingPhotoType +} + +// ChatActionUploadingDocument The user is uploading a document +type ChatActionUploadingDocument struct { + tdCommon + Progress int32 `json:"progress"` // Upload progress, as a percentage +} + +// MessageType return the string telegram-type of ChatActionUploadingDocument +func (chatActionUploadingDocument *ChatActionUploadingDocument) MessageType() string { + return "chatActionUploadingDocument" +} + +// NewChatActionUploadingDocument creates a new ChatActionUploadingDocument +// +// @param progress Upload progress, as a percentage +func NewChatActionUploadingDocument(progress int32) *ChatActionUploadingDocument { + chatActionUploadingDocumentTemp := ChatActionUploadingDocument{ + tdCommon: tdCommon{Type: "chatActionUploadingDocument"}, + Progress: progress, + } + + return &chatActionUploadingDocumentTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionUploadingDocument *ChatActionUploadingDocument) GetChatActionEnum() ChatActionEnum { + return ChatActionUploadingDocumentType +} + +// ChatActionChoosingLocation The user is picking a location or venue to send +type ChatActionChoosingLocation struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionChoosingLocation +func (chatActionChoosingLocation *ChatActionChoosingLocation) MessageType() string { + return "chatActionChoosingLocation" +} + +// NewChatActionChoosingLocation creates a new ChatActionChoosingLocation +// +func NewChatActionChoosingLocation() *ChatActionChoosingLocation { + chatActionChoosingLocationTemp := ChatActionChoosingLocation{ + tdCommon: tdCommon{Type: "chatActionChoosingLocation"}, + } + + return &chatActionChoosingLocationTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionChoosingLocation *ChatActionChoosingLocation) GetChatActionEnum() ChatActionEnum { + return ChatActionChoosingLocationType +} + +// ChatActionChoosingContact The user is picking a contact to send +type ChatActionChoosingContact struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionChoosingContact +func (chatActionChoosingContact *ChatActionChoosingContact) MessageType() string { + return "chatActionChoosingContact" +} + +// NewChatActionChoosingContact creates a new ChatActionChoosingContact +// +func NewChatActionChoosingContact() *ChatActionChoosingContact { + chatActionChoosingContactTemp := ChatActionChoosingContact{ + tdCommon: tdCommon{Type: "chatActionChoosingContact"}, + } + + return &chatActionChoosingContactTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionChoosingContact *ChatActionChoosingContact) GetChatActionEnum() ChatActionEnum { + return ChatActionChoosingContactType +} + +// ChatActionStartPlayingGame The user has started to play a game +type ChatActionStartPlayingGame struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionStartPlayingGame +func (chatActionStartPlayingGame *ChatActionStartPlayingGame) MessageType() string { + return "chatActionStartPlayingGame" +} + +// NewChatActionStartPlayingGame creates a new ChatActionStartPlayingGame +// +func NewChatActionStartPlayingGame() *ChatActionStartPlayingGame { + chatActionStartPlayingGameTemp := ChatActionStartPlayingGame{ + tdCommon: tdCommon{Type: "chatActionStartPlayingGame"}, + } + + return &chatActionStartPlayingGameTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionStartPlayingGame *ChatActionStartPlayingGame) GetChatActionEnum() ChatActionEnum { + return ChatActionStartPlayingGameType +} + +// ChatActionRecordingVideoNote The user is recording a video note +type ChatActionRecordingVideoNote struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionRecordingVideoNote +func (chatActionRecordingVideoNote *ChatActionRecordingVideoNote) MessageType() string { + return "chatActionRecordingVideoNote" +} + +// NewChatActionRecordingVideoNote creates a new ChatActionRecordingVideoNote +// +func NewChatActionRecordingVideoNote() *ChatActionRecordingVideoNote { + chatActionRecordingVideoNoteTemp := ChatActionRecordingVideoNote{ + tdCommon: tdCommon{Type: "chatActionRecordingVideoNote"}, + } + + return &chatActionRecordingVideoNoteTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionRecordingVideoNote *ChatActionRecordingVideoNote) GetChatActionEnum() ChatActionEnum { + return ChatActionRecordingVideoNoteType +} + +// ChatActionUploadingVideoNote The user is uploading a video note +type ChatActionUploadingVideoNote struct { + tdCommon + Progress int32 `json:"progress"` // Upload progress, as a percentage +} + +// MessageType return the string telegram-type of ChatActionUploadingVideoNote +func (chatActionUploadingVideoNote *ChatActionUploadingVideoNote) MessageType() string { + return "chatActionUploadingVideoNote" +} + +// NewChatActionUploadingVideoNote creates a new ChatActionUploadingVideoNote +// +// @param progress Upload progress, as a percentage +func NewChatActionUploadingVideoNote(progress int32) *ChatActionUploadingVideoNote { + chatActionUploadingVideoNoteTemp := ChatActionUploadingVideoNote{ + tdCommon: tdCommon{Type: "chatActionUploadingVideoNote"}, + Progress: progress, + } + + return &chatActionUploadingVideoNoteTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionUploadingVideoNote *ChatActionUploadingVideoNote) GetChatActionEnum() ChatActionEnum { + return ChatActionUploadingVideoNoteType +} + +// ChatActionCancel The user has cancelled the previous action +type ChatActionCancel struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionCancel +func (chatActionCancel *ChatActionCancel) MessageType() string { + return "chatActionCancel" +} + +// NewChatActionCancel creates a new ChatActionCancel +// +func NewChatActionCancel() *ChatActionCancel { + chatActionCancelTemp := ChatActionCancel{ + tdCommon: tdCommon{Type: "chatActionCancel"}, + } + + return &chatActionCancelTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionCancel *ChatActionCancel) GetChatActionEnum() ChatActionEnum { + return ChatActionCancelType +} + +// UserStatusEmpty The user status was never changed +type UserStatusEmpty struct { + tdCommon +} + +// MessageType return the string telegram-type of UserStatusEmpty +func (userStatusEmpty *UserStatusEmpty) MessageType() string { + return "userStatusEmpty" +} + +// NewUserStatusEmpty creates a new UserStatusEmpty +// +func NewUserStatusEmpty() *UserStatusEmpty { + userStatusEmptyTemp := UserStatusEmpty{ + tdCommon: tdCommon{Type: "userStatusEmpty"}, + } + + return &userStatusEmptyTemp +} + +// GetUserStatusEnum return the enum type of this object +func (userStatusEmpty *UserStatusEmpty) GetUserStatusEnum() UserStatusEnum { + return UserStatusEmptyType +} + +// UserStatusOnline The user is online +type UserStatusOnline struct { + tdCommon + Expires int32 `json:"expires"` // Point in time (Unix timestamp) when the user's online status will expire +} + +// MessageType return the string telegram-type of UserStatusOnline +func (userStatusOnline *UserStatusOnline) MessageType() string { + return "userStatusOnline" +} + +// NewUserStatusOnline creates a new UserStatusOnline +// +// @param expires Point in time (Unix timestamp) when the user's online status will expire +func NewUserStatusOnline(expires int32) *UserStatusOnline { + userStatusOnlineTemp := UserStatusOnline{ + tdCommon: tdCommon{Type: "userStatusOnline"}, + Expires: expires, + } + + return &userStatusOnlineTemp +} + +// GetUserStatusEnum return the enum type of this object +func (userStatusOnline *UserStatusOnline) GetUserStatusEnum() UserStatusEnum { + return UserStatusOnlineType +} + +// UserStatusOffline The user is offline +type UserStatusOffline struct { + tdCommon + WasOnline int32 `json:"was_online"` // Point in time (Unix timestamp) when the user was last online +} + +// MessageType return the string telegram-type of UserStatusOffline +func (userStatusOffline *UserStatusOffline) MessageType() string { + return "userStatusOffline" +} + +// NewUserStatusOffline creates a new UserStatusOffline +// +// @param wasOnline Point in time (Unix timestamp) when the user was last online +func NewUserStatusOffline(wasOnline int32) *UserStatusOffline { + userStatusOfflineTemp := UserStatusOffline{ + tdCommon: tdCommon{Type: "userStatusOffline"}, + WasOnline: wasOnline, + } + + return &userStatusOfflineTemp +} + +// GetUserStatusEnum return the enum type of this object +func (userStatusOffline *UserStatusOffline) GetUserStatusEnum() UserStatusEnum { + return UserStatusOfflineType +} + +// UserStatusRecently The user was online recently +type UserStatusRecently struct { + tdCommon +} + +// MessageType return the string telegram-type of UserStatusRecently +func (userStatusRecently *UserStatusRecently) MessageType() string { + return "userStatusRecently" +} + +// NewUserStatusRecently creates a new UserStatusRecently +// +func NewUserStatusRecently() *UserStatusRecently { + userStatusRecentlyTemp := UserStatusRecently{ + tdCommon: tdCommon{Type: "userStatusRecently"}, + } + + return &userStatusRecentlyTemp +} + +// GetUserStatusEnum return the enum type of this object +func (userStatusRecently *UserStatusRecently) GetUserStatusEnum() UserStatusEnum { + return UserStatusRecentlyType +} + +// UserStatusLastWeek The user is offline, but was online last week +type UserStatusLastWeek struct { + tdCommon +} + +// MessageType return the string telegram-type of UserStatusLastWeek +func (userStatusLastWeek *UserStatusLastWeek) MessageType() string { + return "userStatusLastWeek" +} + +// NewUserStatusLastWeek creates a new UserStatusLastWeek +// +func NewUserStatusLastWeek() *UserStatusLastWeek { + userStatusLastWeekTemp := UserStatusLastWeek{ + tdCommon: tdCommon{Type: "userStatusLastWeek"}, + } + + return &userStatusLastWeekTemp +} + +// GetUserStatusEnum return the enum type of this object +func (userStatusLastWeek *UserStatusLastWeek) GetUserStatusEnum() UserStatusEnum { + return UserStatusLastWeekType +} + +// UserStatusLastMonth The user is offline, but was online last month +type UserStatusLastMonth struct { + tdCommon +} + +// MessageType return the string telegram-type of UserStatusLastMonth +func (userStatusLastMonth *UserStatusLastMonth) MessageType() string { + return "userStatusLastMonth" +} + +// NewUserStatusLastMonth creates a new UserStatusLastMonth +// +func NewUserStatusLastMonth() *UserStatusLastMonth { + userStatusLastMonthTemp := UserStatusLastMonth{ + tdCommon: tdCommon{Type: "userStatusLastMonth"}, + } + + return &userStatusLastMonthTemp +} + +// GetUserStatusEnum return the enum type of this object +func (userStatusLastMonth *UserStatusLastMonth) GetUserStatusEnum() UserStatusEnum { + return UserStatusLastMonthType +} + +// Stickers Represents a list of stickers +type Stickers struct { + tdCommon + Stickers []Sticker `json:"stickers"` // List of stickers +} + +// MessageType return the string telegram-type of Stickers +func (stickers *Stickers) MessageType() string { + return "stickers" +} + +// NewStickers creates a new Stickers +// +// @param stickers List of stickers +func NewStickers(stickers []Sticker) *Stickers { + stickersTemp := Stickers{ + tdCommon: tdCommon{Type: "stickers"}, + Stickers: stickers, + } + + return &stickersTemp +} + +// StickerEmojis Represents a list of all emoji corresponding to a sticker in a sticker set. The list is only for informational purposes, because a sticker is always sent with a fixed emoji from the corresponding Sticker object +type StickerEmojis struct { + tdCommon + Emojis []string `json:"emojis"` // List of emojis +} + +// MessageType return the string telegram-type of StickerEmojis +func (stickerEmojis *StickerEmojis) MessageType() string { + return "stickerEmojis" +} + +// NewStickerEmojis creates a new StickerEmojis +// +// @param emojis List of emojis +func NewStickerEmojis(emojis []string) *StickerEmojis { + stickerEmojisTemp := StickerEmojis{ + tdCommon: tdCommon{Type: "stickerEmojis"}, + Emojis: emojis, + } + + return &stickerEmojisTemp +} + +// StickerSet Represents a sticker set +type StickerSet struct { + tdCommon + ID JSONInt64 `json:"id"` // Identifier of the sticker set + Title string `json:"title"` // Title of the sticker set + Name string `json:"name"` // Name of the sticker set + IsInstalled bool `json:"is_installed"` // True, if the sticker set has been installed by the current user + IsArchived bool `json:"is_archived"` // True, if the sticker set has been archived. A sticker set can't be installed and archived simultaneously + IsOfficial bool `json:"is_official"` // True, if the sticker set is official + IsMasks bool `json:"is_masks"` // True, if the stickers in the set are masks + IsViewed bool `json:"is_viewed"` // True for already viewed trending sticker sets + Stickers []Sticker `json:"stickers"` // List of stickers in this set + Emojis []StickerEmojis `json:"emojis"` // A list of emoji corresponding to the stickers in the same order +} + +// MessageType return the string telegram-type of StickerSet +func (stickerSet *StickerSet) MessageType() string { + return "stickerSet" +} + +// NewStickerSet creates a new StickerSet +// +// @param iD Identifier of the sticker set +// @param title Title of the sticker set +// @param name Name of the sticker set +// @param isInstalled True, if the sticker set has been installed by the current user +// @param isArchived True, if the sticker set has been archived. A sticker set can't be installed and archived simultaneously +// @param isOfficial True, if the sticker set is official +// @param isMasks True, if the stickers in the set are masks +// @param isViewed True for already viewed trending sticker sets +// @param stickers List of stickers in this set +// @param emojis A list of emoji corresponding to the stickers in the same order +func NewStickerSet(iD JSONInt64, title string, name string, isInstalled bool, isArchived bool, isOfficial bool, isMasks bool, isViewed bool, stickers []Sticker, emojis []StickerEmojis) *StickerSet { + stickerSetTemp := StickerSet{ + tdCommon: tdCommon{Type: "stickerSet"}, + ID: iD, + Title: title, + Name: name, + IsInstalled: isInstalled, + IsArchived: isArchived, + IsOfficial: isOfficial, + IsMasks: isMasks, + IsViewed: isViewed, + Stickers: stickers, + Emojis: emojis, + } + + return &stickerSetTemp +} + +// StickerSetInfo Represents short information about a sticker set +type StickerSetInfo struct { + tdCommon + ID JSONInt64 `json:"id"` // Identifier of the sticker set + Title string `json:"title"` // Title of the sticker set + Name string `json:"name"` // Name of the sticker set + IsInstalled bool `json:"is_installed"` // True, if the sticker set has been installed by current user + IsArchived bool `json:"is_archived"` // True, if the sticker set has been archived. A sticker set can't be installed and archived simultaneously + IsOfficial bool `json:"is_official"` // True, if the sticker set is official + IsMasks bool `json:"is_masks"` // True, if the stickers in the set are masks + IsViewed bool `json:"is_viewed"` // True for already viewed trending sticker sets + Size int32 `json:"size"` // Total number of stickers in the set + Covers []Sticker `json:"covers"` // Contains up to the first 5 stickers from the set, depending on the context. If the client needs more stickers the full set should be requested +} + +// MessageType return the string telegram-type of StickerSetInfo +func (stickerSetInfo *StickerSetInfo) MessageType() string { + return "stickerSetInfo" +} + +// NewStickerSetInfo creates a new StickerSetInfo +// +// @param iD Identifier of the sticker set +// @param title Title of the sticker set +// @param name Name of the sticker set +// @param isInstalled True, if the sticker set has been installed by current user +// @param isArchived True, if the sticker set has been archived. A sticker set can't be installed and archived simultaneously +// @param isOfficial True, if the sticker set is official +// @param isMasks True, if the stickers in the set are masks +// @param isViewed True for already viewed trending sticker sets +// @param size Total number of stickers in the set +// @param covers Contains up to the first 5 stickers from the set, depending on the context. If the client needs more stickers the full set should be requested +func NewStickerSetInfo(iD JSONInt64, title string, name string, isInstalled bool, isArchived bool, isOfficial bool, isMasks bool, isViewed bool, size int32, covers []Sticker) *StickerSetInfo { + stickerSetInfoTemp := StickerSetInfo{ + tdCommon: tdCommon{Type: "stickerSetInfo"}, + ID: iD, + Title: title, + Name: name, + IsInstalled: isInstalled, + IsArchived: isArchived, + IsOfficial: isOfficial, + IsMasks: isMasks, + IsViewed: isViewed, + Size: size, + Covers: covers, + } + + return &stickerSetInfoTemp +} + +// StickerSets Represents a list of sticker sets +type StickerSets struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total number of sticker sets found + Sets []StickerSetInfo `json:"sets"` // List of sticker sets +} + +// MessageType return the string telegram-type of StickerSets +func (stickerSets *StickerSets) MessageType() string { + return "stickerSets" +} + +// NewStickerSets creates a new StickerSets +// +// @param totalCount Approximate total number of sticker sets found +// @param sets List of sticker sets +func NewStickerSets(totalCount int32, sets []StickerSetInfo) *StickerSets { + stickerSetsTemp := StickerSets{ + tdCommon: tdCommon{Type: "stickerSets"}, + TotalCount: totalCount, + Sets: sets, + } + + return &stickerSetsTemp +} + +// CallDiscardReasonEmpty The call wasn't discarded, or the reason is unknown +type CallDiscardReasonEmpty struct { + tdCommon +} + +// MessageType return the string telegram-type of CallDiscardReasonEmpty +func (callDiscardReasonEmpty *CallDiscardReasonEmpty) MessageType() string { + return "callDiscardReasonEmpty" +} + +// NewCallDiscardReasonEmpty creates a new CallDiscardReasonEmpty +// +func NewCallDiscardReasonEmpty() *CallDiscardReasonEmpty { + callDiscardReasonEmptyTemp := CallDiscardReasonEmpty{ + tdCommon: tdCommon{Type: "callDiscardReasonEmpty"}, + } + + return &callDiscardReasonEmptyTemp +} + +// GetCallDiscardReasonEnum return the enum type of this object +func (callDiscardReasonEmpty *CallDiscardReasonEmpty) GetCallDiscardReasonEnum() CallDiscardReasonEnum { + return CallDiscardReasonEmptyType +} + +// CallDiscardReasonMissed The call was ended before the conversation started. It was cancelled by the caller or missed by the other party +type CallDiscardReasonMissed struct { + tdCommon +} + +// MessageType return the string telegram-type of CallDiscardReasonMissed +func (callDiscardReasonMissed *CallDiscardReasonMissed) MessageType() string { + return "callDiscardReasonMissed" +} + +// NewCallDiscardReasonMissed creates a new CallDiscardReasonMissed +// +func NewCallDiscardReasonMissed() *CallDiscardReasonMissed { + callDiscardReasonMissedTemp := CallDiscardReasonMissed{ + tdCommon: tdCommon{Type: "callDiscardReasonMissed"}, + } + + return &callDiscardReasonMissedTemp +} + +// GetCallDiscardReasonEnum return the enum type of this object +func (callDiscardReasonMissed *CallDiscardReasonMissed) GetCallDiscardReasonEnum() CallDiscardReasonEnum { + return CallDiscardReasonMissedType +} + +// CallDiscardReasonDeclined The call was ended before the conversation started. It was declined by the other party +type CallDiscardReasonDeclined struct { + tdCommon +} + +// MessageType return the string telegram-type of CallDiscardReasonDeclined +func (callDiscardReasonDeclined *CallDiscardReasonDeclined) MessageType() string { + return "callDiscardReasonDeclined" +} + +// NewCallDiscardReasonDeclined creates a new CallDiscardReasonDeclined +// +func NewCallDiscardReasonDeclined() *CallDiscardReasonDeclined { + callDiscardReasonDeclinedTemp := CallDiscardReasonDeclined{ + tdCommon: tdCommon{Type: "callDiscardReasonDeclined"}, + } + + return &callDiscardReasonDeclinedTemp +} + +// GetCallDiscardReasonEnum return the enum type of this object +func (callDiscardReasonDeclined *CallDiscardReasonDeclined) GetCallDiscardReasonEnum() CallDiscardReasonEnum { + return CallDiscardReasonDeclinedType +} + +// CallDiscardReasonDisconnected The call was ended during the conversation because the users were disconnected +type CallDiscardReasonDisconnected struct { + tdCommon +} + +// MessageType return the string telegram-type of CallDiscardReasonDisconnected +func (callDiscardReasonDisconnected *CallDiscardReasonDisconnected) MessageType() string { + return "callDiscardReasonDisconnected" +} + +// NewCallDiscardReasonDisconnected creates a new CallDiscardReasonDisconnected +// +func NewCallDiscardReasonDisconnected() *CallDiscardReasonDisconnected { + callDiscardReasonDisconnectedTemp := CallDiscardReasonDisconnected{ + tdCommon: tdCommon{Type: "callDiscardReasonDisconnected"}, + } + + return &callDiscardReasonDisconnectedTemp +} + +// GetCallDiscardReasonEnum return the enum type of this object +func (callDiscardReasonDisconnected *CallDiscardReasonDisconnected) GetCallDiscardReasonEnum() CallDiscardReasonEnum { + return CallDiscardReasonDisconnectedType +} + +// CallDiscardReasonHungUp The call was ended because one of the parties hung up +type CallDiscardReasonHungUp struct { + tdCommon +} + +// MessageType return the string telegram-type of CallDiscardReasonHungUp +func (callDiscardReasonHungUp *CallDiscardReasonHungUp) MessageType() string { + return "callDiscardReasonHungUp" +} + +// NewCallDiscardReasonHungUp creates a new CallDiscardReasonHungUp +// +func NewCallDiscardReasonHungUp() *CallDiscardReasonHungUp { + callDiscardReasonHungUpTemp := CallDiscardReasonHungUp{ + tdCommon: tdCommon{Type: "callDiscardReasonHungUp"}, + } + + return &callDiscardReasonHungUpTemp +} + +// GetCallDiscardReasonEnum return the enum type of this object +func (callDiscardReasonHungUp *CallDiscardReasonHungUp) GetCallDiscardReasonEnum() CallDiscardReasonEnum { + return CallDiscardReasonHungUpType +} + +// CallProtocol Specifies the supported call protocols +type CallProtocol struct { + tdCommon + UDPP2p bool `json:"udp_p2p"` // True, if UDP peer-to-peer connections are supported + UDPReflector bool `json:"udp_reflector"` // True, if connection through UDP reflectors is supported + MinLayer int32 `json:"min_layer"` // Minimum supported API layer; use 65 + MaxLayer int32 `json:"max_layer"` // Maximum supported API layer; use 65 +} + +// MessageType return the string telegram-type of CallProtocol +func (callProtocol *CallProtocol) MessageType() string { + return "callProtocol" +} + +// NewCallProtocol creates a new CallProtocol +// +// @param uDPP2p True, if UDP peer-to-peer connections are supported +// @param uDPReflector True, if connection through UDP reflectors is supported +// @param minLayer Minimum supported API layer; use 65 +// @param maxLayer Maximum supported API layer; use 65 +func NewCallProtocol(uDPP2p bool, uDPReflector bool, minLayer int32, maxLayer int32) *CallProtocol { + callProtocolTemp := CallProtocol{ + tdCommon: tdCommon{Type: "callProtocol"}, + UDPP2p: uDPP2p, + UDPReflector: uDPReflector, + MinLayer: minLayer, + MaxLayer: maxLayer, + } + + return &callProtocolTemp +} + +// CallConnection Describes the address of UDP reflectors +type CallConnection struct { + tdCommon + ID JSONInt64 `json:"id"` // Reflector identifier + IP string `json:"ip"` // IPv4 reflector address + IPv6 string `json:"ipv6"` // IPv6 reflector address + Port int32 `json:"port"` // Reflector port number + PeerTag []byte `json:"peer_tag"` // Connection peer tag +} + +// MessageType return the string telegram-type of CallConnection +func (callConnection *CallConnection) MessageType() string { + return "callConnection" +} + +// NewCallConnection creates a new CallConnection +// +// @param iD Reflector identifier +// @param iP IPv4 reflector address +// @param iPv6 IPv6 reflector address +// @param port Reflector port number +// @param peerTag Connection peer tag +func NewCallConnection(iD JSONInt64, iP string, iPv6 string, port int32, peerTag []byte) *CallConnection { + callConnectionTemp := CallConnection{ + tdCommon: tdCommon{Type: "callConnection"}, + ID: iD, + IP: iP, + IPv6: iPv6, + Port: port, + PeerTag: peerTag, + } + + return &callConnectionTemp +} + +// CallID Contains the call identifier +type CallID struct { + tdCommon + ID int32 `json:"id"` // Call identifier +} + +// MessageType return the string telegram-type of CallID +func (callID *CallID) MessageType() string { + return "callId" +} + +// NewCallID creates a new CallID +// +// @param iD Call identifier +func NewCallID(iD int32) *CallID { + callIDTemp := CallID{ + tdCommon: tdCommon{Type: "callId"}, + ID: iD, + } + + return &callIDTemp +} + +// CallStatePending The call is pending, waiting to be accepted by a user +type CallStatePending struct { + tdCommon + IsCreated bool `json:"is_created"` // True, if the call has already been created by the server + IsReceived bool `json:"is_received"` // True, if the call has already been received by the other party +} + +// MessageType return the string telegram-type of CallStatePending +func (callStatePending *CallStatePending) MessageType() string { + return "callStatePending" +} + +// NewCallStatePending creates a new CallStatePending +// +// @param isCreated True, if the call has already been created by the server +// @param isReceived True, if the call has already been received by the other party +func NewCallStatePending(isCreated bool, isReceived bool) *CallStatePending { + callStatePendingTemp := CallStatePending{ + tdCommon: tdCommon{Type: "callStatePending"}, + IsCreated: isCreated, + IsReceived: isReceived, + } + + return &callStatePendingTemp +} + +// GetCallStateEnum return the enum type of this object +func (callStatePending *CallStatePending) GetCallStateEnum() CallStateEnum { + return CallStatePendingType +} + +// CallStateExchangingKeys The call has been answered and encryption keys are being exchanged +type CallStateExchangingKeys struct { + tdCommon +} + +// MessageType return the string telegram-type of CallStateExchangingKeys +func (callStateExchangingKeys *CallStateExchangingKeys) MessageType() string { + return "callStateExchangingKeys" +} + +// NewCallStateExchangingKeys creates a new CallStateExchangingKeys +// +func NewCallStateExchangingKeys() *CallStateExchangingKeys { + callStateExchangingKeysTemp := CallStateExchangingKeys{ + tdCommon: tdCommon{Type: "callStateExchangingKeys"}, + } + + return &callStateExchangingKeysTemp +} + +// GetCallStateEnum return the enum type of this object +func (callStateExchangingKeys *CallStateExchangingKeys) GetCallStateEnum() CallStateEnum { + return CallStateExchangingKeysType +} + +// CallStateReady The call is ready to use +type CallStateReady struct { + tdCommon + Protocol *CallProtocol `json:"protocol"` // Call protocols supported by the peer + Connections []CallConnection `json:"connections"` // Available UDP reflectors + Config string `json:"config"` // A JSON-encoded call config + EncryptionKey []byte `json:"encryption_key"` // Call encryption key + Emojis []string `json:"emojis"` // Encryption key emojis fingerprint +} + +// MessageType return the string telegram-type of CallStateReady +func (callStateReady *CallStateReady) MessageType() string { + return "callStateReady" +} + +// NewCallStateReady creates a new CallStateReady +// +// @param protocol Call protocols supported by the peer +// @param connections Available UDP reflectors +// @param config A JSON-encoded call config +// @param encryptionKey Call encryption key +// @param emojis Encryption key emojis fingerprint +func NewCallStateReady(protocol *CallProtocol, connections []CallConnection, config string, encryptionKey []byte, emojis []string) *CallStateReady { + callStateReadyTemp := CallStateReady{ + tdCommon: tdCommon{Type: "callStateReady"}, + Protocol: protocol, + Connections: connections, + Config: config, + EncryptionKey: encryptionKey, + Emojis: emojis, + } + + return &callStateReadyTemp +} + +// GetCallStateEnum return the enum type of this object +func (callStateReady *CallStateReady) GetCallStateEnum() CallStateEnum { + return CallStateReadyType +} + +// CallStateHangingUp The call is hanging up after discardCall has been called +type CallStateHangingUp struct { + tdCommon +} + +// MessageType return the string telegram-type of CallStateHangingUp +func (callStateHangingUp *CallStateHangingUp) MessageType() string { + return "callStateHangingUp" +} + +// NewCallStateHangingUp creates a new CallStateHangingUp +// +func NewCallStateHangingUp() *CallStateHangingUp { + callStateHangingUpTemp := CallStateHangingUp{ + tdCommon: tdCommon{Type: "callStateHangingUp"}, + } + + return &callStateHangingUpTemp +} + +// GetCallStateEnum return the enum type of this object +func (callStateHangingUp *CallStateHangingUp) GetCallStateEnum() CallStateEnum { + return CallStateHangingUpType +} + +// CallStateDiscarded The call has ended successfully +type CallStateDiscarded struct { + tdCommon + Reason CallDiscardReason `json:"reason"` // The reason, why the call has ended + NeedRating bool `json:"need_rating"` // True, if the call rating should be sent to the server + NeedDebugInformation bool `json:"need_debug_information"` // True, if the call debug information should be sent to the server +} + +// MessageType return the string telegram-type of CallStateDiscarded +func (callStateDiscarded *CallStateDiscarded) MessageType() string { + return "callStateDiscarded" +} + +// NewCallStateDiscarded creates a new CallStateDiscarded +// +// @param reason The reason, why the call has ended +// @param needRating True, if the call rating should be sent to the server +// @param needDebugInformation True, if the call debug information should be sent to the server +func NewCallStateDiscarded(reason CallDiscardReason, needRating bool, needDebugInformation bool) *CallStateDiscarded { + callStateDiscardedTemp := CallStateDiscarded{ + tdCommon: tdCommon{Type: "callStateDiscarded"}, + Reason: reason, + NeedRating: needRating, + NeedDebugInformation: needDebugInformation, + } + + return &callStateDiscardedTemp +} + +// UnmarshalJSON unmarshal to json +func (callStateDiscarded *CallStateDiscarded) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + NeedRating bool `json:"need_rating"` // True, if the call rating should be sent to the server + NeedDebugInformation bool `json:"need_debug_information"` // True, if the call debug information should be sent to the server + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + callStateDiscarded.tdCommon = tempObj.tdCommon + callStateDiscarded.NeedRating = tempObj.NeedRating + callStateDiscarded.NeedDebugInformation = tempObj.NeedDebugInformation + + fieldReason, _ := unmarshalCallDiscardReason(objMap["reason"]) + callStateDiscarded.Reason = fieldReason + + return nil +} + +// GetCallStateEnum return the enum type of this object +func (callStateDiscarded *CallStateDiscarded) GetCallStateEnum() CallStateEnum { + return CallStateDiscardedType +} + +// CallStateError The call has ended with an error +type CallStateError struct { + tdCommon + Error *Error `json:"error"` // Error. An error with the code 4005000 will be returned if an outgoing call is missed because of an expired timeout +} + +// MessageType return the string telegram-type of CallStateError +func (callStateError *CallStateError) MessageType() string { + return "callStateError" +} + +// NewCallStateError creates a new CallStateError +// +// @param error Error. An error with the code 4005000 will be returned if an outgoing call is missed because of an expired timeout +func NewCallStateError(error *Error) *CallStateError { + callStateErrorTemp := CallStateError{ + tdCommon: tdCommon{Type: "callStateError"}, + Error: error, + } + + return &callStateErrorTemp +} + +// GetCallStateEnum return the enum type of this object +func (callStateError *CallStateError) GetCallStateEnum() CallStateEnum { + return CallStateErrorType +} + +// Call Describes a call +type Call struct { + tdCommon + ID int32 `json:"id"` // Call identifier, not persistent + UserID int32 `json:"user_id"` // Peer user identifier + IsOutgoing bool `json:"is_outgoing"` // True, if the call is outgoing + State CallState `json:"state"` // Call state +} + +// MessageType return the string telegram-type of Call +func (call *Call) MessageType() string { + return "call" +} + +// NewCall creates a new Call +// +// @param iD Call identifier, not persistent +// @param userID Peer user identifier +// @param isOutgoing True, if the call is outgoing +// @param state Call state +func NewCall(iD int32, userID int32, isOutgoing bool, state CallState) *Call { + callTemp := Call{ + tdCommon: tdCommon{Type: "call"}, + ID: iD, + UserID: userID, + IsOutgoing: isOutgoing, + State: state, + } + + return &callTemp +} + +// UnmarshalJSON unmarshal to json +func (call *Call) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int32 `json:"id"` // Call identifier, not persistent + UserID int32 `json:"user_id"` // Peer user identifier + IsOutgoing bool `json:"is_outgoing"` // True, if the call is outgoing + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + call.tdCommon = tempObj.tdCommon + call.ID = tempObj.ID + call.UserID = tempObj.UserID + call.IsOutgoing = tempObj.IsOutgoing + + fieldState, _ := unmarshalCallState(objMap["state"]) + call.State = fieldState + + return nil +} + +// Animations Represents a list of animations +type Animations struct { + tdCommon + Animations []Animation `json:"animations"` // List of animations +} + +// MessageType return the string telegram-type of Animations +func (animations *Animations) MessageType() string { + return "animations" +} + +// NewAnimations creates a new Animations +// +// @param animations List of animations +func NewAnimations(animations []Animation) *Animations { + animationsTemp := Animations{ + tdCommon: tdCommon{Type: "animations"}, + Animations: animations, + } + + return &animationsTemp +} + +// ImportedContacts Represents the result of an ImportContacts request +type ImportedContacts struct { + tdCommon + UserIDs []int32 `json:"user_ids"` // User identifiers of the imported contacts in the same order as they were specified in the request; 0 if the contact is not yet a registered user + ImporterCount []int32 `json:"importer_count"` // The number of users that imported the corresponding contact; 0 for already registered users or if unavailable +} + +// MessageType return the string telegram-type of ImportedContacts +func (importedContacts *ImportedContacts) MessageType() string { + return "importedContacts" +} + +// NewImportedContacts creates a new ImportedContacts +// +// @param userIDs User identifiers of the imported contacts in the same order as they were specified in the request; 0 if the contact is not yet a registered user +// @param importerCount The number of users that imported the corresponding contact; 0 for already registered users or if unavailable +func NewImportedContacts(userIDs []int32, importerCount []int32) *ImportedContacts { + importedContactsTemp := ImportedContacts{ + tdCommon: tdCommon{Type: "importedContacts"}, + UserIDs: userIDs, + ImporterCount: importerCount, + } + + return &importedContactsTemp +} + +// InputInlineQueryResultAnimatedGif Represents a link to an animated GIF +type InputInlineQueryResultAnimatedGif struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the query result + ThumbnailURL string `json:"thumbnail_url"` // URL of the static result thumbnail (JPEG or GIF), if it exists + GifURL string `json:"gif_url"` // The URL of the GIF-file (file size must not exceed 1MB) + GifDuration int32 `json:"gif_duration"` // Duration of the GIF, in seconds + GifWidth int32 `json:"gif_width"` // Width of the GIF + GifHeight int32 `json:"gif_height"` // Height of the GIF + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageAnimation, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultAnimatedGif +func (inputInlineQueryResultAnimatedGif *InputInlineQueryResultAnimatedGif) MessageType() string { + return "inputInlineQueryResultAnimatedGif" +} + +// NewInputInlineQueryResultAnimatedGif creates a new InputInlineQueryResultAnimatedGif +// +// @param iD Unique identifier of the query result +// @param title Title of the query result +// @param thumbnailURL URL of the static result thumbnail (JPEG or GIF), if it exists +// @param gifURL The URL of the GIF-file (file size must not exceed 1MB) +// @param gifDuration Duration of the GIF, in seconds +// @param gifWidth Width of the GIF +// @param gifHeight Height of the GIF +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageAnimation, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultAnimatedGif(iD string, title string, thumbnailURL string, gifURL string, gifDuration int32, gifWidth int32, gifHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultAnimatedGif { + inputInlineQueryResultAnimatedGifTemp := InputInlineQueryResultAnimatedGif{ + tdCommon: tdCommon{Type: "inputInlineQueryResultAnimatedGif"}, + ID: iD, + Title: title, + ThumbnailURL: thumbnailURL, + GifURL: gifURL, + GifDuration: gifDuration, + GifWidth: gifWidth, + GifHeight: gifHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultAnimatedGifTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultAnimatedGif *InputInlineQueryResultAnimatedGif) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the query result + ThumbnailURL string `json:"thumbnail_url"` // URL of the static result thumbnail (JPEG or GIF), if it exists + GifURL string `json:"gif_url"` // The URL of the GIF-file (file size must not exceed 1MB) + GifDuration int32 `json:"gif_duration"` // Duration of the GIF, in seconds + GifWidth int32 `json:"gif_width"` // Width of the GIF + GifHeight int32 `json:"gif_height"` // Height of the GIF + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultAnimatedGif.tdCommon = tempObj.tdCommon + inputInlineQueryResultAnimatedGif.ID = tempObj.ID + inputInlineQueryResultAnimatedGif.Title = tempObj.Title + inputInlineQueryResultAnimatedGif.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultAnimatedGif.GifURL = tempObj.GifURL + inputInlineQueryResultAnimatedGif.GifDuration = tempObj.GifDuration + inputInlineQueryResultAnimatedGif.GifWidth = tempObj.GifWidth + inputInlineQueryResultAnimatedGif.GifHeight = tempObj.GifHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultAnimatedGif.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultAnimatedGif.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultAnimatedGif *InputInlineQueryResultAnimatedGif) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultAnimatedGifType +} + +// InputInlineQueryResultAnimatedMpeg4 Represents a link to an animated (i.e. without sound) H.264/MPEG-4 AVC video +type InputInlineQueryResultAnimatedMpeg4 struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the result + ThumbnailURL string `json:"thumbnail_url"` // URL of the static result thumbnail (JPEG or GIF), if it exists + Mpeg4URL string `json:"mpeg4_url"` // The URL of the MPEG4-file (file size must not exceed 1MB) + Mpeg4Duration int32 `json:"mpeg4_duration"` // Duration of the video, in seconds + Mpeg4Width int32 `json:"mpeg4_width"` // Width of the video + Mpeg4Height int32 `json:"mpeg4_height"` // Height of the video + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageAnimation, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultAnimatedMpeg4 +func (inputInlineQueryResultAnimatedMpeg4 *InputInlineQueryResultAnimatedMpeg4) MessageType() string { + return "inputInlineQueryResultAnimatedMpeg4" +} + +// NewInputInlineQueryResultAnimatedMpeg4 creates a new InputInlineQueryResultAnimatedMpeg4 +// +// @param iD Unique identifier of the query result +// @param title Title of the result +// @param thumbnailURL URL of the static result thumbnail (JPEG or GIF), if it exists +// @param mpeg4URL The URL of the MPEG4-file (file size must not exceed 1MB) +// @param mpeg4Duration Duration of the video, in seconds +// @param mpeg4Width Width of the video +// @param mpeg4Height Height of the video +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageAnimation, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultAnimatedMpeg4(iD string, title string, thumbnailURL string, mpeg4URL string, mpeg4Duration int32, mpeg4Width int32, mpeg4Height int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultAnimatedMpeg4 { + inputInlineQueryResultAnimatedMpeg4Temp := InputInlineQueryResultAnimatedMpeg4{ + tdCommon: tdCommon{Type: "inputInlineQueryResultAnimatedMpeg4"}, + ID: iD, + Title: title, + ThumbnailURL: thumbnailURL, + Mpeg4URL: mpeg4URL, + Mpeg4Duration: mpeg4Duration, + Mpeg4Width: mpeg4Width, + Mpeg4Height: mpeg4Height, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultAnimatedMpeg4Temp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultAnimatedMpeg4 *InputInlineQueryResultAnimatedMpeg4) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the result + ThumbnailURL string `json:"thumbnail_url"` // URL of the static result thumbnail (JPEG or GIF), if it exists + Mpeg4URL string `json:"mpeg4_url"` // The URL of the MPEG4-file (file size must not exceed 1MB) + Mpeg4Duration int32 `json:"mpeg4_duration"` // Duration of the video, in seconds + Mpeg4Width int32 `json:"mpeg4_width"` // Width of the video + Mpeg4Height int32 `json:"mpeg4_height"` // Height of the video + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultAnimatedMpeg4.tdCommon = tempObj.tdCommon + inputInlineQueryResultAnimatedMpeg4.ID = tempObj.ID + inputInlineQueryResultAnimatedMpeg4.Title = tempObj.Title + inputInlineQueryResultAnimatedMpeg4.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultAnimatedMpeg4.Mpeg4URL = tempObj.Mpeg4URL + inputInlineQueryResultAnimatedMpeg4.Mpeg4Duration = tempObj.Mpeg4Duration + inputInlineQueryResultAnimatedMpeg4.Mpeg4Width = tempObj.Mpeg4Width + inputInlineQueryResultAnimatedMpeg4.Mpeg4Height = tempObj.Mpeg4Height + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultAnimatedMpeg4.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultAnimatedMpeg4.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultAnimatedMpeg4 *InputInlineQueryResultAnimatedMpeg4) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultAnimatedMpeg4Type +} + +// InputInlineQueryResultArticle Represents a link to an article or web page +type InputInlineQueryResultArticle struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + URL string `json:"url"` // URL of the result, if it exists + HideURL bool `json:"hide_url"` // True, if the URL must be not shown + Title string `json:"title"` // Title of the result + Description string `json:"description"` // + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultArticle +func (inputInlineQueryResultArticle *InputInlineQueryResultArticle) MessageType() string { + return "inputInlineQueryResultArticle" +} + +// NewInputInlineQueryResultArticle creates a new InputInlineQueryResultArticle +// +// @param iD Unique identifier of the query result +// @param uRL URL of the result, if it exists +// @param hideURL True, if the URL must be not shown +// @param title Title of the result +// @param description +// @param thumbnailURL URL of the result thumbnail, if it exists +// @param thumbnailWidth Thumbnail width, if known +// @param thumbnailHeight Thumbnail height, if known +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultArticle(iD string, uRL string, hideURL bool, title string, description string, thumbnailURL string, thumbnailWidth int32, thumbnailHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultArticle { + inputInlineQueryResultArticleTemp := InputInlineQueryResultArticle{ + tdCommon: tdCommon{Type: "inputInlineQueryResultArticle"}, + ID: iD, + URL: uRL, + HideURL: hideURL, + Title: title, + Description: description, + ThumbnailURL: thumbnailURL, + ThumbnailWidth: thumbnailWidth, + ThumbnailHeight: thumbnailHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultArticleTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultArticle *InputInlineQueryResultArticle) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + URL string `json:"url"` // URL of the result, if it exists + HideURL bool `json:"hide_url"` // True, if the URL must be not shown + Title string `json:"title"` // Title of the result + Description string `json:"description"` // + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultArticle.tdCommon = tempObj.tdCommon + inputInlineQueryResultArticle.ID = tempObj.ID + inputInlineQueryResultArticle.URL = tempObj.URL + inputInlineQueryResultArticle.HideURL = tempObj.HideURL + inputInlineQueryResultArticle.Title = tempObj.Title + inputInlineQueryResultArticle.Description = tempObj.Description + inputInlineQueryResultArticle.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultArticle.ThumbnailWidth = tempObj.ThumbnailWidth + inputInlineQueryResultArticle.ThumbnailHeight = tempObj.ThumbnailHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultArticle.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultArticle.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultArticle *InputInlineQueryResultArticle) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultArticleType +} + +// InputInlineQueryResultAudio Represents a link to an MP3 audio file +type InputInlineQueryResultAudio struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the audio file + Performer string `json:"performer"` // Performer of the audio file + AudioURL string `json:"audio_url"` // The URL of the audio file + AudioDuration int32 `json:"audio_duration"` // Audio file duration, in seconds + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageAudio, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultAudio +func (inputInlineQueryResultAudio *InputInlineQueryResultAudio) MessageType() string { + return "inputInlineQueryResultAudio" +} + +// NewInputInlineQueryResultAudio creates a new InputInlineQueryResultAudio +// +// @param iD Unique identifier of the query result +// @param title Title of the audio file +// @param performer Performer of the audio file +// @param audioURL The URL of the audio file +// @param audioDuration Audio file duration, in seconds +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageAudio, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultAudio(iD string, title string, performer string, audioURL string, audioDuration int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultAudio { + inputInlineQueryResultAudioTemp := InputInlineQueryResultAudio{ + tdCommon: tdCommon{Type: "inputInlineQueryResultAudio"}, + ID: iD, + Title: title, + Performer: performer, + AudioURL: audioURL, + AudioDuration: audioDuration, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultAudioTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultAudio *InputInlineQueryResultAudio) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the audio file + Performer string `json:"performer"` // Performer of the audio file + AudioURL string `json:"audio_url"` // The URL of the audio file + AudioDuration int32 `json:"audio_duration"` // Audio file duration, in seconds + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultAudio.tdCommon = tempObj.tdCommon + inputInlineQueryResultAudio.ID = tempObj.ID + inputInlineQueryResultAudio.Title = tempObj.Title + inputInlineQueryResultAudio.Performer = tempObj.Performer + inputInlineQueryResultAudio.AudioURL = tempObj.AudioURL + inputInlineQueryResultAudio.AudioDuration = tempObj.AudioDuration + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultAudio.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultAudio.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultAudio *InputInlineQueryResultAudio) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultAudioType +} + +// InputInlineQueryResultContact Represents a user contact +type InputInlineQueryResultContact struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Contact *Contact `json:"contact"` // User contact + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultContact +func (inputInlineQueryResultContact *InputInlineQueryResultContact) MessageType() string { + return "inputInlineQueryResultContact" +} + +// NewInputInlineQueryResultContact creates a new InputInlineQueryResultContact +// +// @param iD Unique identifier of the query result +// @param contact User contact +// @param thumbnailURL URL of the result thumbnail, if it exists +// @param thumbnailWidth Thumbnail width, if known +// @param thumbnailHeight Thumbnail height, if known +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultContact(iD string, contact *Contact, thumbnailURL string, thumbnailWidth int32, thumbnailHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultContact { + inputInlineQueryResultContactTemp := InputInlineQueryResultContact{ + tdCommon: tdCommon{Type: "inputInlineQueryResultContact"}, + ID: iD, + Contact: contact, + ThumbnailURL: thumbnailURL, + ThumbnailWidth: thumbnailWidth, + ThumbnailHeight: thumbnailHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultContactTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultContact *InputInlineQueryResultContact) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Contact *Contact `json:"contact"` // User contact + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultContact.tdCommon = tempObj.tdCommon + inputInlineQueryResultContact.ID = tempObj.ID + inputInlineQueryResultContact.Contact = tempObj.Contact + inputInlineQueryResultContact.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultContact.ThumbnailWidth = tempObj.ThumbnailWidth + inputInlineQueryResultContact.ThumbnailHeight = tempObj.ThumbnailHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultContact.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultContact.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultContact *InputInlineQueryResultContact) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultContactType +} + +// InputInlineQueryResultDocument Represents a link to a file +type InputInlineQueryResultDocument struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the resulting file + Description string `json:"description"` // + DocumentURL string `json:"document_url"` // URL of the file + MimeType string `json:"mime_type"` // MIME type of the file content; only "application/pdf" and "application/zip" are currently allowed + ThumbnailURL string `json:"thumbnail_url"` // The URL of the file thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Width of the thumbnail + ThumbnailHeight int32 `json:"thumbnail_height"` // Height of the thumbnail + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageDocument, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultDocument +func (inputInlineQueryResultDocument *InputInlineQueryResultDocument) MessageType() string { + return "inputInlineQueryResultDocument" +} + +// NewInputInlineQueryResultDocument creates a new InputInlineQueryResultDocument +// +// @param iD Unique identifier of the query result +// @param title Title of the resulting file +// @param description +// @param documentURL URL of the file +// @param mimeType MIME type of the file content; only "application/pdf" and "application/zip" are currently allowed +// @param thumbnailURL The URL of the file thumbnail, if it exists +// @param thumbnailWidth Width of the thumbnail +// @param thumbnailHeight Height of the thumbnail +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageDocument, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultDocument(iD string, title string, description string, documentURL string, mimeType string, thumbnailURL string, thumbnailWidth int32, thumbnailHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultDocument { + inputInlineQueryResultDocumentTemp := InputInlineQueryResultDocument{ + tdCommon: tdCommon{Type: "inputInlineQueryResultDocument"}, + ID: iD, + Title: title, + Description: description, + DocumentURL: documentURL, + MimeType: mimeType, + ThumbnailURL: thumbnailURL, + ThumbnailWidth: thumbnailWidth, + ThumbnailHeight: thumbnailHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultDocumentTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultDocument *InputInlineQueryResultDocument) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the resulting file + Description string `json:"description"` // + DocumentURL string `json:"document_url"` // URL of the file + MimeType string `json:"mime_type"` // MIME type of the file content; only "application/pdf" and "application/zip" are currently allowed + ThumbnailURL string `json:"thumbnail_url"` // The URL of the file thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Width of the thumbnail + ThumbnailHeight int32 `json:"thumbnail_height"` // Height of the thumbnail + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultDocument.tdCommon = tempObj.tdCommon + inputInlineQueryResultDocument.ID = tempObj.ID + inputInlineQueryResultDocument.Title = tempObj.Title + inputInlineQueryResultDocument.Description = tempObj.Description + inputInlineQueryResultDocument.DocumentURL = tempObj.DocumentURL + inputInlineQueryResultDocument.MimeType = tempObj.MimeType + inputInlineQueryResultDocument.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultDocument.ThumbnailWidth = tempObj.ThumbnailWidth + inputInlineQueryResultDocument.ThumbnailHeight = tempObj.ThumbnailHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultDocument.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultDocument.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultDocument *InputInlineQueryResultDocument) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultDocumentType +} + +// InputInlineQueryResultGame Represents a game +type InputInlineQueryResultGame struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + GameShortName string `json:"game_short_name"` // Short name of the game + ReplyMarkup ReplyMarkup `json:"reply_markup"` // Message reply markup. Must be of type replyMarkupInlineKeyboard or null +} + +// MessageType return the string telegram-type of InputInlineQueryResultGame +func (inputInlineQueryResultGame *InputInlineQueryResultGame) MessageType() string { + return "inputInlineQueryResultGame" +} + +// NewInputInlineQueryResultGame creates a new InputInlineQueryResultGame +// +// @param iD Unique identifier of the query result +// @param gameShortName Short name of the game +// @param replyMarkup Message reply markup. Must be of type replyMarkupInlineKeyboard or null +func NewInputInlineQueryResultGame(iD string, gameShortName string, replyMarkup ReplyMarkup) *InputInlineQueryResultGame { + inputInlineQueryResultGameTemp := InputInlineQueryResultGame{ + tdCommon: tdCommon{Type: "inputInlineQueryResultGame"}, + ID: iD, + GameShortName: gameShortName, + ReplyMarkup: replyMarkup, + } + + return &inputInlineQueryResultGameTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultGame *InputInlineQueryResultGame) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + GameShortName string `json:"game_short_name"` // Short name of the game + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultGame.tdCommon = tempObj.tdCommon + inputInlineQueryResultGame.ID = tempObj.ID + inputInlineQueryResultGame.GameShortName = tempObj.GameShortName + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultGame.ReplyMarkup = fieldReplyMarkup + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultGame *InputInlineQueryResultGame) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultGameType +} + +// InputInlineQueryResultLocation Represents a point on the map +type InputInlineQueryResultLocation struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Location *Location `json:"location"` // Location result + LivePeriod int32 `json:"live_period"` // Amount of time relative to the message sent time until the location can be updated, in seconds + Title string `json:"title"` // Title of the result + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultLocation +func (inputInlineQueryResultLocation *InputInlineQueryResultLocation) MessageType() string { + return "inputInlineQueryResultLocation" +} + +// NewInputInlineQueryResultLocation creates a new InputInlineQueryResultLocation +// +// @param iD Unique identifier of the query result +// @param location Location result +// @param livePeriod Amount of time relative to the message sent time until the location can be updated, in seconds +// @param title Title of the result +// @param thumbnailURL URL of the result thumbnail, if it exists +// @param thumbnailWidth Thumbnail width, if known +// @param thumbnailHeight Thumbnail height, if known +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultLocation(iD string, location *Location, livePeriod int32, title string, thumbnailURL string, thumbnailWidth int32, thumbnailHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultLocation { + inputInlineQueryResultLocationTemp := InputInlineQueryResultLocation{ + tdCommon: tdCommon{Type: "inputInlineQueryResultLocation"}, + ID: iD, + Location: location, + LivePeriod: livePeriod, + Title: title, + ThumbnailURL: thumbnailURL, + ThumbnailWidth: thumbnailWidth, + ThumbnailHeight: thumbnailHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultLocationTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultLocation *InputInlineQueryResultLocation) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Location *Location `json:"location"` // Location result + LivePeriod int32 `json:"live_period"` // Amount of time relative to the message sent time until the location can be updated, in seconds + Title string `json:"title"` // Title of the result + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultLocation.tdCommon = tempObj.tdCommon + inputInlineQueryResultLocation.ID = tempObj.ID + inputInlineQueryResultLocation.Location = tempObj.Location + inputInlineQueryResultLocation.LivePeriod = tempObj.LivePeriod + inputInlineQueryResultLocation.Title = tempObj.Title + inputInlineQueryResultLocation.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultLocation.ThumbnailWidth = tempObj.ThumbnailWidth + inputInlineQueryResultLocation.ThumbnailHeight = tempObj.ThumbnailHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultLocation.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultLocation.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultLocation *InputInlineQueryResultLocation) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultLocationType +} + +// InputInlineQueryResultPhoto Represents link to a JPEG image +type InputInlineQueryResultPhoto struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the result, if known + Description string `json:"description"` // + ThumbnailURL string `json:"thumbnail_url"` // URL of the photo thumbnail, if it exists + PhotoURL string `json:"photo_url"` // The URL of the JPEG photo (photo size must not exceed 5MB) + PhotoWidth int32 `json:"photo_width"` // Width of the photo + PhotoHeight int32 `json:"photo_height"` // Height of the photo + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessagePhoto, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultPhoto +func (inputInlineQueryResultPhoto *InputInlineQueryResultPhoto) MessageType() string { + return "inputInlineQueryResultPhoto" +} + +// NewInputInlineQueryResultPhoto creates a new InputInlineQueryResultPhoto +// +// @param iD Unique identifier of the query result +// @param title Title of the result, if known +// @param description +// @param thumbnailURL URL of the photo thumbnail, if it exists +// @param photoURL The URL of the JPEG photo (photo size must not exceed 5MB) +// @param photoWidth Width of the photo +// @param photoHeight Height of the photo +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessagePhoto, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultPhoto(iD string, title string, description string, thumbnailURL string, photoURL string, photoWidth int32, photoHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultPhoto { + inputInlineQueryResultPhotoTemp := InputInlineQueryResultPhoto{ + tdCommon: tdCommon{Type: "inputInlineQueryResultPhoto"}, + ID: iD, + Title: title, + Description: description, + ThumbnailURL: thumbnailURL, + PhotoURL: photoURL, + PhotoWidth: photoWidth, + PhotoHeight: photoHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultPhotoTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultPhoto *InputInlineQueryResultPhoto) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the result, if known + Description string `json:"description"` // + ThumbnailURL string `json:"thumbnail_url"` // URL of the photo thumbnail, if it exists + PhotoURL string `json:"photo_url"` // The URL of the JPEG photo (photo size must not exceed 5MB) + PhotoWidth int32 `json:"photo_width"` // Width of the photo + PhotoHeight int32 `json:"photo_height"` // Height of the photo + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultPhoto.tdCommon = tempObj.tdCommon + inputInlineQueryResultPhoto.ID = tempObj.ID + inputInlineQueryResultPhoto.Title = tempObj.Title + inputInlineQueryResultPhoto.Description = tempObj.Description + inputInlineQueryResultPhoto.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultPhoto.PhotoURL = tempObj.PhotoURL + inputInlineQueryResultPhoto.PhotoWidth = tempObj.PhotoWidth + inputInlineQueryResultPhoto.PhotoHeight = tempObj.PhotoHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultPhoto.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultPhoto.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultPhoto *InputInlineQueryResultPhoto) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultPhotoType +} + +// InputInlineQueryResultSticker Represents a link to a WEBP sticker +type InputInlineQueryResultSticker struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + ThumbnailURL string `json:"thumbnail_url"` // URL of the sticker thumbnail, if it exists + StickerURL string `json:"sticker_url"` // The URL of the WEBP sticker (sticker file size must not exceed 5MB) + StickerWidth int32 `json:"sticker_width"` // Width of the sticker + StickerHeight int32 `json:"sticker_height"` // Height of the sticker + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, inputMessageSticker, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultSticker +func (inputInlineQueryResultSticker *InputInlineQueryResultSticker) MessageType() string { + return "inputInlineQueryResultSticker" +} + +// NewInputInlineQueryResultSticker creates a new InputInlineQueryResultSticker +// +// @param iD Unique identifier of the query result +// @param thumbnailURL URL of the sticker thumbnail, if it exists +// @param stickerURL The URL of the WEBP sticker (sticker file size must not exceed 5MB) +// @param stickerWidth Width of the sticker +// @param stickerHeight Height of the sticker +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, inputMessageSticker, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultSticker(iD string, thumbnailURL string, stickerURL string, stickerWidth int32, stickerHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultSticker { + inputInlineQueryResultStickerTemp := InputInlineQueryResultSticker{ + tdCommon: tdCommon{Type: "inputInlineQueryResultSticker"}, + ID: iD, + ThumbnailURL: thumbnailURL, + StickerURL: stickerURL, + StickerWidth: stickerWidth, + StickerHeight: stickerHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultStickerTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultSticker *InputInlineQueryResultSticker) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + ThumbnailURL string `json:"thumbnail_url"` // URL of the sticker thumbnail, if it exists + StickerURL string `json:"sticker_url"` // The URL of the WEBP sticker (sticker file size must not exceed 5MB) + StickerWidth int32 `json:"sticker_width"` // Width of the sticker + StickerHeight int32 `json:"sticker_height"` // Height of the sticker + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultSticker.tdCommon = tempObj.tdCommon + inputInlineQueryResultSticker.ID = tempObj.ID + inputInlineQueryResultSticker.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultSticker.StickerURL = tempObj.StickerURL + inputInlineQueryResultSticker.StickerWidth = tempObj.StickerWidth + inputInlineQueryResultSticker.StickerHeight = tempObj.StickerHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultSticker.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultSticker.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultSticker *InputInlineQueryResultSticker) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultStickerType +} + +// InputInlineQueryResultVenue Represents information about a venue +type InputInlineQueryResultVenue struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Venue *Venue `json:"venue"` // Venue result + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultVenue +func (inputInlineQueryResultVenue *InputInlineQueryResultVenue) MessageType() string { + return "inputInlineQueryResultVenue" +} + +// NewInputInlineQueryResultVenue creates a new InputInlineQueryResultVenue +// +// @param iD Unique identifier of the query result +// @param venue Venue result +// @param thumbnailURL URL of the result thumbnail, if it exists +// @param thumbnailWidth Thumbnail width, if known +// @param thumbnailHeight Thumbnail height, if known +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultVenue(iD string, venue *Venue, thumbnailURL string, thumbnailWidth int32, thumbnailHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultVenue { + inputInlineQueryResultVenueTemp := InputInlineQueryResultVenue{ + tdCommon: tdCommon{Type: "inputInlineQueryResultVenue"}, + ID: iD, + Venue: venue, + ThumbnailURL: thumbnailURL, + ThumbnailWidth: thumbnailWidth, + ThumbnailHeight: thumbnailHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultVenueTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultVenue *InputInlineQueryResultVenue) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Venue *Venue `json:"venue"` // Venue result + ThumbnailURL string `json:"thumbnail_url"` // URL of the result thumbnail, if it exists + ThumbnailWidth int32 `json:"thumbnail_width"` // Thumbnail width, if known + ThumbnailHeight int32 `json:"thumbnail_height"` // Thumbnail height, if known + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultVenue.tdCommon = tempObj.tdCommon + inputInlineQueryResultVenue.ID = tempObj.ID + inputInlineQueryResultVenue.Venue = tempObj.Venue + inputInlineQueryResultVenue.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultVenue.ThumbnailWidth = tempObj.ThumbnailWidth + inputInlineQueryResultVenue.ThumbnailHeight = tempObj.ThumbnailHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultVenue.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultVenue.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultVenue *InputInlineQueryResultVenue) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultVenueType +} + +// InputInlineQueryResultVideo Represents a link to a page containing an embedded video player or a video file +type InputInlineQueryResultVideo struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the result + Description string `json:"description"` // + ThumbnailURL string `json:"thumbnail_url"` // The URL of the video thumbnail (JPEG), if it exists + VideoURL string `json:"video_url"` // URL of the embedded video player or video file + MimeType string `json:"mime_type"` // MIME type of the content of the video URL, only "text/html" or "video/mp4" are currently supported + VideoWidth int32 `json:"video_width"` // Width of the video + VideoHeight int32 `json:"video_height"` // Height of the video + VideoDuration int32 `json:"video_duration"` // Video duration, in seconds + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageVideo, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultVideo +func (inputInlineQueryResultVideo *InputInlineQueryResultVideo) MessageType() string { + return "inputInlineQueryResultVideo" +} + +// NewInputInlineQueryResultVideo creates a new InputInlineQueryResultVideo +// +// @param iD Unique identifier of the query result +// @param title Title of the result +// @param description +// @param thumbnailURL The URL of the video thumbnail (JPEG), if it exists +// @param videoURL URL of the embedded video player or video file +// @param mimeType MIME type of the content of the video URL, only "text/html" or "video/mp4" are currently supported +// @param videoWidth Width of the video +// @param videoHeight Height of the video +// @param videoDuration Video duration, in seconds +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageVideo, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultVideo(iD string, title string, description string, thumbnailURL string, videoURL string, mimeType string, videoWidth int32, videoHeight int32, videoDuration int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultVideo { + inputInlineQueryResultVideoTemp := InputInlineQueryResultVideo{ + tdCommon: tdCommon{Type: "inputInlineQueryResultVideo"}, + ID: iD, + Title: title, + Description: description, + ThumbnailURL: thumbnailURL, + VideoURL: videoURL, + MimeType: mimeType, + VideoWidth: videoWidth, + VideoHeight: videoHeight, + VideoDuration: videoDuration, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultVideoTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultVideo *InputInlineQueryResultVideo) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the result + Description string `json:"description"` // + ThumbnailURL string `json:"thumbnail_url"` // The URL of the video thumbnail (JPEG), if it exists + VideoURL string `json:"video_url"` // URL of the embedded video player or video file + MimeType string `json:"mime_type"` // MIME type of the content of the video URL, only "text/html" or "video/mp4" are currently supported + VideoWidth int32 `json:"video_width"` // Width of the video + VideoHeight int32 `json:"video_height"` // Height of the video + VideoDuration int32 `json:"video_duration"` // Video duration, in seconds + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultVideo.tdCommon = tempObj.tdCommon + inputInlineQueryResultVideo.ID = tempObj.ID + inputInlineQueryResultVideo.Title = tempObj.Title + inputInlineQueryResultVideo.Description = tempObj.Description + inputInlineQueryResultVideo.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultVideo.VideoURL = tempObj.VideoURL + inputInlineQueryResultVideo.MimeType = tempObj.MimeType + inputInlineQueryResultVideo.VideoWidth = tempObj.VideoWidth + inputInlineQueryResultVideo.VideoHeight = tempObj.VideoHeight + inputInlineQueryResultVideo.VideoDuration = tempObj.VideoDuration + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultVideo.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultVideo.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultVideo *InputInlineQueryResultVideo) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultVideoType +} + +// InputInlineQueryResultVoiceNote Represents a link to an opus-encoded audio file within an OGG container, single channel audio +type InputInlineQueryResultVoiceNote struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the voice note + VoiceNoteURL string `json:"voice_note_url"` // The URL of the voice note file + VoiceNoteDuration int32 `json:"voice_note_duration"` // Duration of the voice note, in seconds + ReplyMarkup ReplyMarkup `json:"reply_markup"` // The message reply markup. Must be of type replyMarkupInlineKeyboard or null + InputMessageContent InputMessageContent `json:"input_message_content"` // The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageVoiceNote, InputMessageLocation, InputMessageVenue or InputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultVoiceNote +func (inputInlineQueryResultVoiceNote *InputInlineQueryResultVoiceNote) MessageType() string { + return "inputInlineQueryResultVoiceNote" +} + +// NewInputInlineQueryResultVoiceNote creates a new InputInlineQueryResultVoiceNote +// +// @param iD Unique identifier of the query result +// @param title Title of the voice note +// @param voiceNoteURL The URL of the voice note file +// @param voiceNoteDuration Duration of the voice note, in seconds +// @param replyMarkup The message reply markup. Must be of type replyMarkupInlineKeyboard or null +// @param inputMessageContent The content of the message to be sent. Must be one of the following types: InputMessageText, InputMessageVoiceNote, InputMessageLocation, InputMessageVenue or InputMessageContact +func NewInputInlineQueryResultVoiceNote(iD string, title string, voiceNoteURL string, voiceNoteDuration int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultVoiceNote { + inputInlineQueryResultVoiceNoteTemp := InputInlineQueryResultVoiceNote{ + tdCommon: tdCommon{Type: "inputInlineQueryResultVoiceNote"}, + ID: iD, + Title: title, + VoiceNoteURL: voiceNoteURL, + VoiceNoteDuration: voiceNoteDuration, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultVoiceNoteTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultVoiceNote *InputInlineQueryResultVoiceNote) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Title string `json:"title"` // Title of the voice note + VoiceNoteURL string `json:"voice_note_url"` // The URL of the voice note file + VoiceNoteDuration int32 `json:"voice_note_duration"` // Duration of the voice note, in seconds + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultVoiceNote.tdCommon = tempObj.tdCommon + inputInlineQueryResultVoiceNote.ID = tempObj.ID + inputInlineQueryResultVoiceNote.Title = tempObj.Title + inputInlineQueryResultVoiceNote.VoiceNoteURL = tempObj.VoiceNoteURL + inputInlineQueryResultVoiceNote.VoiceNoteDuration = tempObj.VoiceNoteDuration + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultVoiceNote.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultVoiceNote.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultVoiceNote *InputInlineQueryResultVoiceNote) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultVoiceNoteType +} + +// InlineQueryResultArticle Represents a link to an article or web page +type InlineQueryResultArticle struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + URL string `json:"url"` // URL of the result, if it exists + HideURL bool `json:"hide_url"` // True, if the URL must be not shown + Title string `json:"title"` // Title of the result + Description string `json:"description"` // + Thumbnail *PhotoSize `json:"thumbnail"` // Result thumbnail; may be null +} + +// MessageType return the string telegram-type of InlineQueryResultArticle +func (inlineQueryResultArticle *InlineQueryResultArticle) MessageType() string { + return "inlineQueryResultArticle" +} + +// NewInlineQueryResultArticle creates a new InlineQueryResultArticle +// +// @param iD Unique identifier of the query result +// @param uRL URL of the result, if it exists +// @param hideURL True, if the URL must be not shown +// @param title Title of the result +// @param description +// @param thumbnail Result thumbnail; may be null +func NewInlineQueryResultArticle(iD string, uRL string, hideURL bool, title string, description string, thumbnail *PhotoSize) *InlineQueryResultArticle { + inlineQueryResultArticleTemp := InlineQueryResultArticle{ + tdCommon: tdCommon{Type: "inlineQueryResultArticle"}, + ID: iD, + URL: uRL, + HideURL: hideURL, + Title: title, + Description: description, + Thumbnail: thumbnail, + } + + return &inlineQueryResultArticleTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultArticle *InlineQueryResultArticle) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultArticleType +} + +// InlineQueryResultContact Represents a user contact +type InlineQueryResultContact struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Contact *Contact `json:"contact"` // A user contact + Thumbnail *PhotoSize `json:"thumbnail"` // Result thumbnail; may be null +} + +// MessageType return the string telegram-type of InlineQueryResultContact +func (inlineQueryResultContact *InlineQueryResultContact) MessageType() string { + return "inlineQueryResultContact" +} + +// NewInlineQueryResultContact creates a new InlineQueryResultContact +// +// @param iD Unique identifier of the query result +// @param contact A user contact +// @param thumbnail Result thumbnail; may be null +func NewInlineQueryResultContact(iD string, contact *Contact, thumbnail *PhotoSize) *InlineQueryResultContact { + inlineQueryResultContactTemp := InlineQueryResultContact{ + tdCommon: tdCommon{Type: "inlineQueryResultContact"}, + ID: iD, + Contact: contact, + Thumbnail: thumbnail, + } + + return &inlineQueryResultContactTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultContact *InlineQueryResultContact) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultContactType +} + +// InlineQueryResultLocation Represents a point on the map +type InlineQueryResultLocation struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Location *Location `json:"location"` // Location result + Title string `json:"title"` // Title of the result + Thumbnail *PhotoSize `json:"thumbnail"` // Result thumbnail; may be null +} + +// MessageType return the string telegram-type of InlineQueryResultLocation +func (inlineQueryResultLocation *InlineQueryResultLocation) MessageType() string { + return "inlineQueryResultLocation" +} + +// NewInlineQueryResultLocation creates a new InlineQueryResultLocation +// +// @param iD Unique identifier of the query result +// @param location Location result +// @param title Title of the result +// @param thumbnail Result thumbnail; may be null +func NewInlineQueryResultLocation(iD string, location *Location, title string, thumbnail *PhotoSize) *InlineQueryResultLocation { + inlineQueryResultLocationTemp := InlineQueryResultLocation{ + tdCommon: tdCommon{Type: "inlineQueryResultLocation"}, + ID: iD, + Location: location, + Title: title, + Thumbnail: thumbnail, + } + + return &inlineQueryResultLocationTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultLocation *InlineQueryResultLocation) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultLocationType +} + +// InlineQueryResultVenue Represents information about a venue +type InlineQueryResultVenue struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Venue *Venue `json:"venue"` // Venue result + Thumbnail *PhotoSize `json:"thumbnail"` // Result thumbnail; may be null +} + +// MessageType return the string telegram-type of InlineQueryResultVenue +func (inlineQueryResultVenue *InlineQueryResultVenue) MessageType() string { + return "inlineQueryResultVenue" +} + +// NewInlineQueryResultVenue creates a new InlineQueryResultVenue +// +// @param iD Unique identifier of the query result +// @param venue Venue result +// @param thumbnail Result thumbnail; may be null +func NewInlineQueryResultVenue(iD string, venue *Venue, thumbnail *PhotoSize) *InlineQueryResultVenue { + inlineQueryResultVenueTemp := InlineQueryResultVenue{ + tdCommon: tdCommon{Type: "inlineQueryResultVenue"}, + ID: iD, + Venue: venue, + Thumbnail: thumbnail, + } + + return &inlineQueryResultVenueTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultVenue *InlineQueryResultVenue) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultVenueType +} + +// InlineQueryResultGame Represents information about a game +type InlineQueryResultGame struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Game *Game `json:"game"` // Game result +} + +// MessageType return the string telegram-type of InlineQueryResultGame +func (inlineQueryResultGame *InlineQueryResultGame) MessageType() string { + return "inlineQueryResultGame" +} + +// NewInlineQueryResultGame creates a new InlineQueryResultGame +// +// @param iD Unique identifier of the query result +// @param game Game result +func NewInlineQueryResultGame(iD string, game *Game) *InlineQueryResultGame { + inlineQueryResultGameTemp := InlineQueryResultGame{ + tdCommon: tdCommon{Type: "inlineQueryResultGame"}, + ID: iD, + Game: game, + } + + return &inlineQueryResultGameTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultGame *InlineQueryResultGame) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultGameType +} + +// InlineQueryResultAnimation Represents an animation file +type InlineQueryResultAnimation struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Animation *Animation `json:"animation"` // Animation file + Title string `json:"title"` // Animation title +} + +// MessageType return the string telegram-type of InlineQueryResultAnimation +func (inlineQueryResultAnimation *InlineQueryResultAnimation) MessageType() string { + return "inlineQueryResultAnimation" +} + +// NewInlineQueryResultAnimation creates a new InlineQueryResultAnimation +// +// @param iD Unique identifier of the query result +// @param animation Animation file +// @param title Animation title +func NewInlineQueryResultAnimation(iD string, animation *Animation, title string) *InlineQueryResultAnimation { + inlineQueryResultAnimationTemp := InlineQueryResultAnimation{ + tdCommon: tdCommon{Type: "inlineQueryResultAnimation"}, + ID: iD, + Animation: animation, + Title: title, + } + + return &inlineQueryResultAnimationTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultAnimation *InlineQueryResultAnimation) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultAnimationType +} + +// InlineQueryResultAudio Represents an audio file +type InlineQueryResultAudio struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Audio *Audio `json:"audio"` // Audio file +} + +// MessageType return the string telegram-type of InlineQueryResultAudio +func (inlineQueryResultAudio *InlineQueryResultAudio) MessageType() string { + return "inlineQueryResultAudio" +} + +// NewInlineQueryResultAudio creates a new InlineQueryResultAudio +// +// @param iD Unique identifier of the query result +// @param audio Audio file +func NewInlineQueryResultAudio(iD string, audio *Audio) *InlineQueryResultAudio { + inlineQueryResultAudioTemp := InlineQueryResultAudio{ + tdCommon: tdCommon{Type: "inlineQueryResultAudio"}, + ID: iD, + Audio: audio, + } + + return &inlineQueryResultAudioTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultAudio *InlineQueryResultAudio) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultAudioType +} + +// InlineQueryResultDocument Represents a document +type InlineQueryResultDocument struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Document *Document `json:"document"` // Document + Title string `json:"title"` // Document title + Description string `json:"description"` // +} + +// MessageType return the string telegram-type of InlineQueryResultDocument +func (inlineQueryResultDocument *InlineQueryResultDocument) MessageType() string { + return "inlineQueryResultDocument" +} + +// NewInlineQueryResultDocument creates a new InlineQueryResultDocument +// +// @param iD Unique identifier of the query result +// @param document Document +// @param title Document title +// @param description +func NewInlineQueryResultDocument(iD string, document *Document, title string, description string) *InlineQueryResultDocument { + inlineQueryResultDocumentTemp := InlineQueryResultDocument{ + tdCommon: tdCommon{Type: "inlineQueryResultDocument"}, + ID: iD, + Document: document, + Title: title, + Description: description, + } + + return &inlineQueryResultDocumentTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultDocument *InlineQueryResultDocument) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultDocumentType +} + +// InlineQueryResultPhoto Represents a photo +type InlineQueryResultPhoto struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Photo *Photo `json:"photo"` // Photo + Title string `json:"title"` // Title of the result, if known + Description string `json:"description"` // +} + +// MessageType return the string telegram-type of InlineQueryResultPhoto +func (inlineQueryResultPhoto *InlineQueryResultPhoto) MessageType() string { + return "inlineQueryResultPhoto" +} + +// NewInlineQueryResultPhoto creates a new InlineQueryResultPhoto +// +// @param iD Unique identifier of the query result +// @param photo Photo +// @param title Title of the result, if known +// @param description +func NewInlineQueryResultPhoto(iD string, photo *Photo, title string, description string) *InlineQueryResultPhoto { + inlineQueryResultPhotoTemp := InlineQueryResultPhoto{ + tdCommon: tdCommon{Type: "inlineQueryResultPhoto"}, + ID: iD, + Photo: photo, + Title: title, + Description: description, + } + + return &inlineQueryResultPhotoTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultPhoto *InlineQueryResultPhoto) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultPhotoType +} + +// InlineQueryResultSticker Represents a sticker +type InlineQueryResultSticker struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Sticker *Sticker `json:"sticker"` // Sticker +} + +// MessageType return the string telegram-type of InlineQueryResultSticker +func (inlineQueryResultSticker *InlineQueryResultSticker) MessageType() string { + return "inlineQueryResultSticker" +} + +// NewInlineQueryResultSticker creates a new InlineQueryResultSticker +// +// @param iD Unique identifier of the query result +// @param sticker Sticker +func NewInlineQueryResultSticker(iD string, sticker *Sticker) *InlineQueryResultSticker { + inlineQueryResultStickerTemp := InlineQueryResultSticker{ + tdCommon: tdCommon{Type: "inlineQueryResultSticker"}, + ID: iD, + Sticker: sticker, + } + + return &inlineQueryResultStickerTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultSticker *InlineQueryResultSticker) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultStickerType +} + +// InlineQueryResultVideo Represents a video +type InlineQueryResultVideo struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + Video *Video `json:"video"` // Video + Title string `json:"title"` // Title of the video + Description string `json:"description"` // +} + +// MessageType return the string telegram-type of InlineQueryResultVideo +func (inlineQueryResultVideo *InlineQueryResultVideo) MessageType() string { + return "inlineQueryResultVideo" +} + +// NewInlineQueryResultVideo creates a new InlineQueryResultVideo +// +// @param iD Unique identifier of the query result +// @param video Video +// @param title Title of the video +// @param description +func NewInlineQueryResultVideo(iD string, video *Video, title string, description string) *InlineQueryResultVideo { + inlineQueryResultVideoTemp := InlineQueryResultVideo{ + tdCommon: tdCommon{Type: "inlineQueryResultVideo"}, + ID: iD, + Video: video, + Title: title, + Description: description, + } + + return &inlineQueryResultVideoTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultVideo *InlineQueryResultVideo) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultVideoType +} + +// InlineQueryResultVoiceNote Represents a voice note +type InlineQueryResultVoiceNote struct { + tdCommon + ID string `json:"id"` // Unique identifier of the query result + VoiceNote *VoiceNote `json:"voice_note"` // Voice note + Title string `json:"title"` // Title of the voice note +} + +// MessageType return the string telegram-type of InlineQueryResultVoiceNote +func (inlineQueryResultVoiceNote *InlineQueryResultVoiceNote) MessageType() string { + return "inlineQueryResultVoiceNote" +} + +// NewInlineQueryResultVoiceNote creates a new InlineQueryResultVoiceNote +// +// @param iD Unique identifier of the query result +// @param voiceNote Voice note +// @param title Title of the voice note +func NewInlineQueryResultVoiceNote(iD string, voiceNote *VoiceNote, title string) *InlineQueryResultVoiceNote { + inlineQueryResultVoiceNoteTemp := InlineQueryResultVoiceNote{ + tdCommon: tdCommon{Type: "inlineQueryResultVoiceNote"}, + ID: iD, + VoiceNote: voiceNote, + Title: title, + } + + return &inlineQueryResultVoiceNoteTemp +} + +// GetInlineQueryResultEnum return the enum type of this object +func (inlineQueryResultVoiceNote *InlineQueryResultVoiceNote) GetInlineQueryResultEnum() InlineQueryResultEnum { + return InlineQueryResultVoiceNoteType +} + +// InlineQueryResults Represents the results of the inline query. Use sendInlineQueryResultMessage to send the result of the query +type InlineQueryResults struct { + tdCommon + InlineQueryID JSONInt64 `json:"inline_query_id"` // Unique identifier of the inline query + NextOffset string `json:"next_offset"` // The offset for the next request. If empty, there are no more results + Results []InlineQueryResult `json:"results"` // Results of the query + SwitchPmText string `json:"switch_pm_text"` // If non-empty, this text should be shown on the button, which opens a private chat with the bot and sends the bot a start message with the switch_pm_parameter + SwitchPmParameter string `json:"switch_pm_parameter"` // Parameter for the bot start message +} + +// MessageType return the string telegram-type of InlineQueryResults +func (inlineQueryResults *InlineQueryResults) MessageType() string { + return "inlineQueryResults" +} + +// NewInlineQueryResults creates a new InlineQueryResults +// +// @param inlineQueryID Unique identifier of the inline query +// @param nextOffset The offset for the next request. If empty, there are no more results +// @param results Results of the query +// @param switchPmText If non-empty, this text should be shown on the button, which opens a private chat with the bot and sends the bot a start message with the switch_pm_parameter +// @param switchPmParameter Parameter for the bot start message +func NewInlineQueryResults(inlineQueryID JSONInt64, nextOffset string, results []InlineQueryResult, switchPmText string, switchPmParameter string) *InlineQueryResults { + inlineQueryResultsTemp := InlineQueryResults{ + tdCommon: tdCommon{Type: "inlineQueryResults"}, + InlineQueryID: inlineQueryID, + NextOffset: nextOffset, + Results: results, + SwitchPmText: switchPmText, + SwitchPmParameter: switchPmParameter, + } + + return &inlineQueryResultsTemp +} + +// CallbackQueryPayloadData The payload from a general callback button +type CallbackQueryPayloadData struct { + tdCommon + Data []byte `json:"data"` // Data that was attached to the callback button +} + +// MessageType return the string telegram-type of CallbackQueryPayloadData +func (callbackQueryPayloadData *CallbackQueryPayloadData) MessageType() string { + return "callbackQueryPayloadData" +} + +// NewCallbackQueryPayloadData creates a new CallbackQueryPayloadData +// +// @param data Data that was attached to the callback button +func NewCallbackQueryPayloadData(data []byte) *CallbackQueryPayloadData { + callbackQueryPayloadDataTemp := CallbackQueryPayloadData{ + tdCommon: tdCommon{Type: "callbackQueryPayloadData"}, + Data: data, + } + + return &callbackQueryPayloadDataTemp +} + +// GetCallbackQueryPayloadEnum return the enum type of this object +func (callbackQueryPayloadData *CallbackQueryPayloadData) GetCallbackQueryPayloadEnum() CallbackQueryPayloadEnum { + return CallbackQueryPayloadDataType +} + +// CallbackQueryPayloadGame The payload from a game callback button +type CallbackQueryPayloadGame struct { + tdCommon + GameShortName string `json:"game_short_name"` // A short name of the game that was attached to the callback button +} + +// MessageType return the string telegram-type of CallbackQueryPayloadGame +func (callbackQueryPayloadGame *CallbackQueryPayloadGame) MessageType() string { + return "callbackQueryPayloadGame" +} + +// NewCallbackQueryPayloadGame creates a new CallbackQueryPayloadGame +// +// @param gameShortName A short name of the game that was attached to the callback button +func NewCallbackQueryPayloadGame(gameShortName string) *CallbackQueryPayloadGame { + callbackQueryPayloadGameTemp := CallbackQueryPayloadGame{ + tdCommon: tdCommon{Type: "callbackQueryPayloadGame"}, + GameShortName: gameShortName, + } + + return &callbackQueryPayloadGameTemp +} + +// GetCallbackQueryPayloadEnum return the enum type of this object +func (callbackQueryPayloadGame *CallbackQueryPayloadGame) GetCallbackQueryPayloadEnum() CallbackQueryPayloadEnum { + return CallbackQueryPayloadGameType +} + +// CallbackQueryAnswer Contains a bot's answer to a callback query +type CallbackQueryAnswer struct { + tdCommon + Text string `json:"text"` // Text of the answer + ShowAlert bool `json:"show_alert"` // True, if an alert should be shown to the user instead of a toast notification + URL string `json:"url"` // URL to be opened +} + +// MessageType return the string telegram-type of CallbackQueryAnswer +func (callbackQueryAnswer *CallbackQueryAnswer) MessageType() string { + return "callbackQueryAnswer" +} + +// NewCallbackQueryAnswer creates a new CallbackQueryAnswer +// +// @param text Text of the answer +// @param showAlert True, if an alert should be shown to the user instead of a toast notification +// @param uRL URL to be opened +func NewCallbackQueryAnswer(text string, showAlert bool, uRL string) *CallbackQueryAnswer { + callbackQueryAnswerTemp := CallbackQueryAnswer{ + tdCommon: tdCommon{Type: "callbackQueryAnswer"}, + Text: text, + ShowAlert: showAlert, + URL: uRL, + } + + return &callbackQueryAnswerTemp +} + +// CustomRequestResult Contains the result of a custom request +type CustomRequestResult struct { + tdCommon + Result string `json:"result"` // A JSON-serialized result +} + +// MessageType return the string telegram-type of CustomRequestResult +func (customRequestResult *CustomRequestResult) MessageType() string { + return "customRequestResult" +} + +// NewCustomRequestResult creates a new CustomRequestResult +// +// @param result A JSON-serialized result +func NewCustomRequestResult(result string) *CustomRequestResult { + customRequestResultTemp := CustomRequestResult{ + tdCommon: tdCommon{Type: "customRequestResult"}, + Result: result, + } + + return &customRequestResultTemp +} + +// GameHighScore Contains one row of the game high score table +type GameHighScore struct { + tdCommon + Position int32 `json:"position"` // Position in the high score table + UserID int32 `json:"user_id"` // User identifier + Score int32 `json:"score"` // User score +} + +// MessageType return the string telegram-type of GameHighScore +func (gameHighScore *GameHighScore) MessageType() string { + return "gameHighScore" +} + +// NewGameHighScore creates a new GameHighScore +// +// @param position Position in the high score table +// @param userID User identifier +// @param score User score +func NewGameHighScore(position int32, userID int32, score int32) *GameHighScore { + gameHighScoreTemp := GameHighScore{ + tdCommon: tdCommon{Type: "gameHighScore"}, + Position: position, + UserID: userID, + Score: score, + } + + return &gameHighScoreTemp +} + +// GameHighScores Contains a list of game high scores +type GameHighScores struct { + tdCommon + Scores []GameHighScore `json:"scores"` // A list of game high scores +} + +// MessageType return the string telegram-type of GameHighScores +func (gameHighScores *GameHighScores) MessageType() string { + return "gameHighScores" +} + +// NewGameHighScores creates a new GameHighScores +// +// @param scores A list of game high scores +func NewGameHighScores(scores []GameHighScore) *GameHighScores { + gameHighScoresTemp := GameHighScores{ + tdCommon: tdCommon{Type: "gameHighScores"}, + Scores: scores, + } + + return &gameHighScoresTemp +} + +// ChatEventMessageEdited A message was edited +type ChatEventMessageEdited struct { + tdCommon + OldMessage *Message `json:"old_message"` // The original message before the edit + NewMessage *Message `json:"new_message"` // The message after it was edited +} + +// MessageType return the string telegram-type of ChatEventMessageEdited +func (chatEventMessageEdited *ChatEventMessageEdited) MessageType() string { + return "chatEventMessageEdited" +} + +// NewChatEventMessageEdited creates a new ChatEventMessageEdited +// +// @param oldMessage The original message before the edit +// @param newMessage The message after it was edited +func NewChatEventMessageEdited(oldMessage *Message, newMessage *Message) *ChatEventMessageEdited { + chatEventMessageEditedTemp := ChatEventMessageEdited{ + tdCommon: tdCommon{Type: "chatEventMessageEdited"}, + OldMessage: oldMessage, + NewMessage: newMessage, + } + + return &chatEventMessageEditedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMessageEdited *ChatEventMessageEdited) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMessageEditedType +} + +// ChatEventMessageDeleted A message was deleted +type ChatEventMessageDeleted struct { + tdCommon + Message *Message `json:"message"` // Deleted message +} + +// MessageType return the string telegram-type of ChatEventMessageDeleted +func (chatEventMessageDeleted *ChatEventMessageDeleted) MessageType() string { + return "chatEventMessageDeleted" +} + +// NewChatEventMessageDeleted creates a new ChatEventMessageDeleted +// +// @param message Deleted message +func NewChatEventMessageDeleted(message *Message) *ChatEventMessageDeleted { + chatEventMessageDeletedTemp := ChatEventMessageDeleted{ + tdCommon: tdCommon{Type: "chatEventMessageDeleted"}, + Message: message, + } + + return &chatEventMessageDeletedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMessageDeleted *ChatEventMessageDeleted) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMessageDeletedType +} + +// ChatEventMessagePinned A message was pinned +type ChatEventMessagePinned struct { + tdCommon + Message *Message `json:"message"` // Pinned message +} + +// MessageType return the string telegram-type of ChatEventMessagePinned +func (chatEventMessagePinned *ChatEventMessagePinned) MessageType() string { + return "chatEventMessagePinned" +} + +// NewChatEventMessagePinned creates a new ChatEventMessagePinned +// +// @param message Pinned message +func NewChatEventMessagePinned(message *Message) *ChatEventMessagePinned { + chatEventMessagePinnedTemp := ChatEventMessagePinned{ + tdCommon: tdCommon{Type: "chatEventMessagePinned"}, + Message: message, + } + + return &chatEventMessagePinnedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMessagePinned *ChatEventMessagePinned) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMessagePinnedType +} + +// ChatEventMessageUnpinned A message was unpinned +type ChatEventMessageUnpinned struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatEventMessageUnpinned +func (chatEventMessageUnpinned *ChatEventMessageUnpinned) MessageType() string { + return "chatEventMessageUnpinned" +} + +// NewChatEventMessageUnpinned creates a new ChatEventMessageUnpinned +// +func NewChatEventMessageUnpinned() *ChatEventMessageUnpinned { + chatEventMessageUnpinnedTemp := ChatEventMessageUnpinned{ + tdCommon: tdCommon{Type: "chatEventMessageUnpinned"}, + } + + return &chatEventMessageUnpinnedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMessageUnpinned *ChatEventMessageUnpinned) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMessageUnpinnedType +} + +// ChatEventMemberJoined A new member joined the chat +type ChatEventMemberJoined struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatEventMemberJoined +func (chatEventMemberJoined *ChatEventMemberJoined) MessageType() string { + return "chatEventMemberJoined" +} + +// NewChatEventMemberJoined creates a new ChatEventMemberJoined +// +func NewChatEventMemberJoined() *ChatEventMemberJoined { + chatEventMemberJoinedTemp := ChatEventMemberJoined{ + tdCommon: tdCommon{Type: "chatEventMemberJoined"}, + } + + return &chatEventMemberJoinedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMemberJoined *ChatEventMemberJoined) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMemberJoinedType +} + +// ChatEventMemberLeft A member left the chat +type ChatEventMemberLeft struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatEventMemberLeft +func (chatEventMemberLeft *ChatEventMemberLeft) MessageType() string { + return "chatEventMemberLeft" +} + +// NewChatEventMemberLeft creates a new ChatEventMemberLeft +// +func NewChatEventMemberLeft() *ChatEventMemberLeft { + chatEventMemberLeftTemp := ChatEventMemberLeft{ + tdCommon: tdCommon{Type: "chatEventMemberLeft"}, + } + + return &chatEventMemberLeftTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMemberLeft *ChatEventMemberLeft) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMemberLeftType +} + +// ChatEventMemberInvited A new chat member was invited +type ChatEventMemberInvited struct { + tdCommon + UserID int32 `json:"user_id"` // New member user identifier + Status ChatMemberStatus `json:"status"` // New member status +} + +// MessageType return the string telegram-type of ChatEventMemberInvited +func (chatEventMemberInvited *ChatEventMemberInvited) MessageType() string { + return "chatEventMemberInvited" +} + +// NewChatEventMemberInvited creates a new ChatEventMemberInvited +// +// @param userID New member user identifier +// @param status New member status +func NewChatEventMemberInvited(userID int32, status ChatMemberStatus) *ChatEventMemberInvited { + chatEventMemberInvitedTemp := ChatEventMemberInvited{ + tdCommon: tdCommon{Type: "chatEventMemberInvited"}, + UserID: userID, + Status: status, + } + + return &chatEventMemberInvitedTemp +} + +// UnmarshalJSON unmarshal to json +func (chatEventMemberInvited *ChatEventMemberInvited) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + UserID int32 `json:"user_id"` // New member user identifier + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatEventMemberInvited.tdCommon = tempObj.tdCommon + chatEventMemberInvited.UserID = tempObj.UserID + + fieldStatus, _ := unmarshalChatMemberStatus(objMap["status"]) + chatEventMemberInvited.Status = fieldStatus + + return nil +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMemberInvited *ChatEventMemberInvited) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMemberInvitedType +} + +// ChatEventMemberPromoted A chat member has gained/lost administrator status, or the list of their administrator privileges has changed +type ChatEventMemberPromoted struct { + tdCommon + UserID int32 `json:"user_id"` // Chat member user identifier + OldStatus ChatMemberStatus `json:"old_status"` // Previous status of the chat member + NewStatus ChatMemberStatus `json:"new_status"` // New status of the chat member +} + +// MessageType return the string telegram-type of ChatEventMemberPromoted +func (chatEventMemberPromoted *ChatEventMemberPromoted) MessageType() string { + return "chatEventMemberPromoted" +} + +// NewChatEventMemberPromoted creates a new ChatEventMemberPromoted +// +// @param userID Chat member user identifier +// @param oldStatus Previous status of the chat member +// @param newStatus New status of the chat member +func NewChatEventMemberPromoted(userID int32, oldStatus ChatMemberStatus, newStatus ChatMemberStatus) *ChatEventMemberPromoted { + chatEventMemberPromotedTemp := ChatEventMemberPromoted{ + tdCommon: tdCommon{Type: "chatEventMemberPromoted"}, + UserID: userID, + OldStatus: oldStatus, + NewStatus: newStatus, + } + + return &chatEventMemberPromotedTemp +} + +// UnmarshalJSON unmarshal to json +func (chatEventMemberPromoted *ChatEventMemberPromoted) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + UserID int32 `json:"user_id"` // Chat member user identifier + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatEventMemberPromoted.tdCommon = tempObj.tdCommon + chatEventMemberPromoted.UserID = tempObj.UserID + + fieldOldStatus, _ := unmarshalChatMemberStatus(objMap["old_status"]) + chatEventMemberPromoted.OldStatus = fieldOldStatus + + fieldNewStatus, _ := unmarshalChatMemberStatus(objMap["new_status"]) + chatEventMemberPromoted.NewStatus = fieldNewStatus + + return nil +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMemberPromoted *ChatEventMemberPromoted) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMemberPromotedType +} + +// ChatEventMemberRestricted A chat member was restricted/unrestricted or banned/unbanned, or the list of their restrictions has changed +type ChatEventMemberRestricted struct { + tdCommon + UserID int32 `json:"user_id"` // Chat member user identifier + OldStatus ChatMemberStatus `json:"old_status"` // Previous status of the chat member + NewStatus ChatMemberStatus `json:"new_status"` // New status of the chat member +} + +// MessageType return the string telegram-type of ChatEventMemberRestricted +func (chatEventMemberRestricted *ChatEventMemberRestricted) MessageType() string { + return "chatEventMemberRestricted" +} + +// NewChatEventMemberRestricted creates a new ChatEventMemberRestricted +// +// @param userID Chat member user identifier +// @param oldStatus Previous status of the chat member +// @param newStatus New status of the chat member +func NewChatEventMemberRestricted(userID int32, oldStatus ChatMemberStatus, newStatus ChatMemberStatus) *ChatEventMemberRestricted { + chatEventMemberRestrictedTemp := ChatEventMemberRestricted{ + tdCommon: tdCommon{Type: "chatEventMemberRestricted"}, + UserID: userID, + OldStatus: oldStatus, + NewStatus: newStatus, + } + + return &chatEventMemberRestrictedTemp +} + +// UnmarshalJSON unmarshal to json +func (chatEventMemberRestricted *ChatEventMemberRestricted) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + UserID int32 `json:"user_id"` // Chat member user identifier + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatEventMemberRestricted.tdCommon = tempObj.tdCommon + chatEventMemberRestricted.UserID = tempObj.UserID + + fieldOldStatus, _ := unmarshalChatMemberStatus(objMap["old_status"]) + chatEventMemberRestricted.OldStatus = fieldOldStatus + + fieldNewStatus, _ := unmarshalChatMemberStatus(objMap["new_status"]) + chatEventMemberRestricted.NewStatus = fieldNewStatus + + return nil +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMemberRestricted *ChatEventMemberRestricted) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMemberRestrictedType +} + +// ChatEventTitleChanged The chat title was changed +type ChatEventTitleChanged struct { + tdCommon + OldTitle string `json:"old_title"` // Previous chat title + NewTitle string `json:"new_title"` // New chat title +} + +// MessageType return the string telegram-type of ChatEventTitleChanged +func (chatEventTitleChanged *ChatEventTitleChanged) MessageType() string { + return "chatEventTitleChanged" +} + +// NewChatEventTitleChanged creates a new ChatEventTitleChanged +// +// @param oldTitle Previous chat title +// @param newTitle New chat title +func NewChatEventTitleChanged(oldTitle string, newTitle string) *ChatEventTitleChanged { + chatEventTitleChangedTemp := ChatEventTitleChanged{ + tdCommon: tdCommon{Type: "chatEventTitleChanged"}, + OldTitle: oldTitle, + NewTitle: newTitle, + } + + return &chatEventTitleChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventTitleChanged *ChatEventTitleChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventTitleChangedType +} + +// ChatEventDescriptionChanged The chat description was changed +type ChatEventDescriptionChanged struct { + tdCommon + OldDescription string `json:"old_description"` // Previous chat description + NewDescription string `json:"new_description"` // New chat description +} + +// MessageType return the string telegram-type of ChatEventDescriptionChanged +func (chatEventDescriptionChanged *ChatEventDescriptionChanged) MessageType() string { + return "chatEventDescriptionChanged" +} + +// NewChatEventDescriptionChanged creates a new ChatEventDescriptionChanged +// +// @param oldDescription Previous chat description +// @param newDescription New chat description +func NewChatEventDescriptionChanged(oldDescription string, newDescription string) *ChatEventDescriptionChanged { + chatEventDescriptionChangedTemp := ChatEventDescriptionChanged{ + tdCommon: tdCommon{Type: "chatEventDescriptionChanged"}, + OldDescription: oldDescription, + NewDescription: newDescription, + } + + return &chatEventDescriptionChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventDescriptionChanged *ChatEventDescriptionChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventDescriptionChangedType +} + +// ChatEventUsernameChanged The chat username was changed +type ChatEventUsernameChanged struct { + tdCommon + OldUsername string `json:"old_username"` // Previous chat username + NewUsername string `json:"new_username"` // New chat username +} + +// MessageType return the string telegram-type of ChatEventUsernameChanged +func (chatEventUsernameChanged *ChatEventUsernameChanged) MessageType() string { + return "chatEventUsernameChanged" +} + +// NewChatEventUsernameChanged creates a new ChatEventUsernameChanged +// +// @param oldUsername Previous chat username +// @param newUsername New chat username +func NewChatEventUsernameChanged(oldUsername string, newUsername string) *ChatEventUsernameChanged { + chatEventUsernameChangedTemp := ChatEventUsernameChanged{ + tdCommon: tdCommon{Type: "chatEventUsernameChanged"}, + OldUsername: oldUsername, + NewUsername: newUsername, + } + + return &chatEventUsernameChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventUsernameChanged *ChatEventUsernameChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventUsernameChangedType +} + +// ChatEventPhotoChanged The chat photo was changed +type ChatEventPhotoChanged struct { + tdCommon + OldPhoto *ChatPhoto `json:"old_photo"` // Previous chat photo value; may be null + NewPhoto *ChatPhoto `json:"new_photo"` // New chat photo value; may be null +} + +// MessageType return the string telegram-type of ChatEventPhotoChanged +func (chatEventPhotoChanged *ChatEventPhotoChanged) MessageType() string { + return "chatEventPhotoChanged" +} + +// NewChatEventPhotoChanged creates a new ChatEventPhotoChanged +// +// @param oldPhoto Previous chat photo value; may be null +// @param newPhoto New chat photo value; may be null +func NewChatEventPhotoChanged(oldPhoto *ChatPhoto, newPhoto *ChatPhoto) *ChatEventPhotoChanged { + chatEventPhotoChangedTemp := ChatEventPhotoChanged{ + tdCommon: tdCommon{Type: "chatEventPhotoChanged"}, + OldPhoto: oldPhoto, + NewPhoto: newPhoto, + } + + return &chatEventPhotoChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventPhotoChanged *ChatEventPhotoChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventPhotoChangedType +} + +// ChatEventInvitesToggled The anyone_can_invite setting of a supergroup chat was toggled +type ChatEventInvitesToggled struct { + tdCommon + AnyoneCanInvite bool `json:"anyone_can_invite"` // New value of anyone_can_invite +} + +// MessageType return the string telegram-type of ChatEventInvitesToggled +func (chatEventInvitesToggled *ChatEventInvitesToggled) MessageType() string { + return "chatEventInvitesToggled" +} + +// NewChatEventInvitesToggled creates a new ChatEventInvitesToggled +// +// @param anyoneCanInvite New value of anyone_can_invite +func NewChatEventInvitesToggled(anyoneCanInvite bool) *ChatEventInvitesToggled { + chatEventInvitesToggledTemp := ChatEventInvitesToggled{ + tdCommon: tdCommon{Type: "chatEventInvitesToggled"}, + AnyoneCanInvite: anyoneCanInvite, + } + + return &chatEventInvitesToggledTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventInvitesToggled *ChatEventInvitesToggled) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventInvitesToggledType +} + +// ChatEventSignMessagesToggled The sign_messages setting of a channel was toggled +type ChatEventSignMessagesToggled struct { + tdCommon + SignMessages bool `json:"sign_messages"` // New value of sign_messages +} + +// MessageType return the string telegram-type of ChatEventSignMessagesToggled +func (chatEventSignMessagesToggled *ChatEventSignMessagesToggled) MessageType() string { + return "chatEventSignMessagesToggled" +} + +// NewChatEventSignMessagesToggled creates a new ChatEventSignMessagesToggled +// +// @param signMessages New value of sign_messages +func NewChatEventSignMessagesToggled(signMessages bool) *ChatEventSignMessagesToggled { + chatEventSignMessagesToggledTemp := ChatEventSignMessagesToggled{ + tdCommon: tdCommon{Type: "chatEventSignMessagesToggled"}, + SignMessages: signMessages, + } + + return &chatEventSignMessagesToggledTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventSignMessagesToggled *ChatEventSignMessagesToggled) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventSignMessagesToggledType +} + +// ChatEventStickerSetChanged The supergroup sticker set was changed +type ChatEventStickerSetChanged struct { + tdCommon + OldStickerSetID JSONInt64 `json:"old_sticker_set_id"` // Previous identifier of the chat sticker set; 0 if none + NewStickerSetID JSONInt64 `json:"new_sticker_set_id"` // New identifier of the chat sticker set; 0 if none +} + +// MessageType return the string telegram-type of ChatEventStickerSetChanged +func (chatEventStickerSetChanged *ChatEventStickerSetChanged) MessageType() string { + return "chatEventStickerSetChanged" +} + +// NewChatEventStickerSetChanged creates a new ChatEventStickerSetChanged +// +// @param oldStickerSetID Previous identifier of the chat sticker set; 0 if none +// @param newStickerSetID New identifier of the chat sticker set; 0 if none +func NewChatEventStickerSetChanged(oldStickerSetID JSONInt64, newStickerSetID JSONInt64) *ChatEventStickerSetChanged { + chatEventStickerSetChangedTemp := ChatEventStickerSetChanged{ + tdCommon: tdCommon{Type: "chatEventStickerSetChanged"}, + OldStickerSetID: oldStickerSetID, + NewStickerSetID: newStickerSetID, + } + + return &chatEventStickerSetChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventStickerSetChanged *ChatEventStickerSetChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventStickerSetChangedType +} + +// ChatEventIsAllHistoryAvailableToggled The is_all_history_available setting of a supergroup was toggled +type ChatEventIsAllHistoryAvailableToggled struct { + tdCommon + IsAllHistoryAvailable bool `json:"is_all_history_available"` // New value of is_all_history_available +} + +// MessageType return the string telegram-type of ChatEventIsAllHistoryAvailableToggled +func (chatEventIsAllHistoryAvailableToggled *ChatEventIsAllHistoryAvailableToggled) MessageType() string { + return "chatEventIsAllHistoryAvailableToggled" +} + +// NewChatEventIsAllHistoryAvailableToggled creates a new ChatEventIsAllHistoryAvailableToggled +// +// @param isAllHistoryAvailable New value of is_all_history_available +func NewChatEventIsAllHistoryAvailableToggled(isAllHistoryAvailable bool) *ChatEventIsAllHistoryAvailableToggled { + chatEventIsAllHistoryAvailableToggledTemp := ChatEventIsAllHistoryAvailableToggled{ + tdCommon: tdCommon{Type: "chatEventIsAllHistoryAvailableToggled"}, + IsAllHistoryAvailable: isAllHistoryAvailable, + } + + return &chatEventIsAllHistoryAvailableToggledTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventIsAllHistoryAvailableToggled *ChatEventIsAllHistoryAvailableToggled) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventIsAllHistoryAvailableToggledType +} + +// ChatEvent Represents a chat event +type ChatEvent struct { + tdCommon + ID JSONInt64 `json:"id"` // Chat event identifier + Date int32 `json:"date"` // Point in time (Unix timestamp) when the event happened + UserID int32 `json:"user_id"` // Identifier of the user who performed the action that triggered the event + Action ChatEventAction `json:"action"` // Action performed by the user +} + +// MessageType return the string telegram-type of ChatEvent +func (chatEvent *ChatEvent) MessageType() string { + return "chatEvent" +} + +// NewChatEvent creates a new ChatEvent +// +// @param iD Chat event identifier +// @param date Point in time (Unix timestamp) when the event happened +// @param userID Identifier of the user who performed the action that triggered the event +// @param action Action performed by the user +func NewChatEvent(iD JSONInt64, date int32, userID int32, action ChatEventAction) *ChatEvent { + chatEventTemp := ChatEvent{ + tdCommon: tdCommon{Type: "chatEvent"}, + ID: iD, + Date: date, + UserID: userID, + Action: action, + } + + return &chatEventTemp +} + +// UnmarshalJSON unmarshal to json +func (chatEvent *ChatEvent) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID JSONInt64 `json:"id"` // Chat event identifier + Date int32 `json:"date"` // Point in time (Unix timestamp) when the event happened + UserID int32 `json:"user_id"` // Identifier of the user who performed the action that triggered the event + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatEvent.tdCommon = tempObj.tdCommon + chatEvent.ID = tempObj.ID + chatEvent.Date = tempObj.Date + chatEvent.UserID = tempObj.UserID + + fieldAction, _ := unmarshalChatEventAction(objMap["action"]) + chatEvent.Action = fieldAction + + return nil +} + +// ChatEvents Contains a list of chat events +type ChatEvents struct { + tdCommon + Events []ChatEvent `json:"events"` // List of events +} + +// MessageType return the string telegram-type of ChatEvents +func (chatEvents *ChatEvents) MessageType() string { + return "chatEvents" +} + +// NewChatEvents creates a new ChatEvents +// +// @param events List of events +func NewChatEvents(events []ChatEvent) *ChatEvents { + chatEventsTemp := ChatEvents{ + tdCommon: tdCommon{Type: "chatEvents"}, + Events: events, + } + + return &chatEventsTemp +} + +// ChatEventLogFilters Represents a set of filters used to obtain a chat event log +type ChatEventLogFilters struct { + tdCommon + MessageEdits bool `json:"message_edits"` // True, if message edits should be returned + MessageDeletions bool `json:"message_deletions"` // True, if message deletions should be returned + MessagePins bool `json:"message_pins"` // True, if pin/unpin events should be returned + MemberJoins bool `json:"member_joins"` // True, if members joining events should be returned + MemberLeaves bool `json:"member_leaves"` // True, if members leaving events should be returned + MemberInvites bool `json:"member_invites"` // True, if invited member events should be returned + MemberPromotions bool `json:"member_promotions"` // True, if member promotion/demotion events should be returned + MemberRestrictions bool `json:"member_restrictions"` // True, if member restricted/unrestricted/banned/unbanned events should be returned + InfoChanges bool `json:"info_changes"` // True, if changes in chat information should be returned + SettingChanges bool `json:"setting_changes"` // True, if changes in chat settings should be returned +} + +// MessageType return the string telegram-type of ChatEventLogFilters +func (chatEventLogFilters *ChatEventLogFilters) MessageType() string { + return "chatEventLogFilters" +} + +// NewChatEventLogFilters creates a new ChatEventLogFilters +// +// @param messageEdits True, if message edits should be returned +// @param messageDeletions True, if message deletions should be returned +// @param messagePins True, if pin/unpin events should be returned +// @param memberJoins True, if members joining events should be returned +// @param memberLeaves True, if members leaving events should be returned +// @param memberInvites True, if invited member events should be returned +// @param memberPromotions True, if member promotion/demotion events should be returned +// @param memberRestrictions True, if member restricted/unrestricted/banned/unbanned events should be returned +// @param infoChanges True, if changes in chat information should be returned +// @param settingChanges True, if changes in chat settings should be returned +func NewChatEventLogFilters(messageEdits bool, messageDeletions bool, messagePins bool, memberJoins bool, memberLeaves bool, memberInvites bool, memberPromotions bool, memberRestrictions bool, infoChanges bool, settingChanges bool) *ChatEventLogFilters { + chatEventLogFiltersTemp := ChatEventLogFilters{ + tdCommon: tdCommon{Type: "chatEventLogFilters"}, + MessageEdits: messageEdits, + MessageDeletions: messageDeletions, + MessagePins: messagePins, + MemberJoins: memberJoins, + MemberLeaves: memberLeaves, + MemberInvites: memberInvites, + MemberPromotions: memberPromotions, + MemberRestrictions: memberRestrictions, + InfoChanges: infoChanges, + SettingChanges: settingChanges, + } + + return &chatEventLogFiltersTemp +} + +// LanguagePackStringValueOrdinary An ordinary language pack string +type LanguagePackStringValueOrdinary struct { + tdCommon + Value string `json:"value"` // String value +} + +// MessageType return the string telegram-type of LanguagePackStringValueOrdinary +func (languagePackStringValueOrdinary *LanguagePackStringValueOrdinary) MessageType() string { + return "languagePackStringValueOrdinary" +} + +// NewLanguagePackStringValueOrdinary creates a new LanguagePackStringValueOrdinary +// +// @param value String value +func NewLanguagePackStringValueOrdinary(value string) *LanguagePackStringValueOrdinary { + languagePackStringValueOrdinaryTemp := LanguagePackStringValueOrdinary{ + tdCommon: tdCommon{Type: "languagePackStringValueOrdinary"}, + Value: value, + } + + return &languagePackStringValueOrdinaryTemp +} + +// GetLanguagePackStringValueEnum return the enum type of this object +func (languagePackStringValueOrdinary *LanguagePackStringValueOrdinary) GetLanguagePackStringValueEnum() LanguagePackStringValueEnum { + return LanguagePackStringValueOrdinaryType +} + +// LanguagePackStringValuePluralized A language pack string which has different forms based on the number of some object it mentions +type LanguagePackStringValuePluralized struct { + tdCommon + ZeroValue string `json:"zero_value"` // Value for zero objects + OneValue string `json:"one_value"` // Value for one object + TwoValue string `json:"two_value"` // Value for two objects + FewValue string `json:"few_value"` // Value for few objects + ManyValue string `json:"many_value"` // Value for many objects + OtherValue string `json:"other_value"` // Default value +} + +// MessageType return the string telegram-type of LanguagePackStringValuePluralized +func (languagePackStringValuePluralized *LanguagePackStringValuePluralized) MessageType() string { + return "languagePackStringValuePluralized" +} + +// NewLanguagePackStringValuePluralized creates a new LanguagePackStringValuePluralized +// +// @param zeroValue Value for zero objects +// @param oneValue Value for one object +// @param twoValue Value for two objects +// @param fewValue Value for few objects +// @param manyValue Value for many objects +// @param otherValue Default value +func NewLanguagePackStringValuePluralized(zeroValue string, oneValue string, twoValue string, fewValue string, manyValue string, otherValue string) *LanguagePackStringValuePluralized { + languagePackStringValuePluralizedTemp := LanguagePackStringValuePluralized{ + tdCommon: tdCommon{Type: "languagePackStringValuePluralized"}, + ZeroValue: zeroValue, + OneValue: oneValue, + TwoValue: twoValue, + FewValue: fewValue, + ManyValue: manyValue, + OtherValue: otherValue, + } + + return &languagePackStringValuePluralizedTemp +} + +// GetLanguagePackStringValueEnum return the enum type of this object +func (languagePackStringValuePluralized *LanguagePackStringValuePluralized) GetLanguagePackStringValueEnum() LanguagePackStringValueEnum { + return LanguagePackStringValuePluralizedType +} + +// LanguagePackStringValueDeleted A deleted language pack string, the value should be taken from the built-in english language pack +type LanguagePackStringValueDeleted struct { + tdCommon +} + +// MessageType return the string telegram-type of LanguagePackStringValueDeleted +func (languagePackStringValueDeleted *LanguagePackStringValueDeleted) MessageType() string { + return "languagePackStringValueDeleted" +} + +// NewLanguagePackStringValueDeleted creates a new LanguagePackStringValueDeleted +// +func NewLanguagePackStringValueDeleted() *LanguagePackStringValueDeleted { + languagePackStringValueDeletedTemp := LanguagePackStringValueDeleted{ + tdCommon: tdCommon{Type: "languagePackStringValueDeleted"}, + } + + return &languagePackStringValueDeletedTemp +} + +// GetLanguagePackStringValueEnum return the enum type of this object +func (languagePackStringValueDeleted *LanguagePackStringValueDeleted) GetLanguagePackStringValueEnum() LanguagePackStringValueEnum { + return LanguagePackStringValueDeletedType +} + +// LanguagePackString Represents one language pack string +type LanguagePackString struct { + tdCommon + Key string `json:"key"` // String key + Value LanguagePackStringValue `json:"value"` // String value +} + +// MessageType return the string telegram-type of LanguagePackString +func (languagePackString *LanguagePackString) MessageType() string { + return "languagePackString" +} + +// NewLanguagePackString creates a new LanguagePackString +// +// @param key String key +// @param value String value +func NewLanguagePackString(key string, value LanguagePackStringValue) *LanguagePackString { + languagePackStringTemp := LanguagePackString{ + tdCommon: tdCommon{Type: "languagePackString"}, + Key: key, + Value: value, + } + + return &languagePackStringTemp +} + +// UnmarshalJSON unmarshal to json +func (languagePackString *LanguagePackString) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Key string `json:"key"` // String key + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + languagePackString.tdCommon = tempObj.tdCommon + languagePackString.Key = tempObj.Key + + fieldValue, _ := unmarshalLanguagePackStringValue(objMap["value"]) + languagePackString.Value = fieldValue + + return nil +} + +// LanguagePackStrings Contains a list of language pack strings +type LanguagePackStrings struct { + tdCommon + Strings []LanguagePackString `json:"strings"` // A list of language pack strings +} + +// MessageType return the string telegram-type of LanguagePackStrings +func (languagePackStrings *LanguagePackStrings) MessageType() string { + return "languagePackStrings" +} + +// NewLanguagePackStrings creates a new LanguagePackStrings +// +// @param strings A list of language pack strings +func NewLanguagePackStrings(strings []LanguagePackString) *LanguagePackStrings { + languagePackStringsTemp := LanguagePackStrings{ + tdCommon: tdCommon{Type: "languagePackStrings"}, + Strings: strings, + } + + return &languagePackStringsTemp +} + +// LanguagePackInfo Contains information about a language pack +type LanguagePackInfo struct { + tdCommon + ID string `json:"id"` // Unique language pack identifier + Name string `json:"name"` // Language name + NativeName string `json:"native_name"` // Name of the language in that language + LocalStringCount int32 `json:"local_string_count"` // Total number of non-deleted strings from the language pack available locally +} + +// MessageType return the string telegram-type of LanguagePackInfo +func (languagePackInfo *LanguagePackInfo) MessageType() string { + return "languagePackInfo" +} + +// NewLanguagePackInfo creates a new LanguagePackInfo +// +// @param iD Unique language pack identifier +// @param name Language name +// @param nativeName Name of the language in that language +// @param localStringCount Total number of non-deleted strings from the language pack available locally +func NewLanguagePackInfo(iD string, name string, nativeName string, localStringCount int32) *LanguagePackInfo { + languagePackInfoTemp := LanguagePackInfo{ + tdCommon: tdCommon{Type: "languagePackInfo"}, + ID: iD, + Name: name, + NativeName: nativeName, + LocalStringCount: localStringCount, + } + + return &languagePackInfoTemp +} + +// LocalizationTargetInfo Contains information about the current localization target +type LocalizationTargetInfo struct { + tdCommon + LanguagePacks []LanguagePackInfo `json:"language_packs"` // List of available language packs for this application +} + +// MessageType return the string telegram-type of LocalizationTargetInfo +func (localizationTargetInfo *LocalizationTargetInfo) MessageType() string { + return "localizationTargetInfo" +} + +// NewLocalizationTargetInfo creates a new LocalizationTargetInfo +// +// @param languagePacks List of available language packs for this application +func NewLocalizationTargetInfo(languagePacks []LanguagePackInfo) *LocalizationTargetInfo { + localizationTargetInfoTemp := LocalizationTargetInfo{ + tdCommon: tdCommon{Type: "localizationTargetInfo"}, + LanguagePacks: languagePacks, + } + + return &localizationTargetInfoTemp +} + +// DeviceTokenGoogleCloudMessaging A token for Google Cloud Messaging +type DeviceTokenGoogleCloudMessaging struct { + tdCommon + Token string `json:"token"` // Device registration token; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenGoogleCloudMessaging +func (deviceTokenGoogleCloudMessaging *DeviceTokenGoogleCloudMessaging) MessageType() string { + return "deviceTokenGoogleCloudMessaging" +} + +// NewDeviceTokenGoogleCloudMessaging creates a new DeviceTokenGoogleCloudMessaging +// +// @param token Device registration token; may be empty to de-register a device +func NewDeviceTokenGoogleCloudMessaging(token string) *DeviceTokenGoogleCloudMessaging { + deviceTokenGoogleCloudMessagingTemp := DeviceTokenGoogleCloudMessaging{ + tdCommon: tdCommon{Type: "deviceTokenGoogleCloudMessaging"}, + Token: token, + } + + return &deviceTokenGoogleCloudMessagingTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenGoogleCloudMessaging *DeviceTokenGoogleCloudMessaging) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenGoogleCloudMessagingType +} + +// DeviceTokenApplePush A token for Apple Push Notification service +type DeviceTokenApplePush struct { + tdCommon + DeviceToken string `json:"device_token"` // Device token; may be empty to de-register a device + IsAppSandbox bool `json:"is_app_sandbox"` // True, if App Sandbox is enabled +} + +// MessageType return the string telegram-type of DeviceTokenApplePush +func (deviceTokenApplePush *DeviceTokenApplePush) MessageType() string { + return "deviceTokenApplePush" +} + +// NewDeviceTokenApplePush creates a new DeviceTokenApplePush +// +// @param deviceToken Device token; may be empty to de-register a device +// @param isAppSandbox True, if App Sandbox is enabled +func NewDeviceTokenApplePush(deviceToken string, isAppSandbox bool) *DeviceTokenApplePush { + deviceTokenApplePushTemp := DeviceTokenApplePush{ + tdCommon: tdCommon{Type: "deviceTokenApplePush"}, + DeviceToken: deviceToken, + IsAppSandbox: isAppSandbox, + } + + return &deviceTokenApplePushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenApplePush *DeviceTokenApplePush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenApplePushType +} + +// DeviceTokenApplePushVoIP A token for Apple Push Notification service VoIP notifications +type DeviceTokenApplePushVoIP struct { + tdCommon + DeviceToken string `json:"device_token"` // Device token; may be empty to de-register a device + IsAppSandbox bool `json:"is_app_sandbox"` // True, if App Sandbox is enabled +} + +// MessageType return the string telegram-type of DeviceTokenApplePushVoIP +func (deviceTokenApplePushVoIP *DeviceTokenApplePushVoIP) MessageType() string { + return "deviceTokenApplePushVoIP" +} + +// NewDeviceTokenApplePushVoIP creates a new DeviceTokenApplePushVoIP +// +// @param deviceToken Device token; may be empty to de-register a device +// @param isAppSandbox True, if App Sandbox is enabled +func NewDeviceTokenApplePushVoIP(deviceToken string, isAppSandbox bool) *DeviceTokenApplePushVoIP { + deviceTokenApplePushVoIPTemp := DeviceTokenApplePushVoIP{ + tdCommon: tdCommon{Type: "deviceTokenApplePushVoIP"}, + DeviceToken: deviceToken, + IsAppSandbox: isAppSandbox, + } + + return &deviceTokenApplePushVoIPTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenApplePushVoIP *DeviceTokenApplePushVoIP) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenApplePushVoIPType +} + +// DeviceTokenWindowsPush A token for Windows Push Notification Services +type DeviceTokenWindowsPush struct { + tdCommon + AccessToken string `json:"access_token"` // The access token that will be used to send notifications; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenWindowsPush +func (deviceTokenWindowsPush *DeviceTokenWindowsPush) MessageType() string { + return "deviceTokenWindowsPush" +} + +// NewDeviceTokenWindowsPush creates a new DeviceTokenWindowsPush +// +// @param accessToken The access token that will be used to send notifications; may be empty to de-register a device +func NewDeviceTokenWindowsPush(accessToken string) *DeviceTokenWindowsPush { + deviceTokenWindowsPushTemp := DeviceTokenWindowsPush{ + tdCommon: tdCommon{Type: "deviceTokenWindowsPush"}, + AccessToken: accessToken, + } + + return &deviceTokenWindowsPushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenWindowsPush *DeviceTokenWindowsPush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenWindowsPushType +} + +// DeviceTokenMicrosoftPush A token for Microsoft Push Notification Service +type DeviceTokenMicrosoftPush struct { + tdCommon + ChannelURI string `json:"channel_uri"` // Push notification channel URI; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenMicrosoftPush +func (deviceTokenMicrosoftPush *DeviceTokenMicrosoftPush) MessageType() string { + return "deviceTokenMicrosoftPush" +} + +// NewDeviceTokenMicrosoftPush creates a new DeviceTokenMicrosoftPush +// +// @param channelURI Push notification channel URI; may be empty to de-register a device +func NewDeviceTokenMicrosoftPush(channelURI string) *DeviceTokenMicrosoftPush { + deviceTokenMicrosoftPushTemp := DeviceTokenMicrosoftPush{ + tdCommon: tdCommon{Type: "deviceTokenMicrosoftPush"}, + ChannelURI: channelURI, + } + + return &deviceTokenMicrosoftPushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenMicrosoftPush *DeviceTokenMicrosoftPush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenMicrosoftPushType +} + +// DeviceTokenMicrosoftPushVoIP A token for Microsoft Push Notification Service VoIP channel +type DeviceTokenMicrosoftPushVoIP struct { + tdCommon + ChannelURI string `json:"channel_uri"` // Push notification channel URI; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenMicrosoftPushVoIP +func (deviceTokenMicrosoftPushVoIP *DeviceTokenMicrosoftPushVoIP) MessageType() string { + return "deviceTokenMicrosoftPushVoIP" +} + +// NewDeviceTokenMicrosoftPushVoIP creates a new DeviceTokenMicrosoftPushVoIP +// +// @param channelURI Push notification channel URI; may be empty to de-register a device +func NewDeviceTokenMicrosoftPushVoIP(channelURI string) *DeviceTokenMicrosoftPushVoIP { + deviceTokenMicrosoftPushVoIPTemp := DeviceTokenMicrosoftPushVoIP{ + tdCommon: tdCommon{Type: "deviceTokenMicrosoftPushVoIP"}, + ChannelURI: channelURI, + } + + return &deviceTokenMicrosoftPushVoIPTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenMicrosoftPushVoIP *DeviceTokenMicrosoftPushVoIP) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenMicrosoftPushVoIPType +} + +// DeviceTokenWebPush A token for web Push API +type DeviceTokenWebPush struct { + tdCommon + Endpoint string `json:"endpoint"` // Absolute URL exposed by the push service where the application server can send push messages; may be empty to de-register a device + P256dhBase64url string `json:"p256dh_base64url"` // Base64url-encoded P-256 elliptic curve Diffie-Hellman public key + AuthBase64url string `json:"auth_base64url"` // Base64url-encoded authentication secret +} + +// MessageType return the string telegram-type of DeviceTokenWebPush +func (deviceTokenWebPush *DeviceTokenWebPush) MessageType() string { + return "deviceTokenWebPush" +} + +// NewDeviceTokenWebPush creates a new DeviceTokenWebPush +// +// @param endpoint Absolute URL exposed by the push service where the application server can send push messages; may be empty to de-register a device +// @param p256dhBase64url Base64url-encoded P-256 elliptic curve Diffie-Hellman public key +// @param authBase64url Base64url-encoded authentication secret +func NewDeviceTokenWebPush(endpoint string, p256dhBase64url string, authBase64url string) *DeviceTokenWebPush { + deviceTokenWebPushTemp := DeviceTokenWebPush{ + tdCommon: tdCommon{Type: "deviceTokenWebPush"}, + Endpoint: endpoint, + P256dhBase64url: p256dhBase64url, + AuthBase64url: authBase64url, + } + + return &deviceTokenWebPushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenWebPush *DeviceTokenWebPush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenWebPushType +} + +// DeviceTokenSimplePush A token for Simple Push API for Firefox OS +type DeviceTokenSimplePush struct { + tdCommon + Endpoint string `json:"endpoint"` // Absolute URL exposed by the push service where the application server can send push messages; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenSimplePush +func (deviceTokenSimplePush *DeviceTokenSimplePush) MessageType() string { + return "deviceTokenSimplePush" +} + +// NewDeviceTokenSimplePush creates a new DeviceTokenSimplePush +// +// @param endpoint Absolute URL exposed by the push service where the application server can send push messages; may be empty to de-register a device +func NewDeviceTokenSimplePush(endpoint string) *DeviceTokenSimplePush { + deviceTokenSimplePushTemp := DeviceTokenSimplePush{ + tdCommon: tdCommon{Type: "deviceTokenSimplePush"}, + Endpoint: endpoint, + } + + return &deviceTokenSimplePushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenSimplePush *DeviceTokenSimplePush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenSimplePushType +} + +// DeviceTokenUbuntuPush A token for Ubuntu Push Client service +type DeviceTokenUbuntuPush struct { + tdCommon + Token string `json:"token"` // Token; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenUbuntuPush +func (deviceTokenUbuntuPush *DeviceTokenUbuntuPush) MessageType() string { + return "deviceTokenUbuntuPush" +} + +// NewDeviceTokenUbuntuPush creates a new DeviceTokenUbuntuPush +// +// @param token Token; may be empty to de-register a device +func NewDeviceTokenUbuntuPush(token string) *DeviceTokenUbuntuPush { + deviceTokenUbuntuPushTemp := DeviceTokenUbuntuPush{ + tdCommon: tdCommon{Type: "deviceTokenUbuntuPush"}, + Token: token, + } + + return &deviceTokenUbuntuPushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenUbuntuPush *DeviceTokenUbuntuPush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenUbuntuPushType +} + +// DeviceTokenBlackBerryPush A token for BlackBerry Push Service +type DeviceTokenBlackBerryPush struct { + tdCommon + Token string `json:"token"` // Token; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenBlackBerryPush +func (deviceTokenBlackBerryPush *DeviceTokenBlackBerryPush) MessageType() string { + return "deviceTokenBlackBerryPush" +} + +// NewDeviceTokenBlackBerryPush creates a new DeviceTokenBlackBerryPush +// +// @param token Token; may be empty to de-register a device +func NewDeviceTokenBlackBerryPush(token string) *DeviceTokenBlackBerryPush { + deviceTokenBlackBerryPushTemp := DeviceTokenBlackBerryPush{ + tdCommon: tdCommon{Type: "deviceTokenBlackBerryPush"}, + Token: token, + } + + return &deviceTokenBlackBerryPushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenBlackBerryPush *DeviceTokenBlackBerryPush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenBlackBerryPushType +} + +// DeviceTokenTizenPush A token for Tizen Push Service +type DeviceTokenTizenPush struct { + tdCommon + RegID string `json:"reg_id"` // Push service registration identifier; may be empty to de-register a device +} + +// MessageType return the string telegram-type of DeviceTokenTizenPush +func (deviceTokenTizenPush *DeviceTokenTizenPush) MessageType() string { + return "deviceTokenTizenPush" +} + +// NewDeviceTokenTizenPush creates a new DeviceTokenTizenPush +// +// @param regID Push service registration identifier; may be empty to de-register a device +func NewDeviceTokenTizenPush(regID string) *DeviceTokenTizenPush { + deviceTokenTizenPushTemp := DeviceTokenTizenPush{ + tdCommon: tdCommon{Type: "deviceTokenTizenPush"}, + RegID: regID, + } + + return &deviceTokenTizenPushTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenTizenPush *DeviceTokenTizenPush) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenTizenPushType +} + +// Wallpaper Contains information about a wallpaper +type Wallpaper struct { + tdCommon + ID int32 `json:"id"` // Unique persistent wallpaper identifier + Sizes []PhotoSize `json:"sizes"` // Available variants of the wallpaper in different sizes. These photos can only be downloaded; they can't be sent in a message + Color int32 `json:"color"` // Main color of the wallpaper in RGB24 format; should be treated as background color if no photos are specified +} + +// MessageType return the string telegram-type of Wallpaper +func (wallpaper *Wallpaper) MessageType() string { + return "wallpaper" +} + +// NewWallpaper creates a new Wallpaper +// +// @param iD Unique persistent wallpaper identifier +// @param sizes Available variants of the wallpaper in different sizes. These photos can only be downloaded; they can't be sent in a message +// @param color Main color of the wallpaper in RGB24 format; should be treated as background color if no photos are specified +func NewWallpaper(iD int32, sizes []PhotoSize, color int32) *Wallpaper { + wallpaperTemp := Wallpaper{ + tdCommon: tdCommon{Type: "wallpaper"}, + ID: iD, + Sizes: sizes, + Color: color, + } + + return &wallpaperTemp +} + +// Wallpapers Contains a list of wallpapers +type Wallpapers struct { + tdCommon + Wallpapers []Wallpaper `json:"wallpapers"` // A list of wallpapers +} + +// MessageType return the string telegram-type of Wallpapers +func (wallpapers *Wallpapers) MessageType() string { + return "wallpapers" +} + +// NewWallpapers creates a new Wallpapers +// +// @param wallpapers A list of wallpapers +func NewWallpapers(wallpapers []Wallpaper) *Wallpapers { + wallpapersTemp := Wallpapers{ + tdCommon: tdCommon{Type: "wallpapers"}, + Wallpapers: wallpapers, + } + + return &wallpapersTemp +} + +// Hashtags Contains a list of hashtags +type Hashtags struct { + tdCommon + Hashtags []string `json:"hashtags"` // A list of hashtags +} + +// MessageType return the string telegram-type of Hashtags +func (hashtags *Hashtags) MessageType() string { + return "hashtags" +} + +// NewHashtags creates a new Hashtags +// +// @param hashtags A list of hashtags +func NewHashtags(hashtags []string) *Hashtags { + hashtagsTemp := Hashtags{ + tdCommon: tdCommon{Type: "hashtags"}, + Hashtags: hashtags, + } + + return &hashtagsTemp +} + +// CheckChatUsernameResultOk The username can be set +type CheckChatUsernameResultOk struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckChatUsernameResultOk +func (checkChatUsernameResultOk *CheckChatUsernameResultOk) MessageType() string { + return "checkChatUsernameResultOk" +} + +// NewCheckChatUsernameResultOk creates a new CheckChatUsernameResultOk +// +func NewCheckChatUsernameResultOk() *CheckChatUsernameResultOk { + checkChatUsernameResultOkTemp := CheckChatUsernameResultOk{ + tdCommon: tdCommon{Type: "checkChatUsernameResultOk"}, + } + + return &checkChatUsernameResultOkTemp +} + +// GetCheckChatUsernameResultEnum return the enum type of this object +func (checkChatUsernameResultOk *CheckChatUsernameResultOk) GetCheckChatUsernameResultEnum() CheckChatUsernameResultEnum { + return CheckChatUsernameResultOkType +} + +// CheckChatUsernameResultUsernameInvalid The username is invalid +type CheckChatUsernameResultUsernameInvalid struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckChatUsernameResultUsernameInvalid +func (checkChatUsernameResultUsernameInvalid *CheckChatUsernameResultUsernameInvalid) MessageType() string { + return "checkChatUsernameResultUsernameInvalid" +} + +// NewCheckChatUsernameResultUsernameInvalid creates a new CheckChatUsernameResultUsernameInvalid +// +func NewCheckChatUsernameResultUsernameInvalid() *CheckChatUsernameResultUsernameInvalid { + checkChatUsernameResultUsernameInvalidTemp := CheckChatUsernameResultUsernameInvalid{ + tdCommon: tdCommon{Type: "checkChatUsernameResultUsernameInvalid"}, + } + + return &checkChatUsernameResultUsernameInvalidTemp +} + +// GetCheckChatUsernameResultEnum return the enum type of this object +func (checkChatUsernameResultUsernameInvalid *CheckChatUsernameResultUsernameInvalid) GetCheckChatUsernameResultEnum() CheckChatUsernameResultEnum { + return CheckChatUsernameResultUsernameInvalidType +} + +// CheckChatUsernameResultUsernameOccupied The username is occupied +type CheckChatUsernameResultUsernameOccupied struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckChatUsernameResultUsernameOccupied +func (checkChatUsernameResultUsernameOccupied *CheckChatUsernameResultUsernameOccupied) MessageType() string { + return "checkChatUsernameResultUsernameOccupied" +} + +// NewCheckChatUsernameResultUsernameOccupied creates a new CheckChatUsernameResultUsernameOccupied +// +func NewCheckChatUsernameResultUsernameOccupied() *CheckChatUsernameResultUsernameOccupied { + checkChatUsernameResultUsernameOccupiedTemp := CheckChatUsernameResultUsernameOccupied{ + tdCommon: tdCommon{Type: "checkChatUsernameResultUsernameOccupied"}, + } + + return &checkChatUsernameResultUsernameOccupiedTemp +} + +// GetCheckChatUsernameResultEnum return the enum type of this object +func (checkChatUsernameResultUsernameOccupied *CheckChatUsernameResultUsernameOccupied) GetCheckChatUsernameResultEnum() CheckChatUsernameResultEnum { + return CheckChatUsernameResultUsernameOccupiedType +} + +// CheckChatUsernameResultPublicChatsTooMuch The user has too much public chats, one of them should be made private first +type CheckChatUsernameResultPublicChatsTooMuch struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckChatUsernameResultPublicChatsTooMuch +func (checkChatUsernameResultPublicChatsTooMuch *CheckChatUsernameResultPublicChatsTooMuch) MessageType() string { + return "checkChatUsernameResultPublicChatsTooMuch" +} + +// NewCheckChatUsernameResultPublicChatsTooMuch creates a new CheckChatUsernameResultPublicChatsTooMuch +// +func NewCheckChatUsernameResultPublicChatsTooMuch() *CheckChatUsernameResultPublicChatsTooMuch { + checkChatUsernameResultPublicChatsTooMuchTemp := CheckChatUsernameResultPublicChatsTooMuch{ + tdCommon: tdCommon{Type: "checkChatUsernameResultPublicChatsTooMuch"}, + } + + return &checkChatUsernameResultPublicChatsTooMuchTemp +} + +// GetCheckChatUsernameResultEnum return the enum type of this object +func (checkChatUsernameResultPublicChatsTooMuch *CheckChatUsernameResultPublicChatsTooMuch) GetCheckChatUsernameResultEnum() CheckChatUsernameResultEnum { + return CheckChatUsernameResultPublicChatsTooMuchType +} + +// CheckChatUsernameResultPublicGroupsUnavailable The user can't be a member of a public supergroup +type CheckChatUsernameResultPublicGroupsUnavailable struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckChatUsernameResultPublicGroupsUnavailable +func (checkChatUsernameResultPublicGroupsUnavailable *CheckChatUsernameResultPublicGroupsUnavailable) MessageType() string { + return "checkChatUsernameResultPublicGroupsUnavailable" +} + +// NewCheckChatUsernameResultPublicGroupsUnavailable creates a new CheckChatUsernameResultPublicGroupsUnavailable +// +func NewCheckChatUsernameResultPublicGroupsUnavailable() *CheckChatUsernameResultPublicGroupsUnavailable { + checkChatUsernameResultPublicGroupsUnavailableTemp := CheckChatUsernameResultPublicGroupsUnavailable{ + tdCommon: tdCommon{Type: "checkChatUsernameResultPublicGroupsUnavailable"}, + } + + return &checkChatUsernameResultPublicGroupsUnavailableTemp +} + +// GetCheckChatUsernameResultEnum return the enum type of this object +func (checkChatUsernameResultPublicGroupsUnavailable *CheckChatUsernameResultPublicGroupsUnavailable) GetCheckChatUsernameResultEnum() CheckChatUsernameResultEnum { + return CheckChatUsernameResultPublicGroupsUnavailableType +} + +// OptionValueBoolean Boolean option +type OptionValueBoolean struct { + tdCommon + Value bool `json:"value"` // The value of the option +} + +// MessageType return the string telegram-type of OptionValueBoolean +func (optionValueBoolean *OptionValueBoolean) MessageType() string { + return "optionValueBoolean" +} + +// NewOptionValueBoolean creates a new OptionValueBoolean +// +// @param value The value of the option +func NewOptionValueBoolean(value bool) *OptionValueBoolean { + optionValueBooleanTemp := OptionValueBoolean{ + tdCommon: tdCommon{Type: "optionValueBoolean"}, + Value: value, + } + + return &optionValueBooleanTemp +} + +// GetOptionValueEnum return the enum type of this object +func (optionValueBoolean *OptionValueBoolean) GetOptionValueEnum() OptionValueEnum { + return OptionValueBooleanType +} + +// OptionValueEmpty An unknown option or an option which has a default value +type OptionValueEmpty struct { + tdCommon +} + +// MessageType return the string telegram-type of OptionValueEmpty +func (optionValueEmpty *OptionValueEmpty) MessageType() string { + return "optionValueEmpty" +} + +// NewOptionValueEmpty creates a new OptionValueEmpty +// +func NewOptionValueEmpty() *OptionValueEmpty { + optionValueEmptyTemp := OptionValueEmpty{ + tdCommon: tdCommon{Type: "optionValueEmpty"}, + } + + return &optionValueEmptyTemp +} + +// GetOptionValueEnum return the enum type of this object +func (optionValueEmpty *OptionValueEmpty) GetOptionValueEnum() OptionValueEnum { + return OptionValueEmptyType +} + +// OptionValueInteger An integer option +type OptionValueInteger struct { + tdCommon + Value int32 `json:"value"` // The value of the option +} + +// MessageType return the string telegram-type of OptionValueInteger +func (optionValueInteger *OptionValueInteger) MessageType() string { + return "optionValueInteger" +} + +// NewOptionValueInteger creates a new OptionValueInteger +// +// @param value The value of the option +func NewOptionValueInteger(value int32) *OptionValueInteger { + optionValueIntegerTemp := OptionValueInteger{ + tdCommon: tdCommon{Type: "optionValueInteger"}, + Value: value, + } + + return &optionValueIntegerTemp +} + +// GetOptionValueEnum return the enum type of this object +func (optionValueInteger *OptionValueInteger) GetOptionValueEnum() OptionValueEnum { + return OptionValueIntegerType +} + +// OptionValueString A string option +type OptionValueString struct { + tdCommon + Value string `json:"value"` // The value of the option +} + +// MessageType return the string telegram-type of OptionValueString +func (optionValueString *OptionValueString) MessageType() string { + return "optionValueString" +} + +// NewOptionValueString creates a new OptionValueString +// +// @param value The value of the option +func NewOptionValueString(value string) *OptionValueString { + optionValueStringTemp := OptionValueString{ + tdCommon: tdCommon{Type: "optionValueString"}, + Value: value, + } + + return &optionValueStringTemp +} + +// GetOptionValueEnum return the enum type of this object +func (optionValueString *OptionValueString) GetOptionValueEnum() OptionValueEnum { + return OptionValueStringType +} + +// UserPrivacySettingRuleAllowAll A rule to allow all users to do something +type UserPrivacySettingRuleAllowAll struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleAllowAll +func (userPrivacySettingRuleAllowAll *UserPrivacySettingRuleAllowAll) MessageType() string { + return "userPrivacySettingRuleAllowAll" +} + +// NewUserPrivacySettingRuleAllowAll creates a new UserPrivacySettingRuleAllowAll +// +func NewUserPrivacySettingRuleAllowAll() *UserPrivacySettingRuleAllowAll { + userPrivacySettingRuleAllowAllTemp := UserPrivacySettingRuleAllowAll{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleAllowAll"}, + } + + return &userPrivacySettingRuleAllowAllTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleAllowAll *UserPrivacySettingRuleAllowAll) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleAllowAllType +} + +// UserPrivacySettingRuleAllowContacts A rule to allow all of a user's contacts to do something +type UserPrivacySettingRuleAllowContacts struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleAllowContacts +func (userPrivacySettingRuleAllowContacts *UserPrivacySettingRuleAllowContacts) MessageType() string { + return "userPrivacySettingRuleAllowContacts" +} + +// NewUserPrivacySettingRuleAllowContacts creates a new UserPrivacySettingRuleAllowContacts +// +func NewUserPrivacySettingRuleAllowContacts() *UserPrivacySettingRuleAllowContacts { + userPrivacySettingRuleAllowContactsTemp := UserPrivacySettingRuleAllowContacts{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleAllowContacts"}, + } + + return &userPrivacySettingRuleAllowContactsTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleAllowContacts *UserPrivacySettingRuleAllowContacts) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleAllowContactsType +} + +// UserPrivacySettingRuleAllowUsers A rule to allow certain specified users to do something +type UserPrivacySettingRuleAllowUsers struct { + tdCommon + UserIDs []int32 `json:"user_ids"` // The user identifiers +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleAllowUsers +func (userPrivacySettingRuleAllowUsers *UserPrivacySettingRuleAllowUsers) MessageType() string { + return "userPrivacySettingRuleAllowUsers" +} + +// NewUserPrivacySettingRuleAllowUsers creates a new UserPrivacySettingRuleAllowUsers +// +// @param userIDs The user identifiers +func NewUserPrivacySettingRuleAllowUsers(userIDs []int32) *UserPrivacySettingRuleAllowUsers { + userPrivacySettingRuleAllowUsersTemp := UserPrivacySettingRuleAllowUsers{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleAllowUsers"}, + UserIDs: userIDs, + } + + return &userPrivacySettingRuleAllowUsersTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleAllowUsers *UserPrivacySettingRuleAllowUsers) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleAllowUsersType +} + +// UserPrivacySettingRuleRestrictAll A rule to restrict all users from doing something +type UserPrivacySettingRuleRestrictAll struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleRestrictAll +func (userPrivacySettingRuleRestrictAll *UserPrivacySettingRuleRestrictAll) MessageType() string { + return "userPrivacySettingRuleRestrictAll" +} + +// NewUserPrivacySettingRuleRestrictAll creates a new UserPrivacySettingRuleRestrictAll +// +func NewUserPrivacySettingRuleRestrictAll() *UserPrivacySettingRuleRestrictAll { + userPrivacySettingRuleRestrictAllTemp := UserPrivacySettingRuleRestrictAll{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleRestrictAll"}, + } + + return &userPrivacySettingRuleRestrictAllTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleRestrictAll *UserPrivacySettingRuleRestrictAll) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleRestrictAllType +} + +// UserPrivacySettingRuleRestrictContacts A rule to restrict all contacts of a user from doing something +type UserPrivacySettingRuleRestrictContacts struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleRestrictContacts +func (userPrivacySettingRuleRestrictContacts *UserPrivacySettingRuleRestrictContacts) MessageType() string { + return "userPrivacySettingRuleRestrictContacts" +} + +// NewUserPrivacySettingRuleRestrictContacts creates a new UserPrivacySettingRuleRestrictContacts +// +func NewUserPrivacySettingRuleRestrictContacts() *UserPrivacySettingRuleRestrictContacts { + userPrivacySettingRuleRestrictContactsTemp := UserPrivacySettingRuleRestrictContacts{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleRestrictContacts"}, + } + + return &userPrivacySettingRuleRestrictContactsTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleRestrictContacts *UserPrivacySettingRuleRestrictContacts) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleRestrictContactsType +} + +// UserPrivacySettingRuleRestrictUsers A rule to restrict all specified users from doing something +type UserPrivacySettingRuleRestrictUsers struct { + tdCommon + UserIDs []int32 `json:"user_ids"` // The user identifiers +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleRestrictUsers +func (userPrivacySettingRuleRestrictUsers *UserPrivacySettingRuleRestrictUsers) MessageType() string { + return "userPrivacySettingRuleRestrictUsers" +} + +// NewUserPrivacySettingRuleRestrictUsers creates a new UserPrivacySettingRuleRestrictUsers +// +// @param userIDs The user identifiers +func NewUserPrivacySettingRuleRestrictUsers(userIDs []int32) *UserPrivacySettingRuleRestrictUsers { + userPrivacySettingRuleRestrictUsersTemp := UserPrivacySettingRuleRestrictUsers{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleRestrictUsers"}, + UserIDs: userIDs, + } + + return &userPrivacySettingRuleRestrictUsersTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleRestrictUsers *UserPrivacySettingRuleRestrictUsers) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleRestrictUsersType +} + +// UserPrivacySettingRules A list of privacy rules. Rules are matched in the specified order. The first matched rule defines the privacy setting for a given user. If no rule matches, the action is not allowed +type UserPrivacySettingRules struct { + tdCommon + Rules []UserPrivacySettingRule `json:"rules"` // A list of rules +} + +// MessageType return the string telegram-type of UserPrivacySettingRules +func (userPrivacySettingRules *UserPrivacySettingRules) MessageType() string { + return "userPrivacySettingRules" +} + +// NewUserPrivacySettingRules creates a new UserPrivacySettingRules +// +// @param rules A list of rules +func NewUserPrivacySettingRules(rules []UserPrivacySettingRule) *UserPrivacySettingRules { + userPrivacySettingRulesTemp := UserPrivacySettingRules{ + tdCommon: tdCommon{Type: "userPrivacySettingRules"}, + Rules: rules, + } + + return &userPrivacySettingRulesTemp +} + +// UserPrivacySettingShowStatus A privacy setting for managing whether the user's online status is visible +type UserPrivacySettingShowStatus struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingShowStatus +func (userPrivacySettingShowStatus *UserPrivacySettingShowStatus) MessageType() string { + return "userPrivacySettingShowStatus" +} + +// NewUserPrivacySettingShowStatus creates a new UserPrivacySettingShowStatus +// +func NewUserPrivacySettingShowStatus() *UserPrivacySettingShowStatus { + userPrivacySettingShowStatusTemp := UserPrivacySettingShowStatus{ + tdCommon: tdCommon{Type: "userPrivacySettingShowStatus"}, + } + + return &userPrivacySettingShowStatusTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingShowStatus *UserPrivacySettingShowStatus) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingShowStatusType +} + +// UserPrivacySettingAllowChatInvites A privacy setting for managing whether the user can be invited to chats +type UserPrivacySettingAllowChatInvites struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingAllowChatInvites +func (userPrivacySettingAllowChatInvites *UserPrivacySettingAllowChatInvites) MessageType() string { + return "userPrivacySettingAllowChatInvites" +} + +// NewUserPrivacySettingAllowChatInvites creates a new UserPrivacySettingAllowChatInvites +// +func NewUserPrivacySettingAllowChatInvites() *UserPrivacySettingAllowChatInvites { + userPrivacySettingAllowChatInvitesTemp := UserPrivacySettingAllowChatInvites{ + tdCommon: tdCommon{Type: "userPrivacySettingAllowChatInvites"}, + } + + return &userPrivacySettingAllowChatInvitesTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingAllowChatInvites *UserPrivacySettingAllowChatInvites) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingAllowChatInvitesType +} + +// UserPrivacySettingAllowCalls A privacy setting for managing whether the user can be called +type UserPrivacySettingAllowCalls struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingAllowCalls +func (userPrivacySettingAllowCalls *UserPrivacySettingAllowCalls) MessageType() string { + return "userPrivacySettingAllowCalls" +} + +// NewUserPrivacySettingAllowCalls creates a new UserPrivacySettingAllowCalls +// +func NewUserPrivacySettingAllowCalls() *UserPrivacySettingAllowCalls { + userPrivacySettingAllowCallsTemp := UserPrivacySettingAllowCalls{ + tdCommon: tdCommon{Type: "userPrivacySettingAllowCalls"}, + } + + return &userPrivacySettingAllowCallsTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingAllowCalls *UserPrivacySettingAllowCalls) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingAllowCallsType +} + +// AccountTTL Contains information about the period of inactivity after which the current user's account will automatically be deleted +type AccountTTL struct { + tdCommon + Days int32 `json:"days"` // Number of days of inactivity before the account will be flagged for deletion; should range from 30-366 days +} + +// MessageType return the string telegram-type of AccountTTL +func (accountTTL *AccountTTL) MessageType() string { + return "accountTtl" +} + +// NewAccountTTL creates a new AccountTTL +// +// @param days Number of days of inactivity before the account will be flagged for deletion; should range from 30-366 days +func NewAccountTTL(days int32) *AccountTTL { + accountTTLTemp := AccountTTL{ + tdCommon: tdCommon{Type: "accountTtl"}, + Days: days, + } + + return &accountTTLTemp +} + +// Session Contains information about one session in a Telegram application used by the current user +type Session struct { + tdCommon + ID JSONInt64 `json:"id"` // Session identifier + IsCurrent bool `json:"is_current"` // True, if this session is the current session + APIID int32 `json:"api_id"` // Telegram API identifier, as provided by the application + ApplicationName string `json:"application_name"` // Name of the application, as provided by the application + ApplicationVersion string `json:"application_version"` // The version of the application, as provided by the application + IsOfficialApplication bool `json:"is_official_application"` // True, if the application is an official application or uses the api_id of an official application + DeviceModel string `json:"device_model"` // Model of the device the application has been run or is running on, as provided by the application + Platform string `json:"platform"` // Operating system the application has been run or is running on, as provided by the application + SystemVersion string `json:"system_version"` // Version of the operating system the application has been run or is running on, as provided by the application + LogInDate int32 `json:"log_in_date"` // Point in time (Unix timestamp) when the user has logged in + LastActiveDate int32 `json:"last_active_date"` // Point in time (Unix timestamp) when the session was last used + IP string `json:"ip"` // IP address from which the session was created, in human-readable format + Country string `json:"country"` // A two-letter country code for the country from which the session was created, based on the IP address + Region string `json:"region"` // Region code from which the session was created, based on the IP address +} + +// MessageType return the string telegram-type of Session +func (session *Session) MessageType() string { + return "session" +} + +// NewSession creates a new Session +// +// @param iD Session identifier +// @param isCurrent True, if this session is the current session +// @param aPIID Telegram API identifier, as provided by the application +// @param applicationName Name of the application, as provided by the application +// @param applicationVersion The version of the application, as provided by the application +// @param isOfficialApplication True, if the application is an official application or uses the api_id of an official application +// @param deviceModel Model of the device the application has been run or is running on, as provided by the application +// @param platform Operating system the application has been run or is running on, as provided by the application +// @param systemVersion Version of the operating system the application has been run or is running on, as provided by the application +// @param logInDate Point in time (Unix timestamp) when the user has logged in +// @param lastActiveDate Point in time (Unix timestamp) when the session was last used +// @param iP IP address from which the session was created, in human-readable format +// @param country A two-letter country code for the country from which the session was created, based on the IP address +// @param region Region code from which the session was created, based on the IP address +func NewSession(iD JSONInt64, isCurrent bool, aPIID int32, applicationName string, applicationVersion string, isOfficialApplication bool, deviceModel string, platform string, systemVersion string, logInDate int32, lastActiveDate int32, iP string, country string, region string) *Session { + sessionTemp := Session{ + tdCommon: tdCommon{Type: "session"}, + ID: iD, + IsCurrent: isCurrent, + APIID: aPIID, + ApplicationName: applicationName, + ApplicationVersion: applicationVersion, + IsOfficialApplication: isOfficialApplication, + DeviceModel: deviceModel, + Platform: platform, + SystemVersion: systemVersion, + LogInDate: logInDate, + LastActiveDate: lastActiveDate, + IP: iP, + Country: country, + Region: region, + } + + return &sessionTemp +} + +// Sessions Contains a list of sessions +type Sessions struct { + tdCommon + Sessions []Session `json:"sessions"` // List of sessions +} + +// MessageType return the string telegram-type of Sessions +func (sessions *Sessions) MessageType() string { + return "sessions" +} + +// NewSessions creates a new Sessions +// +// @param sessions List of sessions +func NewSessions(sessions []Session) *Sessions { + sessionsTemp := Sessions{ + tdCommon: tdCommon{Type: "sessions"}, + Sessions: sessions, + } + + return &sessionsTemp +} + +// ConnectedWebsite Contains information about one website the current user is logged in with Telegram +type ConnectedWebsite struct { + tdCommon + ID JSONInt64 `json:"id"` // Website identifier + DomainName string `json:"domain_name"` // The domain name of the website + BotUserID int32 `json:"bot_user_id"` // User identifier of a bot linked with the website + Browser string `json:"browser"` // The version of a browser used to log in + Platform string `json:"platform"` // Operating system the browser is running on + LogInDate int32 `json:"log_in_date"` // Point in time (Unix timestamp) when the user was logged in + LastActiveDate int32 `json:"last_active_date"` // Point in time (Unix timestamp) when obtained authorization was last used + IP string `json:"ip"` // IP address from which the user was logged in, in human-readable format + Location string `json:"location"` // Human-readable description of a country and a region, from which the user was logged in, based on the IP address +} + +// MessageType return the string telegram-type of ConnectedWebsite +func (connectedWebsite *ConnectedWebsite) MessageType() string { + return "connectedWebsite" +} + +// NewConnectedWebsite creates a new ConnectedWebsite +// +// @param iD Website identifier +// @param domainName The domain name of the website +// @param botUserID User identifier of a bot linked with the website +// @param browser The version of a browser used to log in +// @param platform Operating system the browser is running on +// @param logInDate Point in time (Unix timestamp) when the user was logged in +// @param lastActiveDate Point in time (Unix timestamp) when obtained authorization was last used +// @param iP IP address from which the user was logged in, in human-readable format +// @param location Human-readable description of a country and a region, from which the user was logged in, based on the IP address +func NewConnectedWebsite(iD JSONInt64, domainName string, botUserID int32, browser string, platform string, logInDate int32, lastActiveDate int32, iP string, location string) *ConnectedWebsite { + connectedWebsiteTemp := ConnectedWebsite{ + tdCommon: tdCommon{Type: "connectedWebsite"}, + ID: iD, + DomainName: domainName, + BotUserID: botUserID, + Browser: browser, + Platform: platform, + LogInDate: logInDate, + LastActiveDate: lastActiveDate, + IP: iP, + Location: location, + } + + return &connectedWebsiteTemp +} + +// ConnectedWebsites Contains a list of websites the current user is logged in with Telegram +type ConnectedWebsites struct { + tdCommon + Websites []ConnectedWebsite `json:"websites"` // List of connected websites +} + +// MessageType return the string telegram-type of ConnectedWebsites +func (connectedWebsites *ConnectedWebsites) MessageType() string { + return "connectedWebsites" +} + +// NewConnectedWebsites creates a new ConnectedWebsites +// +// @param websites List of connected websites +func NewConnectedWebsites(websites []ConnectedWebsite) *ConnectedWebsites { + connectedWebsitesTemp := ConnectedWebsites{ + tdCommon: tdCommon{Type: "connectedWebsites"}, + Websites: websites, + } + + return &connectedWebsitesTemp +} + +// ChatReportSpamState Contains information about the availability of the "Report spam" action for a chat +type ChatReportSpamState struct { + tdCommon + CanReportSpam bool `json:"can_report_spam"` // True, if a prompt with the "Report spam" action should be shown to the user +} + +// MessageType return the string telegram-type of ChatReportSpamState +func (chatReportSpamState *ChatReportSpamState) MessageType() string { + return "chatReportSpamState" +} + +// NewChatReportSpamState creates a new ChatReportSpamState +// +// @param canReportSpam True, if a prompt with the "Report spam" action should be shown to the user +func NewChatReportSpamState(canReportSpam bool) *ChatReportSpamState { + chatReportSpamStateTemp := ChatReportSpamState{ + tdCommon: tdCommon{Type: "chatReportSpamState"}, + CanReportSpam: canReportSpam, + } + + return &chatReportSpamStateTemp +} + +// ChatReportReasonSpam The chat contains spam messages +type ChatReportReasonSpam struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonSpam +func (chatReportReasonSpam *ChatReportReasonSpam) MessageType() string { + return "chatReportReasonSpam" +} + +// NewChatReportReasonSpam creates a new ChatReportReasonSpam +// +func NewChatReportReasonSpam() *ChatReportReasonSpam { + chatReportReasonSpamTemp := ChatReportReasonSpam{ + tdCommon: tdCommon{Type: "chatReportReasonSpam"}, + } + + return &chatReportReasonSpamTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonSpam *ChatReportReasonSpam) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonSpamType +} + +// ChatReportReasonViolence The chat promotes violence +type ChatReportReasonViolence struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonViolence +func (chatReportReasonViolence *ChatReportReasonViolence) MessageType() string { + return "chatReportReasonViolence" +} + +// NewChatReportReasonViolence creates a new ChatReportReasonViolence +// +func NewChatReportReasonViolence() *ChatReportReasonViolence { + chatReportReasonViolenceTemp := ChatReportReasonViolence{ + tdCommon: tdCommon{Type: "chatReportReasonViolence"}, + } + + return &chatReportReasonViolenceTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonViolence *ChatReportReasonViolence) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonViolenceType +} + +// ChatReportReasonPornography The chat contains pornographic messages +type ChatReportReasonPornography struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonPornography +func (chatReportReasonPornography *ChatReportReasonPornography) MessageType() string { + return "chatReportReasonPornography" +} + +// NewChatReportReasonPornography creates a new ChatReportReasonPornography +// +func NewChatReportReasonPornography() *ChatReportReasonPornography { + chatReportReasonPornographyTemp := ChatReportReasonPornography{ + tdCommon: tdCommon{Type: "chatReportReasonPornography"}, + } + + return &chatReportReasonPornographyTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonPornography *ChatReportReasonPornography) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonPornographyType +} + +// ChatReportReasonCopyright The chat contains copyrighted content +type ChatReportReasonCopyright struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonCopyright +func (chatReportReasonCopyright *ChatReportReasonCopyright) MessageType() string { + return "chatReportReasonCopyright" +} + +// NewChatReportReasonCopyright creates a new ChatReportReasonCopyright +// +func NewChatReportReasonCopyright() *ChatReportReasonCopyright { + chatReportReasonCopyrightTemp := ChatReportReasonCopyright{ + tdCommon: tdCommon{Type: "chatReportReasonCopyright"}, + } + + return &chatReportReasonCopyrightTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonCopyright *ChatReportReasonCopyright) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonCopyrightType +} + +// ChatReportReasonCustom A custom reason provided by the user +type ChatReportReasonCustom struct { + tdCommon + Text string `json:"text"` // Report text +} + +// MessageType return the string telegram-type of ChatReportReasonCustom +func (chatReportReasonCustom *ChatReportReasonCustom) MessageType() string { + return "chatReportReasonCustom" +} + +// NewChatReportReasonCustom creates a new ChatReportReasonCustom +// +// @param text Report text +func NewChatReportReasonCustom(text string) *ChatReportReasonCustom { + chatReportReasonCustomTemp := ChatReportReasonCustom{ + tdCommon: tdCommon{Type: "chatReportReasonCustom"}, + Text: text, + } + + return &chatReportReasonCustomTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonCustom *ChatReportReasonCustom) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonCustomType +} + +// PublicMessageLink Contains a public HTTPS link to a message in a public supergroup or channel +type PublicMessageLink struct { + tdCommon + Link string `json:"link"` // Message link + HTML string `json:"html"` // HTML-code for embedding the message +} + +// MessageType return the string telegram-type of PublicMessageLink +func (publicMessageLink *PublicMessageLink) MessageType() string { + return "publicMessageLink" +} + +// NewPublicMessageLink creates a new PublicMessageLink +// +// @param link Message link +// @param hTML HTML-code for embedding the message +func NewPublicMessageLink(link string, hTML string) *PublicMessageLink { + publicMessageLinkTemp := PublicMessageLink{ + tdCommon: tdCommon{Type: "publicMessageLink"}, + Link: link, + HTML: hTML, + } + + return &publicMessageLinkTemp +} + +// FileTypeNone The data is not a file +type FileTypeNone struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeNone +func (fileTypeNone *FileTypeNone) MessageType() string { + return "fileTypeNone" +} + +// NewFileTypeNone creates a new FileTypeNone +// +func NewFileTypeNone() *FileTypeNone { + fileTypeNoneTemp := FileTypeNone{ + tdCommon: tdCommon{Type: "fileTypeNone"}, + } + + return &fileTypeNoneTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeNone *FileTypeNone) GetFileTypeEnum() FileTypeEnum { + return FileTypeNoneType +} + +// FileTypeAnimation The file is an animation +type FileTypeAnimation struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeAnimation +func (fileTypeAnimation *FileTypeAnimation) MessageType() string { + return "fileTypeAnimation" +} + +// NewFileTypeAnimation creates a new FileTypeAnimation +// +func NewFileTypeAnimation() *FileTypeAnimation { + fileTypeAnimationTemp := FileTypeAnimation{ + tdCommon: tdCommon{Type: "fileTypeAnimation"}, + } + + return &fileTypeAnimationTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeAnimation *FileTypeAnimation) GetFileTypeEnum() FileTypeEnum { + return FileTypeAnimationType +} + +// FileTypeAudio The file is an audio file +type FileTypeAudio struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeAudio +func (fileTypeAudio *FileTypeAudio) MessageType() string { + return "fileTypeAudio" +} + +// NewFileTypeAudio creates a new FileTypeAudio +// +func NewFileTypeAudio() *FileTypeAudio { + fileTypeAudioTemp := FileTypeAudio{ + tdCommon: tdCommon{Type: "fileTypeAudio"}, + } + + return &fileTypeAudioTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeAudio *FileTypeAudio) GetFileTypeEnum() FileTypeEnum { + return FileTypeAudioType +} + +// FileTypeDocument The file is a document +type FileTypeDocument struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeDocument +func (fileTypeDocument *FileTypeDocument) MessageType() string { + return "fileTypeDocument" +} + +// NewFileTypeDocument creates a new FileTypeDocument +// +func NewFileTypeDocument() *FileTypeDocument { + fileTypeDocumentTemp := FileTypeDocument{ + tdCommon: tdCommon{Type: "fileTypeDocument"}, + } + + return &fileTypeDocumentTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeDocument *FileTypeDocument) GetFileTypeEnum() FileTypeEnum { + return FileTypeDocumentType +} + +// FileTypePhoto The file is a photo +type FileTypePhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypePhoto +func (fileTypePhoto *FileTypePhoto) MessageType() string { + return "fileTypePhoto" +} + +// NewFileTypePhoto creates a new FileTypePhoto +// +func NewFileTypePhoto() *FileTypePhoto { + fileTypePhotoTemp := FileTypePhoto{ + tdCommon: tdCommon{Type: "fileTypePhoto"}, + } + + return &fileTypePhotoTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypePhoto *FileTypePhoto) GetFileTypeEnum() FileTypeEnum { + return FileTypePhotoType +} + +// FileTypeProfilePhoto The file is a profile photo +type FileTypeProfilePhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeProfilePhoto +func (fileTypeProfilePhoto *FileTypeProfilePhoto) MessageType() string { + return "fileTypeProfilePhoto" +} + +// NewFileTypeProfilePhoto creates a new FileTypeProfilePhoto +// +func NewFileTypeProfilePhoto() *FileTypeProfilePhoto { + fileTypeProfilePhotoTemp := FileTypeProfilePhoto{ + tdCommon: tdCommon{Type: "fileTypeProfilePhoto"}, + } + + return &fileTypeProfilePhotoTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeProfilePhoto *FileTypeProfilePhoto) GetFileTypeEnum() FileTypeEnum { + return FileTypeProfilePhotoType +} + +// FileTypeSecret The file was sent to a secret chat (the file type is not known to the server) +type FileTypeSecret struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeSecret +func (fileTypeSecret *FileTypeSecret) MessageType() string { + return "fileTypeSecret" +} + +// NewFileTypeSecret creates a new FileTypeSecret +// +func NewFileTypeSecret() *FileTypeSecret { + fileTypeSecretTemp := FileTypeSecret{ + tdCommon: tdCommon{Type: "fileTypeSecret"}, + } + + return &fileTypeSecretTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeSecret *FileTypeSecret) GetFileTypeEnum() FileTypeEnum { + return FileTypeSecretType +} + +// FileTypeSecretThumbnail The file is a thumbnail of a file from a secret chat +type FileTypeSecretThumbnail struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeSecretThumbnail +func (fileTypeSecretThumbnail *FileTypeSecretThumbnail) MessageType() string { + return "fileTypeSecretThumbnail" +} + +// NewFileTypeSecretThumbnail creates a new FileTypeSecretThumbnail +// +func NewFileTypeSecretThumbnail() *FileTypeSecretThumbnail { + fileTypeSecretThumbnailTemp := FileTypeSecretThumbnail{ + tdCommon: tdCommon{Type: "fileTypeSecretThumbnail"}, + } + + return &fileTypeSecretThumbnailTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeSecretThumbnail *FileTypeSecretThumbnail) GetFileTypeEnum() FileTypeEnum { + return FileTypeSecretThumbnailType +} + +// FileTypeSecure The file is a file from Secure storage used for storing Telegram Passport files +type FileTypeSecure struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeSecure +func (fileTypeSecure *FileTypeSecure) MessageType() string { + return "fileTypeSecure" +} + +// NewFileTypeSecure creates a new FileTypeSecure +// +func NewFileTypeSecure() *FileTypeSecure { + fileTypeSecureTemp := FileTypeSecure{ + tdCommon: tdCommon{Type: "fileTypeSecure"}, + } + + return &fileTypeSecureTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeSecure *FileTypeSecure) GetFileTypeEnum() FileTypeEnum { + return FileTypeSecureType +} + +// FileTypeSticker The file is a sticker +type FileTypeSticker struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeSticker +func (fileTypeSticker *FileTypeSticker) MessageType() string { + return "fileTypeSticker" +} + +// NewFileTypeSticker creates a new FileTypeSticker +// +func NewFileTypeSticker() *FileTypeSticker { + fileTypeStickerTemp := FileTypeSticker{ + tdCommon: tdCommon{Type: "fileTypeSticker"}, + } + + return &fileTypeStickerTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeSticker *FileTypeSticker) GetFileTypeEnum() FileTypeEnum { + return FileTypeStickerType +} + +// FileTypeThumbnail The file is a thumbnail of another file +type FileTypeThumbnail struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeThumbnail +func (fileTypeThumbnail *FileTypeThumbnail) MessageType() string { + return "fileTypeThumbnail" +} + +// NewFileTypeThumbnail creates a new FileTypeThumbnail +// +func NewFileTypeThumbnail() *FileTypeThumbnail { + fileTypeThumbnailTemp := FileTypeThumbnail{ + tdCommon: tdCommon{Type: "fileTypeThumbnail"}, + } + + return &fileTypeThumbnailTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeThumbnail *FileTypeThumbnail) GetFileTypeEnum() FileTypeEnum { + return FileTypeThumbnailType +} + +// FileTypeUnknown The file type is not yet known +type FileTypeUnknown struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeUnknown +func (fileTypeUnknown *FileTypeUnknown) MessageType() string { + return "fileTypeUnknown" +} + +// NewFileTypeUnknown creates a new FileTypeUnknown +// +func NewFileTypeUnknown() *FileTypeUnknown { + fileTypeUnknownTemp := FileTypeUnknown{ + tdCommon: tdCommon{Type: "fileTypeUnknown"}, + } + + return &fileTypeUnknownTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeUnknown *FileTypeUnknown) GetFileTypeEnum() FileTypeEnum { + return FileTypeUnknownType +} + +// FileTypeVideo The file is a video +type FileTypeVideo struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeVideo +func (fileTypeVideo *FileTypeVideo) MessageType() string { + return "fileTypeVideo" +} + +// NewFileTypeVideo creates a new FileTypeVideo +// +func NewFileTypeVideo() *FileTypeVideo { + fileTypeVideoTemp := FileTypeVideo{ + tdCommon: tdCommon{Type: "fileTypeVideo"}, + } + + return &fileTypeVideoTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeVideo *FileTypeVideo) GetFileTypeEnum() FileTypeEnum { + return FileTypeVideoType +} + +// FileTypeVideoNote The file is a video note +type FileTypeVideoNote struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeVideoNote +func (fileTypeVideoNote *FileTypeVideoNote) MessageType() string { + return "fileTypeVideoNote" +} + +// NewFileTypeVideoNote creates a new FileTypeVideoNote +// +func NewFileTypeVideoNote() *FileTypeVideoNote { + fileTypeVideoNoteTemp := FileTypeVideoNote{ + tdCommon: tdCommon{Type: "fileTypeVideoNote"}, + } + + return &fileTypeVideoNoteTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeVideoNote *FileTypeVideoNote) GetFileTypeEnum() FileTypeEnum { + return FileTypeVideoNoteType +} + +// FileTypeVoiceNote The file is a voice note +type FileTypeVoiceNote struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeVoiceNote +func (fileTypeVoiceNote *FileTypeVoiceNote) MessageType() string { + return "fileTypeVoiceNote" +} + +// NewFileTypeVoiceNote creates a new FileTypeVoiceNote +// +func NewFileTypeVoiceNote() *FileTypeVoiceNote { + fileTypeVoiceNoteTemp := FileTypeVoiceNote{ + tdCommon: tdCommon{Type: "fileTypeVoiceNote"}, + } + + return &fileTypeVoiceNoteTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeVoiceNote *FileTypeVoiceNote) GetFileTypeEnum() FileTypeEnum { + return FileTypeVoiceNoteType +} + +// FileTypeWallpaper The file is a wallpaper +type FileTypeWallpaper struct { + tdCommon +} + +// MessageType return the string telegram-type of FileTypeWallpaper +func (fileTypeWallpaper *FileTypeWallpaper) MessageType() string { + return "fileTypeWallpaper" +} + +// NewFileTypeWallpaper creates a new FileTypeWallpaper +// +func NewFileTypeWallpaper() *FileTypeWallpaper { + fileTypeWallpaperTemp := FileTypeWallpaper{ + tdCommon: tdCommon{Type: "fileTypeWallpaper"}, + } + + return &fileTypeWallpaperTemp +} + +// GetFileTypeEnum return the enum type of this object +func (fileTypeWallpaper *FileTypeWallpaper) GetFileTypeEnum() FileTypeEnum { + return FileTypeWallpaperType +} + +// StorageStatisticsByFileType Contains the storage usage statistics for a specific file type +type StorageStatisticsByFileType struct { + tdCommon + FileType FileType `json:"file_type"` // File type + Size int64 `json:"size"` // Total size of the files + Count int32 `json:"count"` // Total number of files +} + +// MessageType return the string telegram-type of StorageStatisticsByFileType +func (storageStatisticsByFileType *StorageStatisticsByFileType) MessageType() string { + return "storageStatisticsByFileType" +} + +// NewStorageStatisticsByFileType creates a new StorageStatisticsByFileType +// +// @param fileType File type +// @param size Total size of the files +// @param count Total number of files +func NewStorageStatisticsByFileType(fileType FileType, size int64, count int32) *StorageStatisticsByFileType { + storageStatisticsByFileTypeTemp := StorageStatisticsByFileType{ + tdCommon: tdCommon{Type: "storageStatisticsByFileType"}, + FileType: fileType, + Size: size, + Count: count, + } + + return &storageStatisticsByFileTypeTemp +} + +// UnmarshalJSON unmarshal to json +func (storageStatisticsByFileType *StorageStatisticsByFileType) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Size int64 `json:"size"` // Total size of the files + Count int32 `json:"count"` // Total number of files + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + storageStatisticsByFileType.tdCommon = tempObj.tdCommon + storageStatisticsByFileType.Size = tempObj.Size + storageStatisticsByFileType.Count = tempObj.Count + + fieldFileType, _ := unmarshalFileType(objMap["file_type"]) + storageStatisticsByFileType.FileType = fieldFileType + + return nil +} + +// StorageStatisticsByChat Contains the storage usage statistics for a specific chat +type StorageStatisticsByChat struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier; 0 if none + Size int64 `json:"size"` // Total size of the files in the chat + Count int32 `json:"count"` // Total number of files in the chat + ByFileType []StorageStatisticsByFileType `json:"by_file_type"` // Statistics split by file types +} + +// MessageType return the string telegram-type of StorageStatisticsByChat +func (storageStatisticsByChat *StorageStatisticsByChat) MessageType() string { + return "storageStatisticsByChat" +} + +// NewStorageStatisticsByChat creates a new StorageStatisticsByChat +// +// @param chatID Chat identifier; 0 if none +// @param size Total size of the files in the chat +// @param count Total number of files in the chat +// @param byFileType Statistics split by file types +func NewStorageStatisticsByChat(chatID int64, size int64, count int32, byFileType []StorageStatisticsByFileType) *StorageStatisticsByChat { + storageStatisticsByChatTemp := StorageStatisticsByChat{ + tdCommon: tdCommon{Type: "storageStatisticsByChat"}, + ChatID: chatID, + Size: size, + Count: count, + ByFileType: byFileType, + } + + return &storageStatisticsByChatTemp +} + +// StorageStatistics Contains the exact storage usage statistics split by chats and file type +type StorageStatistics struct { + tdCommon + Size int64 `json:"size"` // Total size of files + Count int32 `json:"count"` // Total number of files + ByChat []StorageStatisticsByChat `json:"by_chat"` // Statistics split by chats +} + +// MessageType return the string telegram-type of StorageStatistics +func (storageStatistics *StorageStatistics) MessageType() string { + return "storageStatistics" +} + +// NewStorageStatistics creates a new StorageStatistics +// +// @param size Total size of files +// @param count Total number of files +// @param byChat Statistics split by chats +func NewStorageStatistics(size int64, count int32, byChat []StorageStatisticsByChat) *StorageStatistics { + storageStatisticsTemp := StorageStatistics{ + tdCommon: tdCommon{Type: "storageStatistics"}, + Size: size, + Count: count, + ByChat: byChat, + } + + return &storageStatisticsTemp +} + +// StorageStatisticsFast Contains approximate storage usage statistics, excluding files of unknown file type +type StorageStatisticsFast struct { + tdCommon + FilesSize int64 `json:"files_size"` // Approximate total size of files + FileCount int32 `json:"file_count"` // Approximate number of files + DatabaseSize int64 `json:"database_size"` // Size of the database +} + +// MessageType return the string telegram-type of StorageStatisticsFast +func (storageStatisticsFast *StorageStatisticsFast) MessageType() string { + return "storageStatisticsFast" +} + +// NewStorageStatisticsFast creates a new StorageStatisticsFast +// +// @param filesSize Approximate total size of files +// @param fileCount Approximate number of files +// @param databaseSize Size of the database +func NewStorageStatisticsFast(filesSize int64, fileCount int32, databaseSize int64) *StorageStatisticsFast { + storageStatisticsFastTemp := StorageStatisticsFast{ + tdCommon: tdCommon{Type: "storageStatisticsFast"}, + FilesSize: filesSize, + FileCount: fileCount, + DatabaseSize: databaseSize, + } + + return &storageStatisticsFastTemp +} + +// NetworkTypeNone The network is not available +type NetworkTypeNone struct { + tdCommon +} + +// MessageType return the string telegram-type of NetworkTypeNone +func (networkTypeNone *NetworkTypeNone) MessageType() string { + return "networkTypeNone" +} + +// NewNetworkTypeNone creates a new NetworkTypeNone +// +func NewNetworkTypeNone() *NetworkTypeNone { + networkTypeNoneTemp := NetworkTypeNone{ + tdCommon: tdCommon{Type: "networkTypeNone"}, + } + + return &networkTypeNoneTemp +} + +// GetNetworkTypeEnum return the enum type of this object +func (networkTypeNone *NetworkTypeNone) GetNetworkTypeEnum() NetworkTypeEnum { + return NetworkTypeNoneType +} + +// NetworkTypeMobile A mobile network +type NetworkTypeMobile struct { + tdCommon +} + +// MessageType return the string telegram-type of NetworkTypeMobile +func (networkTypeMobile *NetworkTypeMobile) MessageType() string { + return "networkTypeMobile" +} + +// NewNetworkTypeMobile creates a new NetworkTypeMobile +// +func NewNetworkTypeMobile() *NetworkTypeMobile { + networkTypeMobileTemp := NetworkTypeMobile{ + tdCommon: tdCommon{Type: "networkTypeMobile"}, + } + + return &networkTypeMobileTemp +} + +// GetNetworkTypeEnum return the enum type of this object +func (networkTypeMobile *NetworkTypeMobile) GetNetworkTypeEnum() NetworkTypeEnum { + return NetworkTypeMobileType +} + +// NetworkTypeMobileRoaming A mobile roaming network +type NetworkTypeMobileRoaming struct { + tdCommon +} + +// MessageType return the string telegram-type of NetworkTypeMobileRoaming +func (networkTypeMobileRoaming *NetworkTypeMobileRoaming) MessageType() string { + return "networkTypeMobileRoaming" +} + +// NewNetworkTypeMobileRoaming creates a new NetworkTypeMobileRoaming +// +func NewNetworkTypeMobileRoaming() *NetworkTypeMobileRoaming { + networkTypeMobileRoamingTemp := NetworkTypeMobileRoaming{ + tdCommon: tdCommon{Type: "networkTypeMobileRoaming"}, + } + + return &networkTypeMobileRoamingTemp +} + +// GetNetworkTypeEnum return the enum type of this object +func (networkTypeMobileRoaming *NetworkTypeMobileRoaming) GetNetworkTypeEnum() NetworkTypeEnum { + return NetworkTypeMobileRoamingType +} + +// NetworkTypeWiFi A Wi-Fi network +type NetworkTypeWiFi struct { + tdCommon +} + +// MessageType return the string telegram-type of NetworkTypeWiFi +func (networkTypeWiFi *NetworkTypeWiFi) MessageType() string { + return "networkTypeWiFi" +} + +// NewNetworkTypeWiFi creates a new NetworkTypeWiFi +// +func NewNetworkTypeWiFi() *NetworkTypeWiFi { + networkTypeWiFiTemp := NetworkTypeWiFi{ + tdCommon: tdCommon{Type: "networkTypeWiFi"}, + } + + return &networkTypeWiFiTemp +} + +// GetNetworkTypeEnum return the enum type of this object +func (networkTypeWiFi *NetworkTypeWiFi) GetNetworkTypeEnum() NetworkTypeEnum { + return NetworkTypeWiFiType +} + +// NetworkTypeOther A different network type (e.g., Ethernet network) +type NetworkTypeOther struct { + tdCommon +} + +// MessageType return the string telegram-type of NetworkTypeOther +func (networkTypeOther *NetworkTypeOther) MessageType() string { + return "networkTypeOther" +} + +// NewNetworkTypeOther creates a new NetworkTypeOther +// +func NewNetworkTypeOther() *NetworkTypeOther { + networkTypeOtherTemp := NetworkTypeOther{ + tdCommon: tdCommon{Type: "networkTypeOther"}, + } + + return &networkTypeOtherTemp +} + +// GetNetworkTypeEnum return the enum type of this object +func (networkTypeOther *NetworkTypeOther) GetNetworkTypeEnum() NetworkTypeEnum { + return NetworkTypeOtherType +} + +// NetworkStatisticsEntryFile Contains information about the total amount of data that was used to send and receive files +type NetworkStatisticsEntryFile struct { + tdCommon + FileType FileType `json:"file_type"` // Type of the file the data is part of + NetworkType NetworkType `json:"network_type"` // Type of the network the data was sent through. Call setNetworkType to maintain the actual network type + SentBytes int64 `json:"sent_bytes"` // Total number of bytes sent + ReceivedBytes int64 `json:"received_bytes"` // Total number of bytes received +} + +// MessageType return the string telegram-type of NetworkStatisticsEntryFile +func (networkStatisticsEntryFile *NetworkStatisticsEntryFile) MessageType() string { + return "networkStatisticsEntryFile" +} + +// NewNetworkStatisticsEntryFile creates a new NetworkStatisticsEntryFile +// +// @param fileType Type of the file the data is part of +// @param networkType Type of the network the data was sent through. Call setNetworkType to maintain the actual network type +// @param sentBytes Total number of bytes sent +// @param receivedBytes Total number of bytes received +func NewNetworkStatisticsEntryFile(fileType FileType, networkType NetworkType, sentBytes int64, receivedBytes int64) *NetworkStatisticsEntryFile { + networkStatisticsEntryFileTemp := NetworkStatisticsEntryFile{ + tdCommon: tdCommon{Type: "networkStatisticsEntryFile"}, + FileType: fileType, + NetworkType: networkType, + SentBytes: sentBytes, + ReceivedBytes: receivedBytes, + } + + return &networkStatisticsEntryFileTemp +} + +// UnmarshalJSON unmarshal to json +func (networkStatisticsEntryFile *NetworkStatisticsEntryFile) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + SentBytes int64 `json:"sent_bytes"` // Total number of bytes sent + ReceivedBytes int64 `json:"received_bytes"` // Total number of bytes received + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + networkStatisticsEntryFile.tdCommon = tempObj.tdCommon + networkStatisticsEntryFile.SentBytes = tempObj.SentBytes + networkStatisticsEntryFile.ReceivedBytes = tempObj.ReceivedBytes + + fieldFileType, _ := unmarshalFileType(objMap["file_type"]) + networkStatisticsEntryFile.FileType = fieldFileType + + fieldNetworkType, _ := unmarshalNetworkType(objMap["network_type"]) + networkStatisticsEntryFile.NetworkType = fieldNetworkType + + return nil +} + +// GetNetworkStatisticsEntryEnum return the enum type of this object +func (networkStatisticsEntryFile *NetworkStatisticsEntryFile) GetNetworkStatisticsEntryEnum() NetworkStatisticsEntryEnum { + return NetworkStatisticsEntryFileType +} + +// NetworkStatisticsEntryCall Contains information about the total amount of data that was used for calls +type NetworkStatisticsEntryCall struct { + tdCommon + NetworkType NetworkType `json:"network_type"` // Type of the network the data was sent through. Call setNetworkType to maintain the actual network type + SentBytes int64 `json:"sent_bytes"` // Total number of bytes sent + ReceivedBytes int64 `json:"received_bytes"` // Total number of bytes received + Duration float64 `json:"duration"` // Total call duration, in seconds +} + +// MessageType return the string telegram-type of NetworkStatisticsEntryCall +func (networkStatisticsEntryCall *NetworkStatisticsEntryCall) MessageType() string { + return "networkStatisticsEntryCall" +} + +// NewNetworkStatisticsEntryCall creates a new NetworkStatisticsEntryCall +// +// @param networkType Type of the network the data was sent through. Call setNetworkType to maintain the actual network type +// @param sentBytes Total number of bytes sent +// @param receivedBytes Total number of bytes received +// @param duration Total call duration, in seconds +func NewNetworkStatisticsEntryCall(networkType NetworkType, sentBytes int64, receivedBytes int64, duration float64) *NetworkStatisticsEntryCall { + networkStatisticsEntryCallTemp := NetworkStatisticsEntryCall{ + tdCommon: tdCommon{Type: "networkStatisticsEntryCall"}, + NetworkType: networkType, + SentBytes: sentBytes, + ReceivedBytes: receivedBytes, + Duration: duration, + } + + return &networkStatisticsEntryCallTemp +} + +// UnmarshalJSON unmarshal to json +func (networkStatisticsEntryCall *NetworkStatisticsEntryCall) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + SentBytes int64 `json:"sent_bytes"` // Total number of bytes sent + ReceivedBytes int64 `json:"received_bytes"` // Total number of bytes received + Duration float64 `json:"duration"` // Total call duration, in seconds + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + networkStatisticsEntryCall.tdCommon = tempObj.tdCommon + networkStatisticsEntryCall.SentBytes = tempObj.SentBytes + networkStatisticsEntryCall.ReceivedBytes = tempObj.ReceivedBytes + networkStatisticsEntryCall.Duration = tempObj.Duration + + fieldNetworkType, _ := unmarshalNetworkType(objMap["network_type"]) + networkStatisticsEntryCall.NetworkType = fieldNetworkType + + return nil +} + +// GetNetworkStatisticsEntryEnum return the enum type of this object +func (networkStatisticsEntryCall *NetworkStatisticsEntryCall) GetNetworkStatisticsEntryEnum() NetworkStatisticsEntryEnum { + return NetworkStatisticsEntryCallType +} + +// NetworkStatistics A full list of available network statistic entries +type NetworkStatistics struct { + tdCommon + SinceDate int32 `json:"since_date"` // Point in time (Unix timestamp) when the app began collecting statistics + Entries []NetworkStatisticsEntry `json:"entries"` // Network statistics entries +} + +// MessageType return the string telegram-type of NetworkStatistics +func (networkStatistics *NetworkStatistics) MessageType() string { + return "networkStatistics" +} + +// NewNetworkStatistics creates a new NetworkStatistics +// +// @param sinceDate Point in time (Unix timestamp) when the app began collecting statistics +// @param entries Network statistics entries +func NewNetworkStatistics(sinceDate int32, entries []NetworkStatisticsEntry) *NetworkStatistics { + networkStatisticsTemp := NetworkStatistics{ + tdCommon: tdCommon{Type: "networkStatistics"}, + SinceDate: sinceDate, + Entries: entries, + } + + return &networkStatisticsTemp +} + +// ConnectionStateWaitingForNetwork Currently waiting for the network to become available. Use SetNetworkType to change the available network type +type ConnectionStateWaitingForNetwork struct { + tdCommon +} + +// MessageType return the string telegram-type of ConnectionStateWaitingForNetwork +func (connectionStateWaitingForNetwork *ConnectionStateWaitingForNetwork) MessageType() string { + return "connectionStateWaitingForNetwork" +} + +// NewConnectionStateWaitingForNetwork creates a new ConnectionStateWaitingForNetwork +// +func NewConnectionStateWaitingForNetwork() *ConnectionStateWaitingForNetwork { + connectionStateWaitingForNetworkTemp := ConnectionStateWaitingForNetwork{ + tdCommon: tdCommon{Type: "connectionStateWaitingForNetwork"}, + } + + return &connectionStateWaitingForNetworkTemp +} + +// GetConnectionStateEnum return the enum type of this object +func (connectionStateWaitingForNetwork *ConnectionStateWaitingForNetwork) GetConnectionStateEnum() ConnectionStateEnum { + return ConnectionStateWaitingForNetworkType +} + +// ConnectionStateConnectingToProxy Currently establishing a connection with a proxy server +type ConnectionStateConnectingToProxy struct { + tdCommon +} + +// MessageType return the string telegram-type of ConnectionStateConnectingToProxy +func (connectionStateConnectingToProxy *ConnectionStateConnectingToProxy) MessageType() string { + return "connectionStateConnectingToProxy" +} + +// NewConnectionStateConnectingToProxy creates a new ConnectionStateConnectingToProxy +// +func NewConnectionStateConnectingToProxy() *ConnectionStateConnectingToProxy { + connectionStateConnectingToProxyTemp := ConnectionStateConnectingToProxy{ + tdCommon: tdCommon{Type: "connectionStateConnectingToProxy"}, + } + + return &connectionStateConnectingToProxyTemp +} + +// GetConnectionStateEnum return the enum type of this object +func (connectionStateConnectingToProxy *ConnectionStateConnectingToProxy) GetConnectionStateEnum() ConnectionStateEnum { + return ConnectionStateConnectingToProxyType +} + +// ConnectionStateConnecting Currently establishing a connection to the Telegram servers +type ConnectionStateConnecting struct { + tdCommon +} + +// MessageType return the string telegram-type of ConnectionStateConnecting +func (connectionStateConnecting *ConnectionStateConnecting) MessageType() string { + return "connectionStateConnecting" +} + +// NewConnectionStateConnecting creates a new ConnectionStateConnecting +// +func NewConnectionStateConnecting() *ConnectionStateConnecting { + connectionStateConnectingTemp := ConnectionStateConnecting{ + tdCommon: tdCommon{Type: "connectionStateConnecting"}, + } + + return &connectionStateConnectingTemp +} + +// GetConnectionStateEnum return the enum type of this object +func (connectionStateConnecting *ConnectionStateConnecting) GetConnectionStateEnum() ConnectionStateEnum { + return ConnectionStateConnectingType +} + +// ConnectionStateUpdating Downloading data received while the client was offline +type ConnectionStateUpdating struct { + tdCommon +} + +// MessageType return the string telegram-type of ConnectionStateUpdating +func (connectionStateUpdating *ConnectionStateUpdating) MessageType() string { + return "connectionStateUpdating" +} + +// NewConnectionStateUpdating creates a new ConnectionStateUpdating +// +func NewConnectionStateUpdating() *ConnectionStateUpdating { + connectionStateUpdatingTemp := ConnectionStateUpdating{ + tdCommon: tdCommon{Type: "connectionStateUpdating"}, + } + + return &connectionStateUpdatingTemp +} + +// GetConnectionStateEnum return the enum type of this object +func (connectionStateUpdating *ConnectionStateUpdating) GetConnectionStateEnum() ConnectionStateEnum { + return ConnectionStateUpdatingType +} + +// ConnectionStateReady There is a working connection to the Telegram servers +type ConnectionStateReady struct { + tdCommon +} + +// MessageType return the string telegram-type of ConnectionStateReady +func (connectionStateReady *ConnectionStateReady) MessageType() string { + return "connectionStateReady" +} + +// NewConnectionStateReady creates a new ConnectionStateReady +// +func NewConnectionStateReady() *ConnectionStateReady { + connectionStateReadyTemp := ConnectionStateReady{ + tdCommon: tdCommon{Type: "connectionStateReady"}, + } + + return &connectionStateReadyTemp +} + +// GetConnectionStateEnum return the enum type of this object +func (connectionStateReady *ConnectionStateReady) GetConnectionStateEnum() ConnectionStateEnum { + return ConnectionStateReadyType +} + +// TopChatCategoryUsers A category containing frequently used private chats with non-bot users +type TopChatCategoryUsers struct { + tdCommon +} + +// MessageType return the string telegram-type of TopChatCategoryUsers +func (topChatCategoryUsers *TopChatCategoryUsers) MessageType() string { + return "topChatCategoryUsers" +} + +// NewTopChatCategoryUsers creates a new TopChatCategoryUsers +// +func NewTopChatCategoryUsers() *TopChatCategoryUsers { + topChatCategoryUsersTemp := TopChatCategoryUsers{ + tdCommon: tdCommon{Type: "topChatCategoryUsers"}, + } + + return &topChatCategoryUsersTemp +} + +// GetTopChatCategoryEnum return the enum type of this object +func (topChatCategoryUsers *TopChatCategoryUsers) GetTopChatCategoryEnum() TopChatCategoryEnum { + return TopChatCategoryUsersType +} + +// TopChatCategoryBots A category containing frequently used private chats with bot users +type TopChatCategoryBots struct { + tdCommon +} + +// MessageType return the string telegram-type of TopChatCategoryBots +func (topChatCategoryBots *TopChatCategoryBots) MessageType() string { + return "topChatCategoryBots" +} + +// NewTopChatCategoryBots creates a new TopChatCategoryBots +// +func NewTopChatCategoryBots() *TopChatCategoryBots { + topChatCategoryBotsTemp := TopChatCategoryBots{ + tdCommon: tdCommon{Type: "topChatCategoryBots"}, + } + + return &topChatCategoryBotsTemp +} + +// GetTopChatCategoryEnum return the enum type of this object +func (topChatCategoryBots *TopChatCategoryBots) GetTopChatCategoryEnum() TopChatCategoryEnum { + return TopChatCategoryBotsType +} + +// TopChatCategoryGroups A category containing frequently used basic groups and supergroups +type TopChatCategoryGroups struct { + tdCommon +} + +// MessageType return the string telegram-type of TopChatCategoryGroups +func (topChatCategoryGroups *TopChatCategoryGroups) MessageType() string { + return "topChatCategoryGroups" +} + +// NewTopChatCategoryGroups creates a new TopChatCategoryGroups +// +func NewTopChatCategoryGroups() *TopChatCategoryGroups { + topChatCategoryGroupsTemp := TopChatCategoryGroups{ + tdCommon: tdCommon{Type: "topChatCategoryGroups"}, + } + + return &topChatCategoryGroupsTemp +} + +// GetTopChatCategoryEnum return the enum type of this object +func (topChatCategoryGroups *TopChatCategoryGroups) GetTopChatCategoryEnum() TopChatCategoryEnum { + return TopChatCategoryGroupsType +} + +// TopChatCategoryChannels A category containing frequently used channels +type TopChatCategoryChannels struct { + tdCommon +} + +// MessageType return the string telegram-type of TopChatCategoryChannels +func (topChatCategoryChannels *TopChatCategoryChannels) MessageType() string { + return "topChatCategoryChannels" +} + +// NewTopChatCategoryChannels creates a new TopChatCategoryChannels +// +func NewTopChatCategoryChannels() *TopChatCategoryChannels { + topChatCategoryChannelsTemp := TopChatCategoryChannels{ + tdCommon: tdCommon{Type: "topChatCategoryChannels"}, + } + + return &topChatCategoryChannelsTemp +} + +// GetTopChatCategoryEnum return the enum type of this object +func (topChatCategoryChannels *TopChatCategoryChannels) GetTopChatCategoryEnum() TopChatCategoryEnum { + return TopChatCategoryChannelsType +} + +// TopChatCategoryInlineBots A category containing frequently used chats with inline bots sorted by their usage in inline mode +type TopChatCategoryInlineBots struct { + tdCommon +} + +// MessageType return the string telegram-type of TopChatCategoryInlineBots +func (topChatCategoryInlineBots *TopChatCategoryInlineBots) MessageType() string { + return "topChatCategoryInlineBots" +} + +// NewTopChatCategoryInlineBots creates a new TopChatCategoryInlineBots +// +func NewTopChatCategoryInlineBots() *TopChatCategoryInlineBots { + topChatCategoryInlineBotsTemp := TopChatCategoryInlineBots{ + tdCommon: tdCommon{Type: "topChatCategoryInlineBots"}, + } + + return &topChatCategoryInlineBotsTemp +} + +// GetTopChatCategoryEnum return the enum type of this object +func (topChatCategoryInlineBots *TopChatCategoryInlineBots) GetTopChatCategoryEnum() TopChatCategoryEnum { + return TopChatCategoryInlineBotsType +} + +// TopChatCategoryCalls A category containing frequently used chats used for calls +type TopChatCategoryCalls struct { + tdCommon +} + +// MessageType return the string telegram-type of TopChatCategoryCalls +func (topChatCategoryCalls *TopChatCategoryCalls) MessageType() string { + return "topChatCategoryCalls" +} + +// NewTopChatCategoryCalls creates a new TopChatCategoryCalls +// +func NewTopChatCategoryCalls() *TopChatCategoryCalls { + topChatCategoryCallsTemp := TopChatCategoryCalls{ + tdCommon: tdCommon{Type: "topChatCategoryCalls"}, + } + + return &topChatCategoryCallsTemp +} + +// GetTopChatCategoryEnum return the enum type of this object +func (topChatCategoryCalls *TopChatCategoryCalls) GetTopChatCategoryEnum() TopChatCategoryEnum { + return TopChatCategoryCallsType +} + +// TMeURLTypeUser A URL linking to a user +type TMeURLTypeUser struct { + tdCommon + UserID int32 `json:"user_id"` // Identifier of the user +} + +// MessageType return the string telegram-type of TMeURLTypeUser +func (tMeURLTypeUser *TMeURLTypeUser) MessageType() string { + return "tMeUrlTypeUser" +} + +// NewTMeURLTypeUser creates a new TMeURLTypeUser +// +// @param userID Identifier of the user +func NewTMeURLTypeUser(userID int32) *TMeURLTypeUser { + tMeURLTypeUserTemp := TMeURLTypeUser{ + tdCommon: tdCommon{Type: "tMeUrlTypeUser"}, + UserID: userID, + } + + return &tMeURLTypeUserTemp +} + +// GetTMeURLTypeEnum return the enum type of this object +func (tMeURLTypeUser *TMeURLTypeUser) GetTMeURLTypeEnum() TMeURLTypeEnum { + return TMeURLTypeUserType +} + +// TMeURLTypeSupergroup A URL linking to a public supergroup or channel +type TMeURLTypeSupergroup struct { + tdCommon + SupergroupID int64 `json:"supergroup_id"` // Identifier of the supergroup or channel +} + +// MessageType return the string telegram-type of TMeURLTypeSupergroup +func (tMeURLTypeSupergroup *TMeURLTypeSupergroup) MessageType() string { + return "tMeUrlTypeSupergroup" +} + +// NewTMeURLTypeSupergroup creates a new TMeURLTypeSupergroup +// +// @param supergroupID Identifier of the supergroup or channel +func NewTMeURLTypeSupergroup(supergroupID int64) *TMeURLTypeSupergroup { + tMeURLTypeSupergroupTemp := TMeURLTypeSupergroup{ + tdCommon: tdCommon{Type: "tMeUrlTypeSupergroup"}, + SupergroupID: supergroupID, + } + + return &tMeURLTypeSupergroupTemp +} + +// GetTMeURLTypeEnum return the enum type of this object +func (tMeURLTypeSupergroup *TMeURLTypeSupergroup) GetTMeURLTypeEnum() TMeURLTypeEnum { + return TMeURLTypeSupergroupType +} + +// TMeURLTypeChatInvite A chat invite link +type TMeURLTypeChatInvite struct { + tdCommon + Info *ChatInviteLinkInfo `json:"info"` // Chat invite link info +} + +// MessageType return the string telegram-type of TMeURLTypeChatInvite +func (tMeURLTypeChatInvite *TMeURLTypeChatInvite) MessageType() string { + return "tMeUrlTypeChatInvite" +} + +// NewTMeURLTypeChatInvite creates a new TMeURLTypeChatInvite +// +// @param info Chat invite link info +func NewTMeURLTypeChatInvite(info *ChatInviteLinkInfo) *TMeURLTypeChatInvite { + tMeURLTypeChatInviteTemp := TMeURLTypeChatInvite{ + tdCommon: tdCommon{Type: "tMeUrlTypeChatInvite"}, + Info: info, + } + + return &tMeURLTypeChatInviteTemp +} + +// GetTMeURLTypeEnum return the enum type of this object +func (tMeURLTypeChatInvite *TMeURLTypeChatInvite) GetTMeURLTypeEnum() TMeURLTypeEnum { + return TMeURLTypeChatInviteType +} + +// TMeURLTypeStickerSet A URL linking to a sticker set +type TMeURLTypeStickerSet struct { + tdCommon + StickerSetID JSONInt64 `json:"sticker_set_id"` // Identifier of the sticker set +} + +// MessageType return the string telegram-type of TMeURLTypeStickerSet +func (tMeURLTypeStickerSet *TMeURLTypeStickerSet) MessageType() string { + return "tMeUrlTypeStickerSet" +} + +// NewTMeURLTypeStickerSet creates a new TMeURLTypeStickerSet +// +// @param stickerSetID Identifier of the sticker set +func NewTMeURLTypeStickerSet(stickerSetID JSONInt64) *TMeURLTypeStickerSet { + tMeURLTypeStickerSetTemp := TMeURLTypeStickerSet{ + tdCommon: tdCommon{Type: "tMeUrlTypeStickerSet"}, + StickerSetID: stickerSetID, + } + + return &tMeURLTypeStickerSetTemp +} + +// GetTMeURLTypeEnum return the enum type of this object +func (tMeURLTypeStickerSet *TMeURLTypeStickerSet) GetTMeURLTypeEnum() TMeURLTypeEnum { + return TMeURLTypeStickerSetType +} + +// TMeURL Represents a URL linking to an internal Telegram entity +type TMeURL struct { + tdCommon + URL string `json:"url"` // URL + Type TMeURLType `json:"type"` // Type of the URL +} + +// MessageType return the string telegram-type of TMeURL +func (tMeURL *TMeURL) MessageType() string { + return "tMeUrl" +} + +// NewTMeURL creates a new TMeURL +// +// @param uRL URL +// @param typeParam Type of the URL +func NewTMeURL(uRL string, typeParam TMeURLType) *TMeURL { + tMeURLTemp := TMeURL{ + tdCommon: tdCommon{Type: "tMeUrl"}, + URL: uRL, + Type: typeParam, + } + + return &tMeURLTemp +} + +// UnmarshalJSON unmarshal to json +func (tMeURL *TMeURL) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + URL string `json:"url"` // URL + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + tMeURL.tdCommon = tempObj.tdCommon + tMeURL.URL = tempObj.URL + + fieldType, _ := unmarshalTMeURLType(objMap["type"]) + tMeURL.Type = fieldType + + return nil +} + +// TMeURLs Contains a list of t.me URLs +type TMeURLs struct { + tdCommon + URLs []TMeURL `json:"urls"` // List of URLs +} + +// MessageType return the string telegram-type of TMeURLs +func (tMeURLs *TMeURLs) MessageType() string { + return "tMeUrls" +} + +// NewTMeURLs creates a new TMeURLs +// +// @param uRLs List of URLs +func NewTMeURLs(uRLs []TMeURL) *TMeURLs { + tMeURLsTemp := TMeURLs{ + tdCommon: tdCommon{Type: "tMeUrls"}, + URLs: uRLs, + } + + return &tMeURLsTemp +} + +// Count Contains a counter +type Count struct { + tdCommon + Count int32 `json:"count"` // Count +} + +// MessageType return the string telegram-type of Count +func (count *Count) MessageType() string { + return "count" +} + +// NewCount creates a new Count +// +// @param count Count +func NewCount(count int32) *Count { + countTemp := Count{ + tdCommon: tdCommon{Type: "count"}, + Count: count, + } + + return &countTemp +} + +// Text Contains some text +type Text struct { + tdCommon + Text string `json:"text"` // Text +} + +// MessageType return the string telegram-type of Text +func (text *Text) MessageType() string { + return "text" +} + +// NewText creates a new Text +// +// @param text Text +func NewText(text string) *Text { + textTemp := Text{ + tdCommon: tdCommon{Type: "text"}, + Text: text, + } + + return &textTemp +} + +// Seconds Contains a value representing a number of seconds +type Seconds struct { + tdCommon + Seconds float64 `json:"seconds"` // Number of seconds +} + +// MessageType return the string telegram-type of Seconds +func (seconds *Seconds) MessageType() string { + return "seconds" +} + +// NewSeconds creates a new Seconds +// +// @param seconds Number of seconds +func NewSeconds(seconds float64) *Seconds { + secondsTemp := Seconds{ + tdCommon: tdCommon{Type: "seconds"}, + Seconds: seconds, + } + + return &secondsTemp +} + +// DeepLinkInfo Contains information about a tg:// deep link +type DeepLinkInfo struct { + tdCommon + Text *FormattedText `json:"text"` // Text to be shown to the user + NeedUpdateApplication bool `json:"need_update_application"` // True, if user should be asked to update the application +} + +// MessageType return the string telegram-type of DeepLinkInfo +func (deepLinkInfo *DeepLinkInfo) MessageType() string { + return "deepLinkInfo" +} + +// NewDeepLinkInfo creates a new DeepLinkInfo +// +// @param text Text to be shown to the user +// @param needUpdateApplication True, if user should be asked to update the application +func NewDeepLinkInfo(text *FormattedText, needUpdateApplication bool) *DeepLinkInfo { + deepLinkInfoTemp := DeepLinkInfo{ + tdCommon: tdCommon{Type: "deepLinkInfo"}, + Text: text, + NeedUpdateApplication: needUpdateApplication, + } + + return &deepLinkInfoTemp +} + +// TextParseModeMarkdown The text should be parsed in markdown-style +type TextParseModeMarkdown struct { + tdCommon +} + +// MessageType return the string telegram-type of TextParseModeMarkdown +func (textParseModeMarkdown *TextParseModeMarkdown) MessageType() string { + return "textParseModeMarkdown" +} + +// NewTextParseModeMarkdown creates a new TextParseModeMarkdown +// +func NewTextParseModeMarkdown() *TextParseModeMarkdown { + textParseModeMarkdownTemp := TextParseModeMarkdown{ + tdCommon: tdCommon{Type: "textParseModeMarkdown"}, + } + + return &textParseModeMarkdownTemp +} + +// GetTextParseModeEnum return the enum type of this object +func (textParseModeMarkdown *TextParseModeMarkdown) GetTextParseModeEnum() TextParseModeEnum { + return TextParseModeMarkdownType +} + +// TextParseModeHTML The text should be parsed in HTML-style +type TextParseModeHTML struct { + tdCommon +} + +// MessageType return the string telegram-type of TextParseModeHTML +func (textParseModeHTML *TextParseModeHTML) MessageType() string { + return "textParseModeHTML" +} + +// NewTextParseModeHTML creates a new TextParseModeHTML +// +func NewTextParseModeHTML() *TextParseModeHTML { + textParseModeHTMLTemp := TextParseModeHTML{ + tdCommon: tdCommon{Type: "textParseModeHTML"}, + } + + return &textParseModeHTMLTemp +} + +// GetTextParseModeEnum return the enum type of this object +func (textParseModeHTML *TextParseModeHTML) GetTextParseModeEnum() TextParseModeEnum { + return TextParseModeHTMLType +} + +// ProxyTypeSocks5 A SOCKS5 proxy server +type ProxyTypeSocks5 struct { + tdCommon + Username string `json:"username"` // Username for logging in; may be empty + Password string `json:"password"` // Password for logging in; may be empty +} + +// MessageType return the string telegram-type of ProxyTypeSocks5 +func (proxyTypeSocks5 *ProxyTypeSocks5) MessageType() string { + return "proxyTypeSocks5" +} + +// NewProxyTypeSocks5 creates a new ProxyTypeSocks5 +// +// @param username Username for logging in; may be empty +// @param password Password for logging in; may be empty +func NewProxyTypeSocks5(username string, password string) *ProxyTypeSocks5 { + proxyTypeSocks5Temp := ProxyTypeSocks5{ + tdCommon: tdCommon{Type: "proxyTypeSocks5"}, + Username: username, + Password: password, + } + + return &proxyTypeSocks5Temp +} + +// GetProxyTypeEnum return the enum type of this object +func (proxyTypeSocks5 *ProxyTypeSocks5) GetProxyTypeEnum() ProxyTypeEnum { + return ProxyTypeSocks5Type +} + +// ProxyTypeHttp A HTTP transparent proxy server +type ProxyTypeHttp struct { + tdCommon + Username string `json:"username"` // Username for logging in; may be empty + Password string `json:"password"` // Password for logging in; may be empty + HttpOnly bool `json:"http_only"` // Pass true, if the proxy supports only HTTP requests and doesn't support transparent TCP connections via HTTP CONNECT method +} + +// MessageType return the string telegram-type of ProxyTypeHttp +func (proxyTypeHttp *ProxyTypeHttp) MessageType() string { + return "proxyTypeHttp" +} + +// NewProxyTypeHttp creates a new ProxyTypeHttp +// +// @param username Username for logging in; may be empty +// @param password Password for logging in; may be empty +// @param httpOnly Pass true, if the proxy supports only HTTP requests and doesn't support transparent TCP connections via HTTP CONNECT method +func NewProxyTypeHttp(username string, password string, httpOnly bool) *ProxyTypeHttp { + proxyTypeHttpTemp := ProxyTypeHttp{ + tdCommon: tdCommon{Type: "proxyTypeHttp"}, + Username: username, + Password: password, + HttpOnly: httpOnly, + } + + return &proxyTypeHttpTemp +} + +// GetProxyTypeEnum return the enum type of this object +func (proxyTypeHttp *ProxyTypeHttp) GetProxyTypeEnum() ProxyTypeEnum { + return ProxyTypeHttpType +} + +// ProxyTypeMtproto An MTProto proxy server +type ProxyTypeMtproto struct { + tdCommon + Secret string `json:"secret"` // The proxy's secret in hexadecimal encoding +} + +// MessageType return the string telegram-type of ProxyTypeMtproto +func (proxyTypeMtproto *ProxyTypeMtproto) MessageType() string { + return "proxyTypeMtproto" +} + +// NewProxyTypeMtproto creates a new ProxyTypeMtproto +// +// @param secret The proxy's secret in hexadecimal encoding +func NewProxyTypeMtproto(secret string) *ProxyTypeMtproto { + proxyTypeMtprotoTemp := ProxyTypeMtproto{ + tdCommon: tdCommon{Type: "proxyTypeMtproto"}, + Secret: secret, + } + + return &proxyTypeMtprotoTemp +} + +// GetProxyTypeEnum return the enum type of this object +func (proxyTypeMtproto *ProxyTypeMtproto) GetProxyTypeEnum() ProxyTypeEnum { + return ProxyTypeMtprotoType +} + +// Proxy Contains information about a proxy server +type Proxy struct { + tdCommon + ID int32 `json:"id"` // Unique identifier of the proxy + Server string `json:"server"` // Proxy server IP address + Port int32 `json:"port"` // Proxy server port + LastUsedDate int32 `json:"last_used_date"` // Point in time (Unix timestamp) when the proxy was last used; 0 if never + IsEnabled bool `json:"is_enabled"` // True, if the proxy is enabled now + Type ProxyType `json:"type"` // Type of the proxy +} + +// MessageType return the string telegram-type of Proxy +func (proxy *Proxy) MessageType() string { + return "proxy" +} + +// NewProxy creates a new Proxy +// +// @param iD Unique identifier of the proxy +// @param server Proxy server IP address +// @param port Proxy server port +// @param lastUsedDate Point in time (Unix timestamp) when the proxy was last used; 0 if never +// @param isEnabled True, if the proxy is enabled now +// @param typeParam Type of the proxy +func NewProxy(iD int32, server string, port int32, lastUsedDate int32, isEnabled bool, typeParam ProxyType) *Proxy { + proxyTemp := Proxy{ + tdCommon: tdCommon{Type: "proxy"}, + ID: iD, + Server: server, + Port: port, + LastUsedDate: lastUsedDate, + IsEnabled: isEnabled, + Type: typeParam, + } + + return &proxyTemp +} + +// UnmarshalJSON unmarshal to json +func (proxy *Proxy) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID int32 `json:"id"` // Unique identifier of the proxy + Server string `json:"server"` // Proxy server IP address + Port int32 `json:"port"` // Proxy server port + LastUsedDate int32 `json:"last_used_date"` // Point in time (Unix timestamp) when the proxy was last used; 0 if never + IsEnabled bool `json:"is_enabled"` // True, if the proxy is enabled now + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + proxy.tdCommon = tempObj.tdCommon + proxy.ID = tempObj.ID + proxy.Server = tempObj.Server + proxy.Port = tempObj.Port + proxy.LastUsedDate = tempObj.LastUsedDate + proxy.IsEnabled = tempObj.IsEnabled + + fieldType, _ := unmarshalProxyType(objMap["type"]) + proxy.Type = fieldType + + return nil +} + +// Proxies Represents a list of proxy servers +type Proxies struct { + tdCommon + Proxies []Proxy `json:"proxies"` // List of proxy servers +} + +// MessageType return the string telegram-type of Proxies +func (proxies *Proxies) MessageType() string { + return "proxies" +} + +// NewProxies creates a new Proxies +// +// @param proxies List of proxy servers +func NewProxies(proxies []Proxy) *Proxies { + proxiesTemp := Proxies{ + tdCommon: tdCommon{Type: "proxies"}, + Proxies: proxies, + } + + return &proxiesTemp +} + +// InputSticker Describes a sticker that should be added to a sticker set +type InputSticker struct { + tdCommon + PngSticker InputFile `json:"png_sticker"` // PNG image with the sticker; must be up to 512 kB in size and fit in a 512x512 square + Emojis string `json:"emojis"` // Emoji corresponding to the sticker + MaskPosition *MaskPosition `json:"mask_position"` // For masks, position where the mask should be placed; may be null +} + +// MessageType return the string telegram-type of InputSticker +func (inputSticker *InputSticker) MessageType() string { + return "inputSticker" +} + +// NewInputSticker creates a new InputSticker +// +// @param pngSticker PNG image with the sticker; must be up to 512 kB in size and fit in a 512x512 square +// @param emojis Emoji corresponding to the sticker +// @param maskPosition For masks, position where the mask should be placed; may be null +func NewInputSticker(pngSticker InputFile, emojis string, maskPosition *MaskPosition) *InputSticker { + inputStickerTemp := InputSticker{ + tdCommon: tdCommon{Type: "inputSticker"}, + PngSticker: pngSticker, + Emojis: emojis, + MaskPosition: maskPosition, + } + + return &inputStickerTemp +} + +// UnmarshalJSON unmarshal to json +func (inputSticker *InputSticker) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Emojis string `json:"emojis"` // Emoji corresponding to the sticker + MaskPosition *MaskPosition `json:"mask_position"` // For masks, position where the mask should be placed; may be null + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputSticker.tdCommon = tempObj.tdCommon + inputSticker.Emojis = tempObj.Emojis + inputSticker.MaskPosition = tempObj.MaskPosition + + fieldPngSticker, _ := unmarshalInputFile(objMap["png_sticker"]) + inputSticker.PngSticker = fieldPngSticker + + return nil +} + +// UpdateAuthorizationState The user authorization state has changed +type UpdateAuthorizationState struct { + tdCommon + AuthorizationState AuthorizationState `json:"authorization_state"` // New authorization state +} + +// MessageType return the string telegram-type of UpdateAuthorizationState +func (updateAuthorizationState *UpdateAuthorizationState) MessageType() string { + return "updateAuthorizationState" +} + +// NewUpdateAuthorizationState creates a new UpdateAuthorizationState +// +// @param authorizationState New authorization state +func NewUpdateAuthorizationState(authorizationState AuthorizationState) *UpdateAuthorizationState { + updateAuthorizationStateTemp := UpdateAuthorizationState{ + tdCommon: tdCommon{Type: "updateAuthorizationState"}, + AuthorizationState: authorizationState, + } + + return &updateAuthorizationStateTemp +} + +// UnmarshalJSON unmarshal to json +func (updateAuthorizationState *UpdateAuthorizationState) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateAuthorizationState.tdCommon = tempObj.tdCommon + + fieldAuthorizationState, _ := unmarshalAuthorizationState(objMap["authorization_state"]) + updateAuthorizationState.AuthorizationState = fieldAuthorizationState + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateAuthorizationState *UpdateAuthorizationState) GetUpdateEnum() UpdateEnum { + return UpdateAuthorizationStateType +} + +// UpdateNewMessage A new message was received; can also be an outgoing message +type UpdateNewMessage struct { + tdCommon + Message *Message `json:"message"` // The new message + DisableNotification bool `json:"disable_notification"` // True, if this message must not generate a notification + ContainsMention bool `json:"contains_mention"` // True, if the message contains a mention of the current user +} + +// MessageType return the string telegram-type of UpdateNewMessage +func (updateNewMessage *UpdateNewMessage) MessageType() string { + return "updateNewMessage" +} + +// NewUpdateNewMessage creates a new UpdateNewMessage +// +// @param message The new message +// @param disableNotification True, if this message must not generate a notification +// @param containsMention True, if the message contains a mention of the current user +func NewUpdateNewMessage(message *Message, disableNotification bool, containsMention bool) *UpdateNewMessage { + updateNewMessageTemp := UpdateNewMessage{ + tdCommon: tdCommon{Type: "updateNewMessage"}, + Message: message, + DisableNotification: disableNotification, + ContainsMention: containsMention, + } + + return &updateNewMessageTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewMessage *UpdateNewMessage) GetUpdateEnum() UpdateEnum { + return UpdateNewMessageType +} + +// UpdateMessageSendAcknowledged A request to send a message has reached the Telegram server. This doesn't mean that the message will be sent successfully or even that the send message request will be processed. This update will be sent only if the option "use_quick_ack" is set to true. This update may be sent multiple times for the same message +type UpdateMessageSendAcknowledged struct { + tdCommon + ChatID int64 `json:"chat_id"` // The chat identifier of the sent message + MessageID int64 `json:"message_id"` // A temporary message identifier +} + +// MessageType return the string telegram-type of UpdateMessageSendAcknowledged +func (updateMessageSendAcknowledged *UpdateMessageSendAcknowledged) MessageType() string { + return "updateMessageSendAcknowledged" +} + +// NewUpdateMessageSendAcknowledged creates a new UpdateMessageSendAcknowledged +// +// @param chatID The chat identifier of the sent message +// @param messageID A temporary message identifier +func NewUpdateMessageSendAcknowledged(chatID int64, messageID int64) *UpdateMessageSendAcknowledged { + updateMessageSendAcknowledgedTemp := UpdateMessageSendAcknowledged{ + tdCommon: tdCommon{Type: "updateMessageSendAcknowledged"}, + ChatID: chatID, + MessageID: messageID, + } + + return &updateMessageSendAcknowledgedTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageSendAcknowledged *UpdateMessageSendAcknowledged) GetUpdateEnum() UpdateEnum { + return UpdateMessageSendAcknowledgedType +} + +// UpdateMessageSendSucceeded A message has been successfully sent +type UpdateMessageSendSucceeded struct { + tdCommon + Message *Message `json:"message"` // Information about the sent message. Usually only the message identifier, date, and content are changed, but almost all other fields can also change + OldMessageID int64 `json:"old_message_id"` // The previous temporary message identifier +} + +// MessageType return the string telegram-type of UpdateMessageSendSucceeded +func (updateMessageSendSucceeded *UpdateMessageSendSucceeded) MessageType() string { + return "updateMessageSendSucceeded" +} + +// NewUpdateMessageSendSucceeded creates a new UpdateMessageSendSucceeded +// +// @param message Information about the sent message. Usually only the message identifier, date, and content are changed, but almost all other fields can also change +// @param oldMessageID The previous temporary message identifier +func NewUpdateMessageSendSucceeded(message *Message, oldMessageID int64) *UpdateMessageSendSucceeded { + updateMessageSendSucceededTemp := UpdateMessageSendSucceeded{ + tdCommon: tdCommon{Type: "updateMessageSendSucceeded"}, + Message: message, + OldMessageID: oldMessageID, + } + + return &updateMessageSendSucceededTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageSendSucceeded *UpdateMessageSendSucceeded) GetUpdateEnum() UpdateEnum { + return UpdateMessageSendSucceededType +} + +// UpdateMessageSendFailed A message failed to send. Be aware that some messages being sent can be irrecoverably deleted, in which case updateDeleteMessages will be received instead of this update +type UpdateMessageSendFailed struct { + tdCommon + Message *Message `json:"message"` // Contains information about the message that failed to send + OldMessageID int64 `json:"old_message_id"` // The previous temporary message identifier + ErrorCode int32 `json:"error_code"` // An error code + ErrorMessage string `json:"error_message"` // Error message +} + +// MessageType return the string telegram-type of UpdateMessageSendFailed +func (updateMessageSendFailed *UpdateMessageSendFailed) MessageType() string { + return "updateMessageSendFailed" +} + +// NewUpdateMessageSendFailed creates a new UpdateMessageSendFailed +// +// @param message Contains information about the message that failed to send +// @param oldMessageID The previous temporary message identifier +// @param errorCode An error code +// @param errorMessage Error message +func NewUpdateMessageSendFailed(message *Message, oldMessageID int64, errorCode int32, errorMessage string) *UpdateMessageSendFailed { + updateMessageSendFailedTemp := UpdateMessageSendFailed{ + tdCommon: tdCommon{Type: "updateMessageSendFailed"}, + Message: message, + OldMessageID: oldMessageID, + ErrorCode: errorCode, + ErrorMessage: errorMessage, + } + + return &updateMessageSendFailedTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageSendFailed *UpdateMessageSendFailed) GetUpdateEnum() UpdateEnum { + return UpdateMessageSendFailedType +} + +// UpdateMessageContent The message content has changed +type UpdateMessageContent struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier + NewContent MessageContent `json:"new_content"` // New message content +} + +// MessageType return the string telegram-type of UpdateMessageContent +func (updateMessageContent *UpdateMessageContent) MessageType() string { + return "updateMessageContent" +} + +// NewUpdateMessageContent creates a new UpdateMessageContent +// +// @param chatID Chat identifier +// @param messageID Message identifier +// @param newContent New message content +func NewUpdateMessageContent(chatID int64, messageID int64, newContent MessageContent) *UpdateMessageContent { + updateMessageContentTemp := UpdateMessageContent{ + tdCommon: tdCommon{Type: "updateMessageContent"}, + ChatID: chatID, + MessageID: messageID, + NewContent: newContent, + } + + return &updateMessageContentTemp +} + +// UnmarshalJSON unmarshal to json +func (updateMessageContent *UpdateMessageContent) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateMessageContent.tdCommon = tempObj.tdCommon + updateMessageContent.ChatID = tempObj.ChatID + updateMessageContent.MessageID = tempObj.MessageID + + fieldNewContent, _ := unmarshalMessageContent(objMap["new_content"]) + updateMessageContent.NewContent = fieldNewContent + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageContent *UpdateMessageContent) GetUpdateEnum() UpdateEnum { + return UpdateMessageContentType +} + +// UpdateMessageEdited A message was edited. Changes in the message content will come in a separate updateMessageContent +type UpdateMessageEdited struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier + EditDate int32 `json:"edit_date"` // Point in time (Unix timestamp) when the message was edited + ReplyMarkup ReplyMarkup `json:"reply_markup"` // New message reply markup; may be null +} + +// MessageType return the string telegram-type of UpdateMessageEdited +func (updateMessageEdited *UpdateMessageEdited) MessageType() string { + return "updateMessageEdited" +} + +// NewUpdateMessageEdited creates a new UpdateMessageEdited +// +// @param chatID Chat identifier +// @param messageID Message identifier +// @param editDate Point in time (Unix timestamp) when the message was edited +// @param replyMarkup New message reply markup; may be null +func NewUpdateMessageEdited(chatID int64, messageID int64, editDate int32, replyMarkup ReplyMarkup) *UpdateMessageEdited { + updateMessageEditedTemp := UpdateMessageEdited{ + tdCommon: tdCommon{Type: "updateMessageEdited"}, + ChatID: chatID, + MessageID: messageID, + EditDate: editDate, + ReplyMarkup: replyMarkup, + } + + return &updateMessageEditedTemp +} + +// UnmarshalJSON unmarshal to json +func (updateMessageEdited *UpdateMessageEdited) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier + EditDate int32 `json:"edit_date"` // Point in time (Unix timestamp) when the message was edited + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateMessageEdited.tdCommon = tempObj.tdCommon + updateMessageEdited.ChatID = tempObj.ChatID + updateMessageEdited.MessageID = tempObj.MessageID + updateMessageEdited.EditDate = tempObj.EditDate + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + updateMessageEdited.ReplyMarkup = fieldReplyMarkup + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageEdited *UpdateMessageEdited) GetUpdateEnum() UpdateEnum { + return UpdateMessageEditedType +} + +// UpdateMessageViews The view count of the message has changed +type UpdateMessageViews struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier + Views int32 `json:"views"` // New value of the view count +} + +// MessageType return the string telegram-type of UpdateMessageViews +func (updateMessageViews *UpdateMessageViews) MessageType() string { + return "updateMessageViews" +} + +// NewUpdateMessageViews creates a new UpdateMessageViews +// +// @param chatID Chat identifier +// @param messageID Message identifier +// @param views New value of the view count +func NewUpdateMessageViews(chatID int64, messageID int64, views int32) *UpdateMessageViews { + updateMessageViewsTemp := UpdateMessageViews{ + tdCommon: tdCommon{Type: "updateMessageViews"}, + ChatID: chatID, + MessageID: messageID, + Views: views, + } + + return &updateMessageViewsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageViews *UpdateMessageViews) GetUpdateEnum() UpdateEnum { + return UpdateMessageViewsType +} + +// UpdateMessageContentOpened The message content was opened. Updates voice note messages to "listened", video note messages to "viewed" and starts the TTL timer for self-destructing messages +type UpdateMessageContentOpened struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier +} + +// MessageType return the string telegram-type of UpdateMessageContentOpened +func (updateMessageContentOpened *UpdateMessageContentOpened) MessageType() string { + return "updateMessageContentOpened" +} + +// NewUpdateMessageContentOpened creates a new UpdateMessageContentOpened +// +// @param chatID Chat identifier +// @param messageID Message identifier +func NewUpdateMessageContentOpened(chatID int64, messageID int64) *UpdateMessageContentOpened { + updateMessageContentOpenedTemp := UpdateMessageContentOpened{ + tdCommon: tdCommon{Type: "updateMessageContentOpened"}, + ChatID: chatID, + MessageID: messageID, + } + + return &updateMessageContentOpenedTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageContentOpened *UpdateMessageContentOpened) GetUpdateEnum() UpdateEnum { + return UpdateMessageContentOpenedType +} + +// UpdateMessageMentionRead A message with an unread mention was read +type UpdateMessageMentionRead struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier + UnreadMentionCount int32 `json:"unread_mention_count"` // The new number of unread mention messages left in the chat +} + +// MessageType return the string telegram-type of UpdateMessageMentionRead +func (updateMessageMentionRead *UpdateMessageMentionRead) MessageType() string { + return "updateMessageMentionRead" +} + +// NewUpdateMessageMentionRead creates a new UpdateMessageMentionRead +// +// @param chatID Chat identifier +// @param messageID Message identifier +// @param unreadMentionCount The new number of unread mention messages left in the chat +func NewUpdateMessageMentionRead(chatID int64, messageID int64, unreadMentionCount int32) *UpdateMessageMentionRead { + updateMessageMentionReadTemp := UpdateMessageMentionRead{ + tdCommon: tdCommon{Type: "updateMessageMentionRead"}, + ChatID: chatID, + MessageID: messageID, + UnreadMentionCount: unreadMentionCount, + } + + return &updateMessageMentionReadTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageMentionRead *UpdateMessageMentionRead) GetUpdateEnum() UpdateEnum { + return UpdateMessageMentionReadType +} + +// UpdateNewChat A new chat has been loaded/created. This update is guaranteed to come before the chat identifier is returned to the client. The chat field changes will be reported through separate updates +type UpdateNewChat struct { + tdCommon + Chat *Chat `json:"chat"` // The chat +} + +// MessageType return the string telegram-type of UpdateNewChat +func (updateNewChat *UpdateNewChat) MessageType() string { + return "updateNewChat" +} + +// NewUpdateNewChat creates a new UpdateNewChat +// +// @param chat The chat +func NewUpdateNewChat(chat *Chat) *UpdateNewChat { + updateNewChatTemp := UpdateNewChat{ + tdCommon: tdCommon{Type: "updateNewChat"}, + Chat: chat, + } + + return &updateNewChatTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewChat *UpdateNewChat) GetUpdateEnum() UpdateEnum { + return UpdateNewChatType +} + +// UpdateChatTitle The title of a chat was changed +type UpdateChatTitle struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + Title string `json:"title"` // The new chat title +} + +// MessageType return the string telegram-type of UpdateChatTitle +func (updateChatTitle *UpdateChatTitle) MessageType() string { + return "updateChatTitle" +} + +// NewUpdateChatTitle creates a new UpdateChatTitle +// +// @param chatID Chat identifier +// @param title The new chat title +func NewUpdateChatTitle(chatID int64, title string) *UpdateChatTitle { + updateChatTitleTemp := UpdateChatTitle{ + tdCommon: tdCommon{Type: "updateChatTitle"}, + ChatID: chatID, + Title: title, + } + + return &updateChatTitleTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatTitle *UpdateChatTitle) GetUpdateEnum() UpdateEnum { + return UpdateChatTitleType +} + +// UpdateChatPhoto A chat photo was changed +type UpdateChatPhoto struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + Photo *ChatPhoto `json:"photo"` // The new chat photo; may be null +} + +// MessageType return the string telegram-type of UpdateChatPhoto +func (updateChatPhoto *UpdateChatPhoto) MessageType() string { + return "updateChatPhoto" +} + +// NewUpdateChatPhoto creates a new UpdateChatPhoto +// +// @param chatID Chat identifier +// @param photo The new chat photo; may be null +func NewUpdateChatPhoto(chatID int64, photo *ChatPhoto) *UpdateChatPhoto { + updateChatPhotoTemp := UpdateChatPhoto{ + tdCommon: tdCommon{Type: "updateChatPhoto"}, + ChatID: chatID, + Photo: photo, + } + + return &updateChatPhotoTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatPhoto *UpdateChatPhoto) GetUpdateEnum() UpdateEnum { + return UpdateChatPhotoType +} + +// UpdateChatLastMessage The last message of a chat was changed. If last_message is null then the last message in the chat became unknown. Some new unknown messages might be added to the chat in this case +type UpdateChatLastMessage struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + LastMessage *Message `json:"last_message"` // The new last message in the chat; may be null + Order JSONInt64 `json:"order"` // New value of the chat order +} + +// MessageType return the string telegram-type of UpdateChatLastMessage +func (updateChatLastMessage *UpdateChatLastMessage) MessageType() string { + return "updateChatLastMessage" +} + +// NewUpdateChatLastMessage creates a new UpdateChatLastMessage +// +// @param chatID Chat identifier +// @param lastMessage The new last message in the chat; may be null +// @param order New value of the chat order +func NewUpdateChatLastMessage(chatID int64, lastMessage *Message, order JSONInt64) *UpdateChatLastMessage { + updateChatLastMessageTemp := UpdateChatLastMessage{ + tdCommon: tdCommon{Type: "updateChatLastMessage"}, + ChatID: chatID, + LastMessage: lastMessage, + Order: order, + } + + return &updateChatLastMessageTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatLastMessage *UpdateChatLastMessage) GetUpdateEnum() UpdateEnum { + return UpdateChatLastMessageType +} + +// UpdateChatOrder The order of the chat in the chats list has changed. Instead of this update updateChatLastMessage, updateChatIsPinned or updateChatDraftMessage might be sent +type UpdateChatOrder struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + Order JSONInt64 `json:"order"` // New value of the order +} + +// MessageType return the string telegram-type of UpdateChatOrder +func (updateChatOrder *UpdateChatOrder) MessageType() string { + return "updateChatOrder" +} + +// NewUpdateChatOrder creates a new UpdateChatOrder +// +// @param chatID Chat identifier +// @param order New value of the order +func NewUpdateChatOrder(chatID int64, order JSONInt64) *UpdateChatOrder { + updateChatOrderTemp := UpdateChatOrder{ + tdCommon: tdCommon{Type: "updateChatOrder"}, + ChatID: chatID, + Order: order, + } + + return &updateChatOrderTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatOrder *UpdateChatOrder) GetUpdateEnum() UpdateEnum { + return UpdateChatOrderType +} + +// UpdateChatIsPinned A chat was pinned or unpinned +type UpdateChatIsPinned struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + IsPinned bool `json:"is_pinned"` // New value of is_pinned + Order JSONInt64 `json:"order"` // New value of the chat order +} + +// MessageType return the string telegram-type of UpdateChatIsPinned +func (updateChatIsPinned *UpdateChatIsPinned) MessageType() string { + return "updateChatIsPinned" +} + +// NewUpdateChatIsPinned creates a new UpdateChatIsPinned +// +// @param chatID Chat identifier +// @param isPinned New value of is_pinned +// @param order New value of the chat order +func NewUpdateChatIsPinned(chatID int64, isPinned bool, order JSONInt64) *UpdateChatIsPinned { + updateChatIsPinnedTemp := UpdateChatIsPinned{ + tdCommon: tdCommon{Type: "updateChatIsPinned"}, + ChatID: chatID, + IsPinned: isPinned, + Order: order, + } + + return &updateChatIsPinnedTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatIsPinned *UpdateChatIsPinned) GetUpdateEnum() UpdateEnum { + return UpdateChatIsPinnedType +} + +// UpdateChatIsMarkedAsUnread A chat was marked as unread or was read +type UpdateChatIsMarkedAsUnread struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + IsMarkedAsUnread bool `json:"is_marked_as_unread"` // New value of is_marked_as_unread +} + +// MessageType return the string telegram-type of UpdateChatIsMarkedAsUnread +func (updateChatIsMarkedAsUnread *UpdateChatIsMarkedAsUnread) MessageType() string { + return "updateChatIsMarkedAsUnread" +} + +// NewUpdateChatIsMarkedAsUnread creates a new UpdateChatIsMarkedAsUnread +// +// @param chatID Chat identifier +// @param isMarkedAsUnread New value of is_marked_as_unread +func NewUpdateChatIsMarkedAsUnread(chatID int64, isMarkedAsUnread bool) *UpdateChatIsMarkedAsUnread { + updateChatIsMarkedAsUnreadTemp := UpdateChatIsMarkedAsUnread{ + tdCommon: tdCommon{Type: "updateChatIsMarkedAsUnread"}, + ChatID: chatID, + IsMarkedAsUnread: isMarkedAsUnread, + } + + return &updateChatIsMarkedAsUnreadTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatIsMarkedAsUnread *UpdateChatIsMarkedAsUnread) GetUpdateEnum() UpdateEnum { + return UpdateChatIsMarkedAsUnreadType +} + +// UpdateChatIsSponsored A chat's is_sponsored field has changed +type UpdateChatIsSponsored struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + IsSponsored bool `json:"is_sponsored"` // New value of is_sponsored + Order JSONInt64 `json:"order"` // New value of chat order +} + +// MessageType return the string telegram-type of UpdateChatIsSponsored +func (updateChatIsSponsored *UpdateChatIsSponsored) MessageType() string { + return "updateChatIsSponsored" +} + +// NewUpdateChatIsSponsored creates a new UpdateChatIsSponsored +// +// @param chatID Chat identifier +// @param isSponsored New value of is_sponsored +// @param order New value of chat order +func NewUpdateChatIsSponsored(chatID int64, isSponsored bool, order JSONInt64) *UpdateChatIsSponsored { + updateChatIsSponsoredTemp := UpdateChatIsSponsored{ + tdCommon: tdCommon{Type: "updateChatIsSponsored"}, + ChatID: chatID, + IsSponsored: isSponsored, + Order: order, + } + + return &updateChatIsSponsoredTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatIsSponsored *UpdateChatIsSponsored) GetUpdateEnum() UpdateEnum { + return UpdateChatIsSponsoredType +} + +// UpdateChatDefaultDisableNotification The value of the default disable_notification parameter, used when a message is sent to the chat, was changed +type UpdateChatDefaultDisableNotification struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + DefaultDisableNotification bool `json:"default_disable_notification"` // The new default_disable_notification value +} + +// MessageType return the string telegram-type of UpdateChatDefaultDisableNotification +func (updateChatDefaultDisableNotification *UpdateChatDefaultDisableNotification) MessageType() string { + return "updateChatDefaultDisableNotification" +} + +// NewUpdateChatDefaultDisableNotification creates a new UpdateChatDefaultDisableNotification +// +// @param chatID Chat identifier +// @param defaultDisableNotification The new default_disable_notification value +func NewUpdateChatDefaultDisableNotification(chatID int64, defaultDisableNotification bool) *UpdateChatDefaultDisableNotification { + updateChatDefaultDisableNotificationTemp := UpdateChatDefaultDisableNotification{ + tdCommon: tdCommon{Type: "updateChatDefaultDisableNotification"}, + ChatID: chatID, + DefaultDisableNotification: defaultDisableNotification, + } + + return &updateChatDefaultDisableNotificationTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatDefaultDisableNotification *UpdateChatDefaultDisableNotification) GetUpdateEnum() UpdateEnum { + return UpdateChatDefaultDisableNotificationType +} + +// UpdateChatReadInbox Incoming messages were read or number of unread messages has been changed +type UpdateChatReadInbox struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + LastReadInboxMessageID int64 `json:"last_read_inbox_message_id"` // Identifier of the last read incoming message + UnreadCount int32 `json:"unread_count"` // The number of unread messages left in the chat +} + +// MessageType return the string telegram-type of UpdateChatReadInbox +func (updateChatReadInbox *UpdateChatReadInbox) MessageType() string { + return "updateChatReadInbox" +} + +// NewUpdateChatReadInbox creates a new UpdateChatReadInbox +// +// @param chatID Chat identifier +// @param lastReadInboxMessageID Identifier of the last read incoming message +// @param unreadCount The number of unread messages left in the chat +func NewUpdateChatReadInbox(chatID int64, lastReadInboxMessageID int64, unreadCount int32) *UpdateChatReadInbox { + updateChatReadInboxTemp := UpdateChatReadInbox{ + tdCommon: tdCommon{Type: "updateChatReadInbox"}, + ChatID: chatID, + LastReadInboxMessageID: lastReadInboxMessageID, + UnreadCount: unreadCount, + } + + return &updateChatReadInboxTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatReadInbox *UpdateChatReadInbox) GetUpdateEnum() UpdateEnum { + return UpdateChatReadInboxType +} + +// UpdateChatReadOutbox Outgoing messages were read +type UpdateChatReadOutbox struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + LastReadOutboxMessageID int64 `json:"last_read_outbox_message_id"` // Identifier of last read outgoing message +} + +// MessageType return the string telegram-type of UpdateChatReadOutbox +func (updateChatReadOutbox *UpdateChatReadOutbox) MessageType() string { + return "updateChatReadOutbox" +} + +// NewUpdateChatReadOutbox creates a new UpdateChatReadOutbox +// +// @param chatID Chat identifier +// @param lastReadOutboxMessageID Identifier of last read outgoing message +func NewUpdateChatReadOutbox(chatID int64, lastReadOutboxMessageID int64) *UpdateChatReadOutbox { + updateChatReadOutboxTemp := UpdateChatReadOutbox{ + tdCommon: tdCommon{Type: "updateChatReadOutbox"}, + ChatID: chatID, + LastReadOutboxMessageID: lastReadOutboxMessageID, + } + + return &updateChatReadOutboxTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatReadOutbox *UpdateChatReadOutbox) GetUpdateEnum() UpdateEnum { + return UpdateChatReadOutboxType +} + +// UpdateChatUnreadMentionCount The chat unread_mention_count has changed +type UpdateChatUnreadMentionCount struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + UnreadMentionCount int32 `json:"unread_mention_count"` // The number of unread mention messages left in the chat +} + +// MessageType return the string telegram-type of UpdateChatUnreadMentionCount +func (updateChatUnreadMentionCount *UpdateChatUnreadMentionCount) MessageType() string { + return "updateChatUnreadMentionCount" +} + +// NewUpdateChatUnreadMentionCount creates a new UpdateChatUnreadMentionCount +// +// @param chatID Chat identifier +// @param unreadMentionCount The number of unread mention messages left in the chat +func NewUpdateChatUnreadMentionCount(chatID int64, unreadMentionCount int32) *UpdateChatUnreadMentionCount { + updateChatUnreadMentionCountTemp := UpdateChatUnreadMentionCount{ + tdCommon: tdCommon{Type: "updateChatUnreadMentionCount"}, + ChatID: chatID, + UnreadMentionCount: unreadMentionCount, + } + + return &updateChatUnreadMentionCountTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatUnreadMentionCount *UpdateChatUnreadMentionCount) GetUpdateEnum() UpdateEnum { + return UpdateChatUnreadMentionCountType +} + +// UpdateChatNotificationSettings Notification settings for a chat were changed +type UpdateChatNotificationSettings struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + NotificationSettings *ChatNotificationSettings `json:"notification_settings"` // The new notification settings +} + +// MessageType return the string telegram-type of UpdateChatNotificationSettings +func (updateChatNotificationSettings *UpdateChatNotificationSettings) MessageType() string { + return "updateChatNotificationSettings" +} + +// NewUpdateChatNotificationSettings creates a new UpdateChatNotificationSettings +// +// @param chatID Chat identifier +// @param notificationSettings The new notification settings +func NewUpdateChatNotificationSettings(chatID int64, notificationSettings *ChatNotificationSettings) *UpdateChatNotificationSettings { + updateChatNotificationSettingsTemp := UpdateChatNotificationSettings{ + tdCommon: tdCommon{Type: "updateChatNotificationSettings"}, + ChatID: chatID, + NotificationSettings: notificationSettings, + } + + return &updateChatNotificationSettingsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatNotificationSettings *UpdateChatNotificationSettings) GetUpdateEnum() UpdateEnum { + return UpdateChatNotificationSettingsType +} + +// UpdateScopeNotificationSettings Notification settings for some type of chats were updated +type UpdateScopeNotificationSettings struct { + tdCommon + Scope NotificationSettingsScope `json:"scope"` // Types of chats for which notification settings were updated + NotificationSettings *ScopeNotificationSettings `json:"notification_settings"` // The new notification settings +} + +// MessageType return the string telegram-type of UpdateScopeNotificationSettings +func (updateScopeNotificationSettings *UpdateScopeNotificationSettings) MessageType() string { + return "updateScopeNotificationSettings" +} + +// NewUpdateScopeNotificationSettings creates a new UpdateScopeNotificationSettings +// +// @param scope Types of chats for which notification settings were updated +// @param notificationSettings The new notification settings +func NewUpdateScopeNotificationSettings(scope NotificationSettingsScope, notificationSettings *ScopeNotificationSettings) *UpdateScopeNotificationSettings { + updateScopeNotificationSettingsTemp := UpdateScopeNotificationSettings{ + tdCommon: tdCommon{Type: "updateScopeNotificationSettings"}, + Scope: scope, + NotificationSettings: notificationSettings, + } + + return &updateScopeNotificationSettingsTemp +} + +// UnmarshalJSON unmarshal to json +func (updateScopeNotificationSettings *UpdateScopeNotificationSettings) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + NotificationSettings *ScopeNotificationSettings `json:"notification_settings"` // The new notification settings + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateScopeNotificationSettings.tdCommon = tempObj.tdCommon + updateScopeNotificationSettings.NotificationSettings = tempObj.NotificationSettings + + fieldScope, _ := unmarshalNotificationSettingsScope(objMap["scope"]) + updateScopeNotificationSettings.Scope = fieldScope + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateScopeNotificationSettings *UpdateScopeNotificationSettings) GetUpdateEnum() UpdateEnum { + return UpdateScopeNotificationSettingsType +} + +// UpdateChatReplyMarkup The default chat reply markup was changed. Can occur because new messages with reply markup were received or because an old reply markup was hidden by the user +type UpdateChatReplyMarkup struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + ReplyMarkupMessageID int64 `json:"reply_markup_message_id"` // Identifier of the message from which reply markup needs to be used; 0 if there is no default custom reply markup in the chat +} + +// MessageType return the string telegram-type of UpdateChatReplyMarkup +func (updateChatReplyMarkup *UpdateChatReplyMarkup) MessageType() string { + return "updateChatReplyMarkup" +} + +// NewUpdateChatReplyMarkup creates a new UpdateChatReplyMarkup +// +// @param chatID Chat identifier +// @param replyMarkupMessageID Identifier of the message from which reply markup needs to be used; 0 if there is no default custom reply markup in the chat +func NewUpdateChatReplyMarkup(chatID int64, replyMarkupMessageID int64) *UpdateChatReplyMarkup { + updateChatReplyMarkupTemp := UpdateChatReplyMarkup{ + tdCommon: tdCommon{Type: "updateChatReplyMarkup"}, + ChatID: chatID, + ReplyMarkupMessageID: replyMarkupMessageID, + } + + return &updateChatReplyMarkupTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatReplyMarkup *UpdateChatReplyMarkup) GetUpdateEnum() UpdateEnum { + return UpdateChatReplyMarkupType +} + +// UpdateChatDraftMessage A chat draft has changed. Be aware that the update may come in the currently opened chat but with old content of the draft. If the user has changed the content of the draft, this update shouldn't be applied +type UpdateChatDraftMessage struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + DraftMessage *DraftMessage `json:"draft_message"` // The new draft message; may be null + Order JSONInt64 `json:"order"` // New value of the chat order +} + +// MessageType return the string telegram-type of UpdateChatDraftMessage +func (updateChatDraftMessage *UpdateChatDraftMessage) MessageType() string { + return "updateChatDraftMessage" +} + +// NewUpdateChatDraftMessage creates a new UpdateChatDraftMessage +// +// @param chatID Chat identifier +// @param draftMessage The new draft message; may be null +// @param order New value of the chat order +func NewUpdateChatDraftMessage(chatID int64, draftMessage *DraftMessage, order JSONInt64) *UpdateChatDraftMessage { + updateChatDraftMessageTemp := UpdateChatDraftMessage{ + tdCommon: tdCommon{Type: "updateChatDraftMessage"}, + ChatID: chatID, + DraftMessage: draftMessage, + Order: order, + } + + return &updateChatDraftMessageTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatDraftMessage *UpdateChatDraftMessage) GetUpdateEnum() UpdateEnum { + return UpdateChatDraftMessageType +} + +// UpdateDeleteMessages Some messages were deleted +type UpdateDeleteMessages struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageIDs []int64 `json:"message_ids"` // Identifiers of the deleted messages + IsPermanent bool `json:"is_permanent"` // True, if the messages are permanently deleted by a user (as opposed to just becoming unaccessible) + FromCache bool `json:"from_cache"` // True, if the messages are deleted only from the cache and can possibly be retrieved again in the future +} + +// MessageType return the string telegram-type of UpdateDeleteMessages +func (updateDeleteMessages *UpdateDeleteMessages) MessageType() string { + return "updateDeleteMessages" +} + +// NewUpdateDeleteMessages creates a new UpdateDeleteMessages +// +// @param chatID Chat identifier +// @param messageIDs Identifiers of the deleted messages +// @param isPermanent True, if the messages are permanently deleted by a user (as opposed to just becoming unaccessible) +// @param fromCache True, if the messages are deleted only from the cache and can possibly be retrieved again in the future +func NewUpdateDeleteMessages(chatID int64, messageIDs []int64, isPermanent bool, fromCache bool) *UpdateDeleteMessages { + updateDeleteMessagesTemp := UpdateDeleteMessages{ + tdCommon: tdCommon{Type: "updateDeleteMessages"}, + ChatID: chatID, + MessageIDs: messageIDs, + IsPermanent: isPermanent, + FromCache: fromCache, + } + + return &updateDeleteMessagesTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateDeleteMessages *UpdateDeleteMessages) GetUpdateEnum() UpdateEnum { + return UpdateDeleteMessagesType +} + +// UpdateUserChatAction User activity in the chat has changed +type UpdateUserChatAction struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + UserID int32 `json:"user_id"` // Identifier of a user performing an action + Action ChatAction `json:"action"` // The action description +} + +// MessageType return the string telegram-type of UpdateUserChatAction +func (updateUserChatAction *UpdateUserChatAction) MessageType() string { + return "updateUserChatAction" +} + +// NewUpdateUserChatAction creates a new UpdateUserChatAction +// +// @param chatID Chat identifier +// @param userID Identifier of a user performing an action +// @param action The action description +func NewUpdateUserChatAction(chatID int64, userID int32, action ChatAction) *UpdateUserChatAction { + updateUserChatActionTemp := UpdateUserChatAction{ + tdCommon: tdCommon{Type: "updateUserChatAction"}, + ChatID: chatID, + UserID: userID, + Action: action, + } + + return &updateUserChatActionTemp +} + +// UnmarshalJSON unmarshal to json +func (updateUserChatAction *UpdateUserChatAction) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + UserID int32 `json:"user_id"` // Identifier of a user performing an action + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateUserChatAction.tdCommon = tempObj.tdCommon + updateUserChatAction.ChatID = tempObj.ChatID + updateUserChatAction.UserID = tempObj.UserID + + fieldAction, _ := unmarshalChatAction(objMap["action"]) + updateUserChatAction.Action = fieldAction + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateUserChatAction *UpdateUserChatAction) GetUpdateEnum() UpdateEnum { + return UpdateUserChatActionType +} + +// UpdateUserStatus The user went online or offline +type UpdateUserStatus struct { + tdCommon + UserID int32 `json:"user_id"` // User identifier + Status UserStatus `json:"status"` // New status of the user +} + +// MessageType return the string telegram-type of UpdateUserStatus +func (updateUserStatus *UpdateUserStatus) MessageType() string { + return "updateUserStatus" +} + +// NewUpdateUserStatus creates a new UpdateUserStatus +// +// @param userID User identifier +// @param status New status of the user +func NewUpdateUserStatus(userID int32, status UserStatus) *UpdateUserStatus { + updateUserStatusTemp := UpdateUserStatus{ + tdCommon: tdCommon{Type: "updateUserStatus"}, + UserID: userID, + Status: status, + } + + return &updateUserStatusTemp +} + +// UnmarshalJSON unmarshal to json +func (updateUserStatus *UpdateUserStatus) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + UserID int32 `json:"user_id"` // User identifier + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateUserStatus.tdCommon = tempObj.tdCommon + updateUserStatus.UserID = tempObj.UserID + + fieldStatus, _ := unmarshalUserStatus(objMap["status"]) + updateUserStatus.Status = fieldStatus + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateUserStatus *UpdateUserStatus) GetUpdateEnum() UpdateEnum { + return UpdateUserStatusType +} + +// UpdateUser Some data of a user has changed. This update is guaranteed to come before the user identifier is returned to the client +type UpdateUser struct { + tdCommon + User *User `json:"user"` // New data about the user +} + +// MessageType return the string telegram-type of UpdateUser +func (updateUser *UpdateUser) MessageType() string { + return "updateUser" +} + +// NewUpdateUser creates a new UpdateUser +// +// @param user New data about the user +func NewUpdateUser(user *User) *UpdateUser { + updateUserTemp := UpdateUser{ + tdCommon: tdCommon{Type: "updateUser"}, + User: user, + } + + return &updateUserTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateUser *UpdateUser) GetUpdateEnum() UpdateEnum { + return UpdateUserType +} + +// UpdateBasicGroup Some data of a basic group has changed. This update is guaranteed to come before the basic group identifier is returned to the client +type UpdateBasicGroup struct { + tdCommon + BasicGroup *BasicGroup `json:"basic_group"` // New data about the group +} + +// MessageType return the string telegram-type of UpdateBasicGroup +func (updateBasicGroup *UpdateBasicGroup) MessageType() string { + return "updateBasicGroup" +} + +// NewUpdateBasicGroup creates a new UpdateBasicGroup +// +// @param basicGroup New data about the group +func NewUpdateBasicGroup(basicGroup *BasicGroup) *UpdateBasicGroup { + updateBasicGroupTemp := UpdateBasicGroup{ + tdCommon: tdCommon{Type: "updateBasicGroup"}, + BasicGroup: basicGroup, + } + + return &updateBasicGroupTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateBasicGroup *UpdateBasicGroup) GetUpdateEnum() UpdateEnum { + return UpdateBasicGroupType +} + +// UpdateSupergroup Some data of a supergroup or a channel has changed. This update is guaranteed to come before the supergroup identifier is returned to the client +type UpdateSupergroup struct { + tdCommon + Supergroup *Supergroup `json:"supergroup"` // New data about the supergroup +} + +// MessageType return the string telegram-type of UpdateSupergroup +func (updateSupergroup *UpdateSupergroup) MessageType() string { + return "updateSupergroup" +} + +// NewUpdateSupergroup creates a new UpdateSupergroup +// +// @param supergroup New data about the supergroup +func NewUpdateSupergroup(supergroup *Supergroup) *UpdateSupergroup { + updateSupergroupTemp := UpdateSupergroup{ + tdCommon: tdCommon{Type: "updateSupergroup"}, + Supergroup: supergroup, + } + + return &updateSupergroupTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateSupergroup *UpdateSupergroup) GetUpdateEnum() UpdateEnum { + return UpdateSupergroupType +} + +// UpdateSecretChat Some data of a secret chat has changed. This update is guaranteed to come before the secret chat identifier is returned to the client +type UpdateSecretChat struct { + tdCommon + SecretChat *SecretChat `json:"secret_chat"` // New data about the secret chat +} + +// MessageType return the string telegram-type of UpdateSecretChat +func (updateSecretChat *UpdateSecretChat) MessageType() string { + return "updateSecretChat" +} + +// NewUpdateSecretChat creates a new UpdateSecretChat +// +// @param secretChat New data about the secret chat +func NewUpdateSecretChat(secretChat *SecretChat) *UpdateSecretChat { + updateSecretChatTemp := UpdateSecretChat{ + tdCommon: tdCommon{Type: "updateSecretChat"}, + SecretChat: secretChat, + } + + return &updateSecretChatTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateSecretChat *UpdateSecretChat) GetUpdateEnum() UpdateEnum { + return UpdateSecretChatType +} + +// UpdateUserFullInfo Some data from userFullInfo has been changed +type UpdateUserFullInfo struct { + tdCommon + UserID int32 `json:"user_id"` // User identifier + UserFullInfo *UserFullInfo `json:"user_full_info"` // New full information about the user +} + +// MessageType return the string telegram-type of UpdateUserFullInfo +func (updateUserFullInfo *UpdateUserFullInfo) MessageType() string { + return "updateUserFullInfo" +} + +// NewUpdateUserFullInfo creates a new UpdateUserFullInfo +// +// @param userID User identifier +// @param userFullInfo New full information about the user +func NewUpdateUserFullInfo(userID int32, userFullInfo *UserFullInfo) *UpdateUserFullInfo { + updateUserFullInfoTemp := UpdateUserFullInfo{ + tdCommon: tdCommon{Type: "updateUserFullInfo"}, + UserID: userID, + UserFullInfo: userFullInfo, + } + + return &updateUserFullInfoTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateUserFullInfo *UpdateUserFullInfo) GetUpdateEnum() UpdateEnum { + return UpdateUserFullInfoType +} + +// UpdateBasicGroupFullInfo Some data from basicGroupFullInfo has been changed +type UpdateBasicGroupFullInfo struct { + tdCommon + BasicGroupID int32 `json:"basic_group_id"` // Identifier of a basic group + BasicGroupFullInfo *BasicGroupFullInfo `json:"basic_group_full_info"` // New full information about the group +} + +// MessageType return the string telegram-type of UpdateBasicGroupFullInfo +func (updateBasicGroupFullInfo *UpdateBasicGroupFullInfo) MessageType() string { + return "updateBasicGroupFullInfo" +} + +// NewUpdateBasicGroupFullInfo creates a new UpdateBasicGroupFullInfo +// +// @param basicGroupID Identifier of a basic group +// @param basicGroupFullInfo New full information about the group +func NewUpdateBasicGroupFullInfo(basicGroupID int32, basicGroupFullInfo *BasicGroupFullInfo) *UpdateBasicGroupFullInfo { + updateBasicGroupFullInfoTemp := UpdateBasicGroupFullInfo{ + tdCommon: tdCommon{Type: "updateBasicGroupFullInfo"}, + BasicGroupID: basicGroupID, + BasicGroupFullInfo: basicGroupFullInfo, + } + + return &updateBasicGroupFullInfoTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateBasicGroupFullInfo *UpdateBasicGroupFullInfo) GetUpdateEnum() UpdateEnum { + return UpdateBasicGroupFullInfoType +} + +// UpdateSupergroupFullInfo Some data from supergroupFullInfo has been changed +type UpdateSupergroupFullInfo struct { + tdCommon + SupergroupID int32 `json:"supergroup_id"` // Identifier of the supergroup or channel + SupergroupFullInfo *SupergroupFullInfo `json:"supergroup_full_info"` // New full information about the supergroup +} + +// MessageType return the string telegram-type of UpdateSupergroupFullInfo +func (updateSupergroupFullInfo *UpdateSupergroupFullInfo) MessageType() string { + return "updateSupergroupFullInfo" +} + +// NewUpdateSupergroupFullInfo creates a new UpdateSupergroupFullInfo +// +// @param supergroupID Identifier of the supergroup or channel +// @param supergroupFullInfo New full information about the supergroup +func NewUpdateSupergroupFullInfo(supergroupID int32, supergroupFullInfo *SupergroupFullInfo) *UpdateSupergroupFullInfo { + updateSupergroupFullInfoTemp := UpdateSupergroupFullInfo{ + tdCommon: tdCommon{Type: "updateSupergroupFullInfo"}, + SupergroupID: supergroupID, + SupergroupFullInfo: supergroupFullInfo, + } + + return &updateSupergroupFullInfoTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateSupergroupFullInfo *UpdateSupergroupFullInfo) GetUpdateEnum() UpdateEnum { + return UpdateSupergroupFullInfoType +} + +// UpdateServiceNotification Service notification from the server. Upon receiving this the client must show a popup with the content of the notification +type UpdateServiceNotification struct { + tdCommon + Type string `json:"type"` // Notification type. If type begins with "AUTH_KEY_DROP_", then two buttons "Cancel" and "Log out" should be shown under notification; if user presses the second, all local data should be destroyed using Destroy method + Content MessageContent `json:"content"` // Notification content +} + +// MessageType return the string telegram-type of UpdateServiceNotification +func (updateServiceNotification *UpdateServiceNotification) MessageType() string { + return "updateServiceNotification" +} + +// NewUpdateServiceNotification creates a new UpdateServiceNotification +// +// @param typeParam Notification type. If type begins with "AUTH_KEY_DROP_", then two buttons "Cancel" and "Log out" should be shown under notification; if user presses the second, all local data should be destroyed using Destroy method +// @param content Notification content +func NewUpdateServiceNotification(typeParam string, content MessageContent) *UpdateServiceNotification { + updateServiceNotificationTemp := UpdateServiceNotification{ + tdCommon: tdCommon{Type: "updateServiceNotification"}, + Type: typeParam, + Content: content, + } + + return &updateServiceNotificationTemp +} + +// UnmarshalJSON unmarshal to json +func (updateServiceNotification *UpdateServiceNotification) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Type string `json:"type"` // Notification type. If type begins with "AUTH_KEY_DROP_", then two buttons "Cancel" and "Log out" should be shown under notification; if user presses the second, all local data should be destroyed using Destroy method + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateServiceNotification.tdCommon = tempObj.tdCommon + updateServiceNotification.Type = tempObj.Type + + fieldContent, _ := unmarshalMessageContent(objMap["content"]) + updateServiceNotification.Content = fieldContent + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateServiceNotification *UpdateServiceNotification) GetUpdateEnum() UpdateEnum { + return UpdateServiceNotificationType +} + +// UpdateFile Information about a file was updated +type UpdateFile struct { + tdCommon + File *File `json:"file"` // New data about the file +} + +// MessageType return the string telegram-type of UpdateFile +func (updateFile *UpdateFile) MessageType() string { + return "updateFile" +} + +// NewUpdateFile creates a new UpdateFile +// +// @param file New data about the file +func NewUpdateFile(file *File) *UpdateFile { + updateFileTemp := UpdateFile{ + tdCommon: tdCommon{Type: "updateFile"}, + File: file, + } + + return &updateFileTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateFile *UpdateFile) GetUpdateEnum() UpdateEnum { + return UpdateFileType +} + +// UpdateFileGenerationStart The file generation process needs to be started by the client +type UpdateFileGenerationStart struct { + tdCommon + GenerationID JSONInt64 `json:"generation_id"` // Unique identifier for the generation process + OriginalPath string `json:"original_path"` // The path to a file from which a new file is generated; may be empty + DestinationPath string `json:"destination_path"` // The path to a file that should be created and where the new file should be generated + Conversion string `json:"conversion"` // String specifying the conversion applied to the original file. If conversion is "#url#" than original_path contains an HTTP/HTTPS URL of a file, which should be downloaded by the client +} + +// MessageType return the string telegram-type of UpdateFileGenerationStart +func (updateFileGenerationStart *UpdateFileGenerationStart) MessageType() string { + return "updateFileGenerationStart" +} + +// NewUpdateFileGenerationStart creates a new UpdateFileGenerationStart +// +// @param generationID Unique identifier for the generation process +// @param originalPath The path to a file from which a new file is generated; may be empty +// @param destinationPath The path to a file that should be created and where the new file should be generated +// @param conversion String specifying the conversion applied to the original file. If conversion is "#url#" than original_path contains an HTTP/HTTPS URL of a file, which should be downloaded by the client +func NewUpdateFileGenerationStart(generationID JSONInt64, originalPath string, destinationPath string, conversion string) *UpdateFileGenerationStart { + updateFileGenerationStartTemp := UpdateFileGenerationStart{ + tdCommon: tdCommon{Type: "updateFileGenerationStart"}, + GenerationID: generationID, + OriginalPath: originalPath, + DestinationPath: destinationPath, + Conversion: conversion, + } + + return &updateFileGenerationStartTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateFileGenerationStart *UpdateFileGenerationStart) GetUpdateEnum() UpdateEnum { + return UpdateFileGenerationStartType +} + +// UpdateFileGenerationStop File generation is no longer needed +type UpdateFileGenerationStop struct { + tdCommon + GenerationID JSONInt64 `json:"generation_id"` // Unique identifier for the generation process +} + +// MessageType return the string telegram-type of UpdateFileGenerationStop +func (updateFileGenerationStop *UpdateFileGenerationStop) MessageType() string { + return "updateFileGenerationStop" +} + +// NewUpdateFileGenerationStop creates a new UpdateFileGenerationStop +// +// @param generationID Unique identifier for the generation process +func NewUpdateFileGenerationStop(generationID JSONInt64) *UpdateFileGenerationStop { + updateFileGenerationStopTemp := UpdateFileGenerationStop{ + tdCommon: tdCommon{Type: "updateFileGenerationStop"}, + GenerationID: generationID, + } + + return &updateFileGenerationStopTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateFileGenerationStop *UpdateFileGenerationStop) GetUpdateEnum() UpdateEnum { + return UpdateFileGenerationStopType +} + +// UpdateCall New call was created or information about a call was updated +type UpdateCall struct { + tdCommon + Call *Call `json:"call"` // New data about a call +} + +// MessageType return the string telegram-type of UpdateCall +func (updateCall *UpdateCall) MessageType() string { + return "updateCall" +} + +// NewUpdateCall creates a new UpdateCall +// +// @param call New data about a call +func NewUpdateCall(call *Call) *UpdateCall { + updateCallTemp := UpdateCall{ + tdCommon: tdCommon{Type: "updateCall"}, + Call: call, + } + + return &updateCallTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateCall *UpdateCall) GetUpdateEnum() UpdateEnum { + return UpdateCallType +} + +// UpdateUserPrivacySettingRules Some privacy setting rules have been changed +type UpdateUserPrivacySettingRules struct { + tdCommon + Setting UserPrivacySetting `json:"setting"` // The privacy setting + Rules *UserPrivacySettingRules `json:"rules"` // New privacy rules +} + +// MessageType return the string telegram-type of UpdateUserPrivacySettingRules +func (updateUserPrivacySettingRules *UpdateUserPrivacySettingRules) MessageType() string { + return "updateUserPrivacySettingRules" +} + +// NewUpdateUserPrivacySettingRules creates a new UpdateUserPrivacySettingRules +// +// @param setting The privacy setting +// @param rules New privacy rules +func NewUpdateUserPrivacySettingRules(setting UserPrivacySetting, rules *UserPrivacySettingRules) *UpdateUserPrivacySettingRules { + updateUserPrivacySettingRulesTemp := UpdateUserPrivacySettingRules{ + tdCommon: tdCommon{Type: "updateUserPrivacySettingRules"}, + Setting: setting, + Rules: rules, + } + + return &updateUserPrivacySettingRulesTemp +} + +// UnmarshalJSON unmarshal to json +func (updateUserPrivacySettingRules *UpdateUserPrivacySettingRules) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Rules *UserPrivacySettingRules `json:"rules"` // New privacy rules + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateUserPrivacySettingRules.tdCommon = tempObj.tdCommon + updateUserPrivacySettingRules.Rules = tempObj.Rules + + fieldSetting, _ := unmarshalUserPrivacySetting(objMap["setting"]) + updateUserPrivacySettingRules.Setting = fieldSetting + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateUserPrivacySettingRules *UpdateUserPrivacySettingRules) GetUpdateEnum() UpdateEnum { + return UpdateUserPrivacySettingRulesType +} + +// UpdateUnreadMessageCount Number of unread messages has changed. This update is sent only if a message database is used +type UpdateUnreadMessageCount struct { + tdCommon + UnreadCount int32 `json:"unread_count"` // Total number of unread messages + UnreadUnmutedCount int32 `json:"unread_unmuted_count"` // Total number of unread messages in unmuted chats +} + +// MessageType return the string telegram-type of UpdateUnreadMessageCount +func (updateUnreadMessageCount *UpdateUnreadMessageCount) MessageType() string { + return "updateUnreadMessageCount" +} + +// NewUpdateUnreadMessageCount creates a new UpdateUnreadMessageCount +// +// @param unreadCount Total number of unread messages +// @param unreadUnmutedCount Total number of unread messages in unmuted chats +func NewUpdateUnreadMessageCount(unreadCount int32, unreadUnmutedCount int32) *UpdateUnreadMessageCount { + updateUnreadMessageCountTemp := UpdateUnreadMessageCount{ + tdCommon: tdCommon{Type: "updateUnreadMessageCount"}, + UnreadCount: unreadCount, + UnreadUnmutedCount: unreadUnmutedCount, + } + + return &updateUnreadMessageCountTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateUnreadMessageCount *UpdateUnreadMessageCount) GetUpdateEnum() UpdateEnum { + return UpdateUnreadMessageCountType +} + +// UpdateUnreadChatCount Number of unread chats, i.e. with unread messages or marked as unread, has changed. This update is sent only if a message database is used +type UpdateUnreadChatCount struct { + tdCommon + UnreadCount int32 `json:"unread_count"` // Total number of unread chats + UnreadUnmutedCount int32 `json:"unread_unmuted_count"` // Total number of unread unmuted chats + MarkedAsUnreadCount int32 `json:"marked_as_unread_count"` // Total number of chats marked as unread + MarkedAsUnreadUnmutedCount int32 `json:"marked_as_unread_unmuted_count"` // Total number of unmuted chats marked as unread +} + +// MessageType return the string telegram-type of UpdateUnreadChatCount +func (updateUnreadChatCount *UpdateUnreadChatCount) MessageType() string { + return "updateUnreadChatCount" +} + +// NewUpdateUnreadChatCount creates a new UpdateUnreadChatCount +// +// @param unreadCount Total number of unread chats +// @param unreadUnmutedCount Total number of unread unmuted chats +// @param markedAsUnreadCount Total number of chats marked as unread +// @param markedAsUnreadUnmutedCount Total number of unmuted chats marked as unread +func NewUpdateUnreadChatCount(unreadCount int32, unreadUnmutedCount int32, markedAsUnreadCount int32, markedAsUnreadUnmutedCount int32) *UpdateUnreadChatCount { + updateUnreadChatCountTemp := UpdateUnreadChatCount{ + tdCommon: tdCommon{Type: "updateUnreadChatCount"}, + UnreadCount: unreadCount, + UnreadUnmutedCount: unreadUnmutedCount, + MarkedAsUnreadCount: markedAsUnreadCount, + MarkedAsUnreadUnmutedCount: markedAsUnreadUnmutedCount, + } + + return &updateUnreadChatCountTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateUnreadChatCount *UpdateUnreadChatCount) GetUpdateEnum() UpdateEnum { + return UpdateUnreadChatCountType +} + +// UpdateOption An option changed its value +type UpdateOption struct { + tdCommon + Name string `json:"name"` // The option name + Value OptionValue `json:"value"` // The new option value +} + +// MessageType return the string telegram-type of UpdateOption +func (updateOption *UpdateOption) MessageType() string { + return "updateOption" +} + +// NewUpdateOption creates a new UpdateOption +// +// @param name The option name +// @param value The new option value +func NewUpdateOption(name string, value OptionValue) *UpdateOption { + updateOptionTemp := UpdateOption{ + tdCommon: tdCommon{Type: "updateOption"}, + Name: name, + Value: value, + } + + return &updateOptionTemp +} + +// UnmarshalJSON unmarshal to json +func (updateOption *UpdateOption) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Name string `json:"name"` // The option name + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateOption.tdCommon = tempObj.tdCommon + updateOption.Name = tempObj.Name + + fieldValue, _ := unmarshalOptionValue(objMap["value"]) + updateOption.Value = fieldValue + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateOption *UpdateOption) GetUpdateEnum() UpdateEnum { + return UpdateOptionType +} + +// UpdateInstalledStickerSets The list of installed sticker sets was updated +type UpdateInstalledStickerSets struct { + tdCommon + IsMasks bool `json:"is_masks"` // True, if the list of installed mask sticker sets was updated + StickerSetIDs []JSONInt64 `json:"sticker_set_ids"` // The new list of installed ordinary sticker sets +} + +// MessageType return the string telegram-type of UpdateInstalledStickerSets +func (updateInstalledStickerSets *UpdateInstalledStickerSets) MessageType() string { + return "updateInstalledStickerSets" +} + +// NewUpdateInstalledStickerSets creates a new UpdateInstalledStickerSets +// +// @param isMasks True, if the list of installed mask sticker sets was updated +// @param stickerSetIDs The new list of installed ordinary sticker sets +func NewUpdateInstalledStickerSets(isMasks bool, stickerSetIDs []JSONInt64) *UpdateInstalledStickerSets { + updateInstalledStickerSetsTemp := UpdateInstalledStickerSets{ + tdCommon: tdCommon{Type: "updateInstalledStickerSets"}, + IsMasks: isMasks, + StickerSetIDs: stickerSetIDs, + } + + return &updateInstalledStickerSetsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateInstalledStickerSets *UpdateInstalledStickerSets) GetUpdateEnum() UpdateEnum { + return UpdateInstalledStickerSetsType +} + +// UpdateTrendingStickerSets The list of trending sticker sets was updated or some of them were viewed +type UpdateTrendingStickerSets struct { + tdCommon + StickerSets *StickerSets `json:"sticker_sets"` // The new list of trending sticker sets +} + +// MessageType return the string telegram-type of UpdateTrendingStickerSets +func (updateTrendingStickerSets *UpdateTrendingStickerSets) MessageType() string { + return "updateTrendingStickerSets" +} + +// NewUpdateTrendingStickerSets creates a new UpdateTrendingStickerSets +// +// @param stickerSets The new list of trending sticker sets +func NewUpdateTrendingStickerSets(stickerSets *StickerSets) *UpdateTrendingStickerSets { + updateTrendingStickerSetsTemp := UpdateTrendingStickerSets{ + tdCommon: tdCommon{Type: "updateTrendingStickerSets"}, + StickerSets: stickerSets, + } + + return &updateTrendingStickerSetsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateTrendingStickerSets *UpdateTrendingStickerSets) GetUpdateEnum() UpdateEnum { + return UpdateTrendingStickerSetsType +} + +// UpdateRecentStickers The list of recently used stickers was updated +type UpdateRecentStickers struct { + tdCommon + IsAttached bool `json:"is_attached"` // True, if the list of stickers attached to photo or video files was updated, otherwise the list of sent stickers is updated + StickerIDs []int32 `json:"sticker_ids"` // The new list of file identifiers of recently used stickers +} + +// MessageType return the string telegram-type of UpdateRecentStickers +func (updateRecentStickers *UpdateRecentStickers) MessageType() string { + return "updateRecentStickers" +} + +// NewUpdateRecentStickers creates a new UpdateRecentStickers +// +// @param isAttached True, if the list of stickers attached to photo or video files was updated, otherwise the list of sent stickers is updated +// @param stickerIDs The new list of file identifiers of recently used stickers +func NewUpdateRecentStickers(isAttached bool, stickerIDs []int32) *UpdateRecentStickers { + updateRecentStickersTemp := UpdateRecentStickers{ + tdCommon: tdCommon{Type: "updateRecentStickers"}, + IsAttached: isAttached, + StickerIDs: stickerIDs, + } + + return &updateRecentStickersTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateRecentStickers *UpdateRecentStickers) GetUpdateEnum() UpdateEnum { + return UpdateRecentStickersType +} + +// UpdateFavoriteStickers The list of favorite stickers was updated +type UpdateFavoriteStickers struct { + tdCommon + StickerIDs []int32 `json:"sticker_ids"` // The new list of file identifiers of favorite stickers +} + +// MessageType return the string telegram-type of UpdateFavoriteStickers +func (updateFavoriteStickers *UpdateFavoriteStickers) MessageType() string { + return "updateFavoriteStickers" +} + +// NewUpdateFavoriteStickers creates a new UpdateFavoriteStickers +// +// @param stickerIDs The new list of file identifiers of favorite stickers +func NewUpdateFavoriteStickers(stickerIDs []int32) *UpdateFavoriteStickers { + updateFavoriteStickersTemp := UpdateFavoriteStickers{ + tdCommon: tdCommon{Type: "updateFavoriteStickers"}, + StickerIDs: stickerIDs, + } + + return &updateFavoriteStickersTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateFavoriteStickers *UpdateFavoriteStickers) GetUpdateEnum() UpdateEnum { + return UpdateFavoriteStickersType +} + +// UpdateSavedAnimations The list of saved animations was updated +type UpdateSavedAnimations struct { + tdCommon + AnimationIDs []int32 `json:"animation_ids"` // The new list of file identifiers of saved animations +} + +// MessageType return the string telegram-type of UpdateSavedAnimations +func (updateSavedAnimations *UpdateSavedAnimations) MessageType() string { + return "updateSavedAnimations" +} + +// NewUpdateSavedAnimations creates a new UpdateSavedAnimations +// +// @param animationIDs The new list of file identifiers of saved animations +func NewUpdateSavedAnimations(animationIDs []int32) *UpdateSavedAnimations { + updateSavedAnimationsTemp := UpdateSavedAnimations{ + tdCommon: tdCommon{Type: "updateSavedAnimations"}, + AnimationIDs: animationIDs, + } + + return &updateSavedAnimationsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateSavedAnimations *UpdateSavedAnimations) GetUpdateEnum() UpdateEnum { + return UpdateSavedAnimationsType +} + +// UpdateLanguagePackStrings Some language pack strings have been updated +type UpdateLanguagePackStrings struct { + tdCommon + LocalizationTarget string `json:"localization_target"` // Localization target to which the language pack belongs + LanguagePackID string `json:"language_pack_id"` // Identifier of the updated language pack + Strings []LanguagePackString `json:"strings"` // List of changed language pack strings +} + +// MessageType return the string telegram-type of UpdateLanguagePackStrings +func (updateLanguagePackStrings *UpdateLanguagePackStrings) MessageType() string { + return "updateLanguagePackStrings" +} + +// NewUpdateLanguagePackStrings creates a new UpdateLanguagePackStrings +// +// @param localizationTarget Localization target to which the language pack belongs +// @param languagePackID Identifier of the updated language pack +// @param strings List of changed language pack strings +func NewUpdateLanguagePackStrings(localizationTarget string, languagePackID string, strings []LanguagePackString) *UpdateLanguagePackStrings { + updateLanguagePackStringsTemp := UpdateLanguagePackStrings{ + tdCommon: tdCommon{Type: "updateLanguagePackStrings"}, + LocalizationTarget: localizationTarget, + LanguagePackID: languagePackID, + Strings: strings, + } + + return &updateLanguagePackStringsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateLanguagePackStrings *UpdateLanguagePackStrings) GetUpdateEnum() UpdateEnum { + return UpdateLanguagePackStringsType +} + +// UpdateConnectionState The connection state has changed +type UpdateConnectionState struct { + tdCommon + State ConnectionState `json:"state"` // The new connection state +} + +// MessageType return the string telegram-type of UpdateConnectionState +func (updateConnectionState *UpdateConnectionState) MessageType() string { + return "updateConnectionState" +} + +// NewUpdateConnectionState creates a new UpdateConnectionState +// +// @param state The new connection state +func NewUpdateConnectionState(state ConnectionState) *UpdateConnectionState { + updateConnectionStateTemp := UpdateConnectionState{ + tdCommon: tdCommon{Type: "updateConnectionState"}, + State: state, + } + + return &updateConnectionStateTemp +} + +// UnmarshalJSON unmarshal to json +func (updateConnectionState *UpdateConnectionState) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateConnectionState.tdCommon = tempObj.tdCommon + + fieldState, _ := unmarshalConnectionState(objMap["state"]) + updateConnectionState.State = fieldState + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateConnectionState *UpdateConnectionState) GetUpdateEnum() UpdateEnum { + return UpdateConnectionStateType +} + +// UpdateTermsOfService New terms of service must be accepted by the user. If the terms of service are declined, then the deleteAccount method should be called with the reason "Decline ToS update" +type UpdateTermsOfService struct { + tdCommon + TermsOfServiceID string `json:"terms_of_service_id"` // Identifier of the terms of service + TermsOfService *TermsOfService `json:"terms_of_service"` // The new terms of service +} + +// MessageType return the string telegram-type of UpdateTermsOfService +func (updateTermsOfService *UpdateTermsOfService) MessageType() string { + return "updateTermsOfService" +} + +// NewUpdateTermsOfService creates a new UpdateTermsOfService +// +// @param termsOfServiceID Identifier of the terms of service +// @param termsOfService The new terms of service +func NewUpdateTermsOfService(termsOfServiceID string, termsOfService *TermsOfService) *UpdateTermsOfService { + updateTermsOfServiceTemp := UpdateTermsOfService{ + tdCommon: tdCommon{Type: "updateTermsOfService"}, + TermsOfServiceID: termsOfServiceID, + TermsOfService: termsOfService, + } + + return &updateTermsOfServiceTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateTermsOfService *UpdateTermsOfService) GetUpdateEnum() UpdateEnum { + return UpdateTermsOfServiceType +} + +// UpdateNewInlineQuery A new incoming inline query; for bots only +type UpdateNewInlineQuery struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + UserLocation *Location `json:"user_location"` // User location, provided by the client; may be null + Query string `json:"query"` // Text of the query + Offset string `json:"offset"` // Offset of the first entry to return +} + +// MessageType return the string telegram-type of UpdateNewInlineQuery +func (updateNewInlineQuery *UpdateNewInlineQuery) MessageType() string { + return "updateNewInlineQuery" +} + +// NewUpdateNewInlineQuery creates a new UpdateNewInlineQuery +// +// @param iD Unique query identifier +// @param senderUserID Identifier of the user who sent the query +// @param userLocation User location, provided by the client; may be null +// @param query Text of the query +// @param offset Offset of the first entry to return +func NewUpdateNewInlineQuery(iD JSONInt64, senderUserID int32, userLocation *Location, query string, offset string) *UpdateNewInlineQuery { + updateNewInlineQueryTemp := UpdateNewInlineQuery{ + tdCommon: tdCommon{Type: "updateNewInlineQuery"}, + ID: iD, + SenderUserID: senderUserID, + UserLocation: userLocation, + Query: query, + Offset: offset, + } + + return &updateNewInlineQueryTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewInlineQuery *UpdateNewInlineQuery) GetUpdateEnum() UpdateEnum { + return UpdateNewInlineQueryType +} + +// UpdateNewChosenInlineResult The user has chosen a result of an inline query; for bots only +type UpdateNewChosenInlineResult struct { + tdCommon + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + UserLocation *Location `json:"user_location"` // User location, provided by the client; may be null + Query string `json:"query"` // Text of the query + ResultID string `json:"result_id"` // Identifier of the chosen result + InlineMessageID string `json:"inline_message_id"` // Identifier of the sent inline message, if known +} + +// MessageType return the string telegram-type of UpdateNewChosenInlineResult +func (updateNewChosenInlineResult *UpdateNewChosenInlineResult) MessageType() string { + return "updateNewChosenInlineResult" +} + +// NewUpdateNewChosenInlineResult creates a new UpdateNewChosenInlineResult +// +// @param senderUserID Identifier of the user who sent the query +// @param userLocation User location, provided by the client; may be null +// @param query Text of the query +// @param resultID Identifier of the chosen result +// @param inlineMessageID Identifier of the sent inline message, if known +func NewUpdateNewChosenInlineResult(senderUserID int32, userLocation *Location, query string, resultID string, inlineMessageID string) *UpdateNewChosenInlineResult { + updateNewChosenInlineResultTemp := UpdateNewChosenInlineResult{ + tdCommon: tdCommon{Type: "updateNewChosenInlineResult"}, + SenderUserID: senderUserID, + UserLocation: userLocation, + Query: query, + ResultID: resultID, + InlineMessageID: inlineMessageID, + } + + return &updateNewChosenInlineResultTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewChosenInlineResult *UpdateNewChosenInlineResult) GetUpdateEnum() UpdateEnum { + return UpdateNewChosenInlineResultType +} + +// UpdateNewCallbackQuery A new incoming callback query; for bots only +type UpdateNewCallbackQuery struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + ChatID int64 `json:"chat_id"` // Identifier of the chat, in which the query was sent + MessageID int64 `json:"message_id"` // Identifier of the message, from which the query originated + ChatInstance JSONInt64 `json:"chat_instance"` // Identifier that uniquely corresponds to the chat to which the message was sent + Payload CallbackQueryPayload `json:"payload"` // Query payload +} + +// MessageType return the string telegram-type of UpdateNewCallbackQuery +func (updateNewCallbackQuery *UpdateNewCallbackQuery) MessageType() string { + return "updateNewCallbackQuery" +} + +// NewUpdateNewCallbackQuery creates a new UpdateNewCallbackQuery +// +// @param iD Unique query identifier +// @param senderUserID Identifier of the user who sent the query +// @param chatID Identifier of the chat, in which the query was sent +// @param messageID Identifier of the message, from which the query originated +// @param chatInstance Identifier that uniquely corresponds to the chat to which the message was sent +// @param payload Query payload +func NewUpdateNewCallbackQuery(iD JSONInt64, senderUserID int32, chatID int64, messageID int64, chatInstance JSONInt64, payload CallbackQueryPayload) *UpdateNewCallbackQuery { + updateNewCallbackQueryTemp := UpdateNewCallbackQuery{ + tdCommon: tdCommon{Type: "updateNewCallbackQuery"}, + ID: iD, + SenderUserID: senderUserID, + ChatID: chatID, + MessageID: messageID, + ChatInstance: chatInstance, + Payload: payload, + } + + return &updateNewCallbackQueryTemp +} + +// UnmarshalJSON unmarshal to json +func (updateNewCallbackQuery *UpdateNewCallbackQuery) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + ChatID int64 `json:"chat_id"` // Identifier of the chat, in which the query was sent + MessageID int64 `json:"message_id"` // Identifier of the message, from which the query originated + ChatInstance JSONInt64 `json:"chat_instance"` // Identifier that uniquely corresponds to the chat to which the message was sent + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateNewCallbackQuery.tdCommon = tempObj.tdCommon + updateNewCallbackQuery.ID = tempObj.ID + updateNewCallbackQuery.SenderUserID = tempObj.SenderUserID + updateNewCallbackQuery.ChatID = tempObj.ChatID + updateNewCallbackQuery.MessageID = tempObj.MessageID + updateNewCallbackQuery.ChatInstance = tempObj.ChatInstance + + fieldPayload, _ := unmarshalCallbackQueryPayload(objMap["payload"]) + updateNewCallbackQuery.Payload = fieldPayload + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateNewCallbackQuery *UpdateNewCallbackQuery) GetUpdateEnum() UpdateEnum { + return UpdateNewCallbackQueryType +} + +// UpdateNewInlineCallbackQuery A new incoming callback query from a message sent via a bot; for bots only +type UpdateNewInlineCallbackQuery struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + InlineMessageID string `json:"inline_message_id"` // Identifier of the inline message, from which the query originated + ChatInstance JSONInt64 `json:"chat_instance"` // An identifier uniquely corresponding to the chat a message was sent to + Payload CallbackQueryPayload `json:"payload"` // Query payload +} + +// MessageType return the string telegram-type of UpdateNewInlineCallbackQuery +func (updateNewInlineCallbackQuery *UpdateNewInlineCallbackQuery) MessageType() string { + return "updateNewInlineCallbackQuery" +} + +// NewUpdateNewInlineCallbackQuery creates a new UpdateNewInlineCallbackQuery +// +// @param iD Unique query identifier +// @param senderUserID Identifier of the user who sent the query +// @param inlineMessageID Identifier of the inline message, from which the query originated +// @param chatInstance An identifier uniquely corresponding to the chat a message was sent to +// @param payload Query payload +func NewUpdateNewInlineCallbackQuery(iD JSONInt64, senderUserID int32, inlineMessageID string, chatInstance JSONInt64, payload CallbackQueryPayload) *UpdateNewInlineCallbackQuery { + updateNewInlineCallbackQueryTemp := UpdateNewInlineCallbackQuery{ + tdCommon: tdCommon{Type: "updateNewInlineCallbackQuery"}, + ID: iD, + SenderUserID: senderUserID, + InlineMessageID: inlineMessageID, + ChatInstance: chatInstance, + Payload: payload, + } + + return &updateNewInlineCallbackQueryTemp +} + +// UnmarshalJSON unmarshal to json +func (updateNewInlineCallbackQuery *UpdateNewInlineCallbackQuery) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + InlineMessageID string `json:"inline_message_id"` // Identifier of the inline message, from which the query originated + ChatInstance JSONInt64 `json:"chat_instance"` // An identifier uniquely corresponding to the chat a message was sent to + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateNewInlineCallbackQuery.tdCommon = tempObj.tdCommon + updateNewInlineCallbackQuery.ID = tempObj.ID + updateNewInlineCallbackQuery.SenderUserID = tempObj.SenderUserID + updateNewInlineCallbackQuery.InlineMessageID = tempObj.InlineMessageID + updateNewInlineCallbackQuery.ChatInstance = tempObj.ChatInstance + + fieldPayload, _ := unmarshalCallbackQueryPayload(objMap["payload"]) + updateNewInlineCallbackQuery.Payload = fieldPayload + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateNewInlineCallbackQuery *UpdateNewInlineCallbackQuery) GetUpdateEnum() UpdateEnum { + return UpdateNewInlineCallbackQueryType +} + +// UpdateNewShippingQuery A new incoming shipping query; for bots only. Only for invoices with flexible price +type UpdateNewShippingQuery struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + InvoicePayload string `json:"invoice_payload"` // Invoice payload + ShippingAddress *Address `json:"shipping_address"` // User shipping address +} + +// MessageType return the string telegram-type of UpdateNewShippingQuery +func (updateNewShippingQuery *UpdateNewShippingQuery) MessageType() string { + return "updateNewShippingQuery" +} + +// NewUpdateNewShippingQuery creates a new UpdateNewShippingQuery +// +// @param iD Unique query identifier +// @param senderUserID Identifier of the user who sent the query +// @param invoicePayload Invoice payload +// @param shippingAddress User shipping address +func NewUpdateNewShippingQuery(iD JSONInt64, senderUserID int32, invoicePayload string, shippingAddress *Address) *UpdateNewShippingQuery { + updateNewShippingQueryTemp := UpdateNewShippingQuery{ + tdCommon: tdCommon{Type: "updateNewShippingQuery"}, + ID: iD, + SenderUserID: senderUserID, + InvoicePayload: invoicePayload, + ShippingAddress: shippingAddress, + } + + return &updateNewShippingQueryTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewShippingQuery *UpdateNewShippingQuery) GetUpdateEnum() UpdateEnum { + return UpdateNewShippingQueryType +} + +// UpdateNewPreCheckoutQuery A new incoming pre-checkout query; for bots only. Contains full information about a checkout +type UpdateNewPreCheckoutQuery struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int32 `json:"sender_user_id"` // Identifier of the user who sent the query + Currency string `json:"currency"` // Currency for the product price + TotalAmount int64 `json:"total_amount"` // Total price for the product, in the minimal quantity of the currency + InvoicePayload []byte `json:"invoice_payload"` // Invoice payload + ShippingOptionID string `json:"shipping_option_id"` // Identifier of a shipping option chosen by the user; may be empty if not applicable + OrderInfo *OrderInfo `json:"order_info"` // Information about the order; may be null +} + +// MessageType return the string telegram-type of UpdateNewPreCheckoutQuery +func (updateNewPreCheckoutQuery *UpdateNewPreCheckoutQuery) MessageType() string { + return "updateNewPreCheckoutQuery" +} + +// NewUpdateNewPreCheckoutQuery creates a new UpdateNewPreCheckoutQuery +// +// @param iD Unique query identifier +// @param senderUserID Identifier of the user who sent the query +// @param currency Currency for the product price +// @param totalAmount Total price for the product, in the minimal quantity of the currency +// @param invoicePayload Invoice payload +// @param shippingOptionID Identifier of a shipping option chosen by the user; may be empty if not applicable +// @param orderInfo Information about the order; may be null +func NewUpdateNewPreCheckoutQuery(iD JSONInt64, senderUserID int32, currency string, totalAmount int64, invoicePayload []byte, shippingOptionID string, orderInfo *OrderInfo) *UpdateNewPreCheckoutQuery { + updateNewPreCheckoutQueryTemp := UpdateNewPreCheckoutQuery{ + tdCommon: tdCommon{Type: "updateNewPreCheckoutQuery"}, + ID: iD, + SenderUserID: senderUserID, + Currency: currency, + TotalAmount: totalAmount, + InvoicePayload: invoicePayload, + ShippingOptionID: shippingOptionID, + OrderInfo: orderInfo, + } + + return &updateNewPreCheckoutQueryTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewPreCheckoutQuery *UpdateNewPreCheckoutQuery) GetUpdateEnum() UpdateEnum { + return UpdateNewPreCheckoutQueryType +} + +// UpdateNewCustomEvent A new incoming event; for bots only +type UpdateNewCustomEvent struct { + tdCommon + Event string `json:"event"` // A JSON-serialized event +} + +// MessageType return the string telegram-type of UpdateNewCustomEvent +func (updateNewCustomEvent *UpdateNewCustomEvent) MessageType() string { + return "updateNewCustomEvent" +} + +// NewUpdateNewCustomEvent creates a new UpdateNewCustomEvent +// +// @param event A JSON-serialized event +func NewUpdateNewCustomEvent(event string) *UpdateNewCustomEvent { + updateNewCustomEventTemp := UpdateNewCustomEvent{ + tdCommon: tdCommon{Type: "updateNewCustomEvent"}, + Event: event, + } + + return &updateNewCustomEventTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewCustomEvent *UpdateNewCustomEvent) GetUpdateEnum() UpdateEnum { + return UpdateNewCustomEventType +} + +// UpdateNewCustomQuery A new incoming query; for bots only +type UpdateNewCustomQuery struct { + tdCommon + ID JSONInt64 `json:"id"` // The query identifier + Data string `json:"data"` // JSON-serialized query data + Timeout int32 `json:"timeout"` // Query timeout +} + +// MessageType return the string telegram-type of UpdateNewCustomQuery +func (updateNewCustomQuery *UpdateNewCustomQuery) MessageType() string { + return "updateNewCustomQuery" +} + +// NewUpdateNewCustomQuery creates a new UpdateNewCustomQuery +// +// @param iD The query identifier +// @param data JSON-serialized query data +// @param timeout Query timeout +func NewUpdateNewCustomQuery(iD JSONInt64, data string, timeout int32) *UpdateNewCustomQuery { + updateNewCustomQueryTemp := UpdateNewCustomQuery{ + tdCommon: tdCommon{Type: "updateNewCustomQuery"}, + ID: iD, + Data: data, + Timeout: timeout, + } + + return &updateNewCustomQueryTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewCustomQuery *UpdateNewCustomQuery) GetUpdateEnum() UpdateEnum { + return UpdateNewCustomQueryType +} + +// TestInt A simple object containing a number; for testing only +type TestInt struct { + tdCommon + Value int32 `json:"value"` // Number +} + +// MessageType return the string telegram-type of TestInt +func (testInt *TestInt) MessageType() string { + return "testInt" +} + +// NewTestInt creates a new TestInt +// +// @param value Number +func NewTestInt(value int32) *TestInt { + testIntTemp := TestInt{ + tdCommon: tdCommon{Type: "testInt"}, + Value: value, + } + + return &testIntTemp +} + +// TestString A simple object containing a string; for testing only +type TestString struct { + tdCommon + Value string `json:"value"` // String +} + +// MessageType return the string telegram-type of TestString +func (testString *TestString) MessageType() string { + return "testString" +} + +// NewTestString creates a new TestString +// +// @param value String +func NewTestString(value string) *TestString { + testStringTemp := TestString{ + tdCommon: tdCommon{Type: "testString"}, + Value: value, + } + + return &testStringTemp +} + +// TestBytes A simple object containing a sequence of bytes; for testing only +type TestBytes struct { + tdCommon + Value []byte `json:"value"` // Bytes +} + +// MessageType return the string telegram-type of TestBytes +func (testBytes *TestBytes) MessageType() string { + return "testBytes" +} + +// NewTestBytes creates a new TestBytes +// +// @param value Bytes +func NewTestBytes(value []byte) *TestBytes { + testBytesTemp := TestBytes{ + tdCommon: tdCommon{Type: "testBytes"}, + Value: value, + } + + return &testBytesTemp +} + +// TestVectorInt A simple object containing a vector of numbers; for testing only +type TestVectorInt struct { + tdCommon + Value []int32 `json:"value"` // Vector of numbers +} + +// MessageType return the string telegram-type of TestVectorInt +func (testVectorInt *TestVectorInt) MessageType() string { + return "testVectorInt" +} + +// NewTestVectorInt creates a new TestVectorInt +// +// @param value Vector of numbers +func NewTestVectorInt(value []int32) *TestVectorInt { + testVectorIntTemp := TestVectorInt{ + tdCommon: tdCommon{Type: "testVectorInt"}, + Value: value, + } + + return &testVectorIntTemp +} + +// TestVectorIntObject A simple object containing a vector of objects that hold a number; for testing only +type TestVectorIntObject struct { + tdCommon + Value []TestInt `json:"value"` // Vector of objects +} + +// MessageType return the string telegram-type of TestVectorIntObject +func (testVectorIntObject *TestVectorIntObject) MessageType() string { + return "testVectorIntObject" +} + +// NewTestVectorIntObject creates a new TestVectorIntObject +// +// @param value Vector of objects +func NewTestVectorIntObject(value []TestInt) *TestVectorIntObject { + testVectorIntObjectTemp := TestVectorIntObject{ + tdCommon: tdCommon{Type: "testVectorIntObject"}, + Value: value, + } + + return &testVectorIntObjectTemp +} + +// TestVectorString A simple object containing a vector of strings; for testing only +type TestVectorString struct { + tdCommon + Value []string `json:"value"` // Vector of strings +} + +// MessageType return the string telegram-type of TestVectorString +func (testVectorString *TestVectorString) MessageType() string { + return "testVectorString" +} + +// NewTestVectorString creates a new TestVectorString +// +// @param value Vector of strings +func NewTestVectorString(value []string) *TestVectorString { + testVectorStringTemp := TestVectorString{ + tdCommon: tdCommon{Type: "testVectorString"}, + Value: value, + } + + return &testVectorStringTemp +} + +// TestVectorStringObject A simple object containing a vector of objects that hold a string; for testing only +type TestVectorStringObject struct { + tdCommon + Value []TestString `json:"value"` // Vector of objects +} + +// MessageType return the string telegram-type of TestVectorStringObject +func (testVectorStringObject *TestVectorStringObject) MessageType() string { + return "testVectorStringObject" +} + +// NewTestVectorStringObject creates a new TestVectorStringObject +// +// @param value Vector of objects +func NewTestVectorStringObject(value []TestString) *TestVectorStringObject { + testVectorStringObjectTemp := TestVectorStringObject{ + tdCommon: tdCommon{Type: "testVectorStringObject"}, + Value: value, + } + + return &testVectorStringObjectTemp +} + +func unmarshalAuthenticationCodeType(rawMsg *json.RawMessage) (AuthenticationCodeType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch AuthenticationCodeTypeEnum(objMap["@type"].(string)) { + case AuthenticationCodeTypeTelegramMessageType: + var authenticationCodeTypeTelegramMessage AuthenticationCodeTypeTelegramMessage + err := json.Unmarshal(*rawMsg, &authenticationCodeTypeTelegramMessage) + return &authenticationCodeTypeTelegramMessage, err + + case AuthenticationCodeTypeSmsType: + var authenticationCodeTypeSms AuthenticationCodeTypeSms + err := json.Unmarshal(*rawMsg, &authenticationCodeTypeSms) + return &authenticationCodeTypeSms, err + + case AuthenticationCodeTypeCallType: + var authenticationCodeTypeCall AuthenticationCodeTypeCall + err := json.Unmarshal(*rawMsg, &authenticationCodeTypeCall) + return &authenticationCodeTypeCall, err + + case AuthenticationCodeTypeFlashCallType: + var authenticationCodeTypeFlashCall AuthenticationCodeTypeFlashCall + err := json.Unmarshal(*rawMsg, &authenticationCodeTypeFlashCall) + return &authenticationCodeTypeFlashCall, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalAuthorizationState(rawMsg *json.RawMessage) (AuthorizationState, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch AuthorizationStateEnum(objMap["@type"].(string)) { + case AuthorizationStateWaitTdlibParametersType: + var authorizationStateWaitTdlibParameters AuthorizationStateWaitTdlibParameters + err := json.Unmarshal(*rawMsg, &authorizationStateWaitTdlibParameters) + return &authorizationStateWaitTdlibParameters, err + + case AuthorizationStateWaitEncryptionKeyType: + var authorizationStateWaitEncryptionKey AuthorizationStateWaitEncryptionKey + err := json.Unmarshal(*rawMsg, &authorizationStateWaitEncryptionKey) + return &authorizationStateWaitEncryptionKey, err + + case AuthorizationStateWaitPhoneNumberType: + var authorizationStateWaitPhoneNumber AuthorizationStateWaitPhoneNumber + err := json.Unmarshal(*rawMsg, &authorizationStateWaitPhoneNumber) + return &authorizationStateWaitPhoneNumber, err + + case AuthorizationStateWaitCodeType: + var authorizationStateWaitCode AuthorizationStateWaitCode + err := json.Unmarshal(*rawMsg, &authorizationStateWaitCode) + return &authorizationStateWaitCode, err + + case AuthorizationStateWaitPasswordType: + var authorizationStateWaitPassword AuthorizationStateWaitPassword + err := json.Unmarshal(*rawMsg, &authorizationStateWaitPassword) + return &authorizationStateWaitPassword, err + + case AuthorizationStateReadyType: + var authorizationStateReady AuthorizationStateReady + err := json.Unmarshal(*rawMsg, &authorizationStateReady) + return &authorizationStateReady, err + + case AuthorizationStateLoggingOutType: + var authorizationStateLoggingOut AuthorizationStateLoggingOut + err := json.Unmarshal(*rawMsg, &authorizationStateLoggingOut) + return &authorizationStateLoggingOut, err + + case AuthorizationStateClosingType: + var authorizationStateClosing AuthorizationStateClosing + err := json.Unmarshal(*rawMsg, &authorizationStateClosing) + return &authorizationStateClosing, err + + case AuthorizationStateClosedType: + var authorizationStateClosed AuthorizationStateClosed + err := json.Unmarshal(*rawMsg, &authorizationStateClosed) + return &authorizationStateClosed, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInputFile(rawMsg *json.RawMessage) (InputFile, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputFileEnum(objMap["@type"].(string)) { + case InputFileIDType: + var inputFileID InputFileID + err := json.Unmarshal(*rawMsg, &inputFileID) + return &inputFileID, err + + case InputFileRemoteType: + var inputFileRemote InputFileRemote + err := json.Unmarshal(*rawMsg, &inputFileRemote) + return &inputFileRemote, err + + case InputFileLocalType: + var inputFileLocal InputFileLocal + err := json.Unmarshal(*rawMsg, &inputFileLocal) + return &inputFileLocal, err + + case InputFileGeneratedType: + var inputFileGenerated InputFileGenerated + err := json.Unmarshal(*rawMsg, &inputFileGenerated) + return &inputFileGenerated, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalMaskPoint(rawMsg *json.RawMessage) (MaskPoint, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MaskPointEnum(objMap["@type"].(string)) { + case MaskPointForeheadType: + var maskPointForehead MaskPointForehead + err := json.Unmarshal(*rawMsg, &maskPointForehead) + return &maskPointForehead, err + + case MaskPointEyesType: + var maskPointEyes MaskPointEyes + err := json.Unmarshal(*rawMsg, &maskPointEyes) + return &maskPointEyes, err + + case MaskPointMouthType: + var maskPointMouth MaskPointMouth + err := json.Unmarshal(*rawMsg, &maskPointMouth) + return &maskPointMouth, err + + case MaskPointChinType: + var maskPointChin MaskPointChin + err := json.Unmarshal(*rawMsg, &maskPointChin) + return &maskPointChin, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalLinkState(rawMsg *json.RawMessage) (LinkState, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch LinkStateEnum(objMap["@type"].(string)) { + case LinkStateNoneType: + var linkStateNone LinkStateNone + err := json.Unmarshal(*rawMsg, &linkStateNone) + return &linkStateNone, err + + case LinkStateKnowsPhoneNumberType: + var linkStateKnowsPhoneNumber LinkStateKnowsPhoneNumber + err := json.Unmarshal(*rawMsg, &linkStateKnowsPhoneNumber) + return &linkStateKnowsPhoneNumber, err + + case LinkStateIsContactType: + var linkStateIsContact LinkStateIsContact + err := json.Unmarshal(*rawMsg, &linkStateIsContact) + return &linkStateIsContact, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalUserType(rawMsg *json.RawMessage) (UserType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch UserTypeEnum(objMap["@type"].(string)) { + case UserTypeRegularType: + var userTypeRegular UserTypeRegular + err := json.Unmarshal(*rawMsg, &userTypeRegular) + return &userTypeRegular, err + + case UserTypeDeletedType: + var userTypeDeleted UserTypeDeleted + err := json.Unmarshal(*rawMsg, &userTypeDeleted) + return &userTypeDeleted, err + + case UserTypeBotType: + var userTypeBot UserTypeBot + err := json.Unmarshal(*rawMsg, &userTypeBot) + return &userTypeBot, err + + case UserTypeUnknownType: + var userTypeUnknown UserTypeUnknown + err := json.Unmarshal(*rawMsg, &userTypeUnknown) + return &userTypeUnknown, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalChatMemberStatus(rawMsg *json.RawMessage) (ChatMemberStatus, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatMemberStatusEnum(objMap["@type"].(string)) { + case ChatMemberStatusCreatorType: + var chatMemberStatusCreator ChatMemberStatusCreator + err := json.Unmarshal(*rawMsg, &chatMemberStatusCreator) + return &chatMemberStatusCreator, err + + case ChatMemberStatusAdministratorType: + var chatMemberStatusAdministrator ChatMemberStatusAdministrator + err := json.Unmarshal(*rawMsg, &chatMemberStatusAdministrator) + return &chatMemberStatusAdministrator, err + + case ChatMemberStatusMemberType: + var chatMemberStatusMember ChatMemberStatusMember + err := json.Unmarshal(*rawMsg, &chatMemberStatusMember) + return &chatMemberStatusMember, err + + case ChatMemberStatusRestrictedType: + var chatMemberStatusRestricted ChatMemberStatusRestricted + err := json.Unmarshal(*rawMsg, &chatMemberStatusRestricted) + return &chatMemberStatusRestricted, err + + case ChatMemberStatusLeftType: + var chatMemberStatusLeft ChatMemberStatusLeft + err := json.Unmarshal(*rawMsg, &chatMemberStatusLeft) + return &chatMemberStatusLeft, err + + case ChatMemberStatusBannedType: + var chatMemberStatusBanned ChatMemberStatusBanned + err := json.Unmarshal(*rawMsg, &chatMemberStatusBanned) + return &chatMemberStatusBanned, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalChatMembersFilter(rawMsg *json.RawMessage) (ChatMembersFilter, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatMembersFilterEnum(objMap["@type"].(string)) { + case ChatMembersFilterAdministratorsType: + var chatMembersFilterAdministrators ChatMembersFilterAdministrators + err := json.Unmarshal(*rawMsg, &chatMembersFilterAdministrators) + return &chatMembersFilterAdministrators, err + + case ChatMembersFilterMembersType: + var chatMembersFilterMembers ChatMembersFilterMembers + err := json.Unmarshal(*rawMsg, &chatMembersFilterMembers) + return &chatMembersFilterMembers, err + + case ChatMembersFilterRestrictedType: + var chatMembersFilterRestricted ChatMembersFilterRestricted + err := json.Unmarshal(*rawMsg, &chatMembersFilterRestricted) + return &chatMembersFilterRestricted, err + + case ChatMembersFilterBannedType: + var chatMembersFilterBanned ChatMembersFilterBanned + err := json.Unmarshal(*rawMsg, &chatMembersFilterBanned) + return &chatMembersFilterBanned, err + + case ChatMembersFilterBotsType: + var chatMembersFilterBots ChatMembersFilterBots + err := json.Unmarshal(*rawMsg, &chatMembersFilterBots) + return &chatMembersFilterBots, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalSupergroupMembersFilter(rawMsg *json.RawMessage) (SupergroupMembersFilter, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch SupergroupMembersFilterEnum(objMap["@type"].(string)) { + case SupergroupMembersFilterRecentType: + var supergroupMembersFilterRecent SupergroupMembersFilterRecent + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterRecent) + return &supergroupMembersFilterRecent, err + + case SupergroupMembersFilterAdministratorsType: + var supergroupMembersFilterAdministrators SupergroupMembersFilterAdministrators + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterAdministrators) + return &supergroupMembersFilterAdministrators, err + + case SupergroupMembersFilterSearchType: + var supergroupMembersFilterSearch SupergroupMembersFilterSearch + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterSearch) + return &supergroupMembersFilterSearch, err + + case SupergroupMembersFilterRestrictedType: + var supergroupMembersFilterRestricted SupergroupMembersFilterRestricted + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterRestricted) + return &supergroupMembersFilterRestricted, err + + case SupergroupMembersFilterBannedType: + var supergroupMembersFilterBanned SupergroupMembersFilterBanned + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterBanned) + return &supergroupMembersFilterBanned, err + + case SupergroupMembersFilterBotsType: + var supergroupMembersFilterBots SupergroupMembersFilterBots + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterBots) + return &supergroupMembersFilterBots, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalSecretChatState(rawMsg *json.RawMessage) (SecretChatState, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch SecretChatStateEnum(objMap["@type"].(string)) { + case SecretChatStatePendingType: + var secretChatStatePending SecretChatStatePending + err := json.Unmarshal(*rawMsg, &secretChatStatePending) + return &secretChatStatePending, err + + case SecretChatStateReadyType: + var secretChatStateReady SecretChatStateReady + err := json.Unmarshal(*rawMsg, &secretChatStateReady) + return &secretChatStateReady, err + + case SecretChatStateClosedType: + var secretChatStateClosed SecretChatStateClosed + err := json.Unmarshal(*rawMsg, &secretChatStateClosed) + return &secretChatStateClosed, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalMessageForwardInfo(rawMsg *json.RawMessage) (MessageForwardInfo, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MessageForwardInfoEnum(objMap["@type"].(string)) { + case MessageForwardedFromUserType: + var messageForwardedFromUser MessageForwardedFromUser + err := json.Unmarshal(*rawMsg, &messageForwardedFromUser) + return &messageForwardedFromUser, err + + case MessageForwardedPostType: + var messageForwardedPost MessageForwardedPost + err := json.Unmarshal(*rawMsg, &messageForwardedPost) + return &messageForwardedPost, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalMessageSendingState(rawMsg *json.RawMessage) (MessageSendingState, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MessageSendingStateEnum(objMap["@type"].(string)) { + case MessageSendingStatePendingType: + var messageSendingStatePending MessageSendingStatePending + err := json.Unmarshal(*rawMsg, &messageSendingStatePending) + return &messageSendingStatePending, err + + case MessageSendingStateFailedType: + var messageSendingStateFailed MessageSendingStateFailed + err := json.Unmarshal(*rawMsg, &messageSendingStateFailed) + return &messageSendingStateFailed, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalNotificationSettingsScope(rawMsg *json.RawMessage) (NotificationSettingsScope, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch NotificationSettingsScopeEnum(objMap["@type"].(string)) { + case NotificationSettingsScopePrivateChatsType: + var notificationSettingsScopePrivateChats NotificationSettingsScopePrivateChats + err := json.Unmarshal(*rawMsg, ¬ificationSettingsScopePrivateChats) + return ¬ificationSettingsScopePrivateChats, err + + case NotificationSettingsScopeGroupChatsType: + var notificationSettingsScopeGroupChats NotificationSettingsScopeGroupChats + err := json.Unmarshal(*rawMsg, ¬ificationSettingsScopeGroupChats) + return ¬ificationSettingsScopeGroupChats, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalChatType(rawMsg *json.RawMessage) (ChatType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatTypeEnum(objMap["@type"].(string)) { + case ChatTypePrivateType: + var chatTypePrivate ChatTypePrivate + err := json.Unmarshal(*rawMsg, &chatTypePrivate) + return &chatTypePrivate, err + + case ChatTypeBasicGroupType: + var chatTypeBasicGroup ChatTypeBasicGroup + err := json.Unmarshal(*rawMsg, &chatTypeBasicGroup) + return &chatTypeBasicGroup, err + + case ChatTypeSupergroupType: + var chatTypeSupergroup ChatTypeSupergroup + err := json.Unmarshal(*rawMsg, &chatTypeSupergroup) + return &chatTypeSupergroup, err + + case ChatTypeSecretType: + var chatTypeSecret ChatTypeSecret + err := json.Unmarshal(*rawMsg, &chatTypeSecret) + return &chatTypeSecret, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalKeyboardButtonType(rawMsg *json.RawMessage) (KeyboardButtonType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch KeyboardButtonTypeEnum(objMap["@type"].(string)) { + case KeyboardButtonTypeTextType: + var keyboardButtonTypeText KeyboardButtonTypeText + err := json.Unmarshal(*rawMsg, &keyboardButtonTypeText) + return &keyboardButtonTypeText, err + + case KeyboardButtonTypeRequestPhoneNumberType: + var keyboardButtonTypeRequestPhoneNumber KeyboardButtonTypeRequestPhoneNumber + err := json.Unmarshal(*rawMsg, &keyboardButtonTypeRequestPhoneNumber) + return &keyboardButtonTypeRequestPhoneNumber, err + + case KeyboardButtonTypeRequestLocationType: + var keyboardButtonTypeRequestLocation KeyboardButtonTypeRequestLocation + err := json.Unmarshal(*rawMsg, &keyboardButtonTypeRequestLocation) + return &keyboardButtonTypeRequestLocation, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInlineKeyboardButtonType(rawMsg *json.RawMessage) (InlineKeyboardButtonType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InlineKeyboardButtonTypeEnum(objMap["@type"].(string)) { + case InlineKeyboardButtonTypeURLType: + var inlineKeyboardButtonTypeURL InlineKeyboardButtonTypeURL + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeURL) + return &inlineKeyboardButtonTypeURL, err + + case InlineKeyboardButtonTypeCallbackType: + var inlineKeyboardButtonTypeCallback InlineKeyboardButtonTypeCallback + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeCallback) + return &inlineKeyboardButtonTypeCallback, err + + case InlineKeyboardButtonTypeCallbackGameType: + var inlineKeyboardButtonTypeCallbackGame InlineKeyboardButtonTypeCallbackGame + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeCallbackGame) + return &inlineKeyboardButtonTypeCallbackGame, err + + case InlineKeyboardButtonTypeSwitchInlineType: + var inlineKeyboardButtonTypeSwitchInline InlineKeyboardButtonTypeSwitchInline + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeSwitchInline) + return &inlineKeyboardButtonTypeSwitchInline, err + + case InlineKeyboardButtonTypeBuyType: + var inlineKeyboardButtonTypeBuy InlineKeyboardButtonTypeBuy + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeBuy) + return &inlineKeyboardButtonTypeBuy, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalReplyMarkup(rawMsg *json.RawMessage) (ReplyMarkup, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ReplyMarkupEnum(objMap["@type"].(string)) { + case ReplyMarkupRemoveKeyboardType: + var replyMarkupRemoveKeyboard ReplyMarkupRemoveKeyboard + err := json.Unmarshal(*rawMsg, &replyMarkupRemoveKeyboard) + return &replyMarkupRemoveKeyboard, err + + case ReplyMarkupForceReplyType: + var replyMarkupForceReply ReplyMarkupForceReply + err := json.Unmarshal(*rawMsg, &replyMarkupForceReply) + return &replyMarkupForceReply, err + + case ReplyMarkupShowKeyboardType: + var replyMarkupShowKeyboard ReplyMarkupShowKeyboard + err := json.Unmarshal(*rawMsg, &replyMarkupShowKeyboard) + return &replyMarkupShowKeyboard, err + + case ReplyMarkupInlineKeyboardType: + var replyMarkupInlineKeyboard ReplyMarkupInlineKeyboard + err := json.Unmarshal(*rawMsg, &replyMarkupInlineKeyboard) + return &replyMarkupInlineKeyboard, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalRichText(rawMsg *json.RawMessage) (RichText, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch RichTextEnum(objMap["@type"].(string)) { + case RichTextPlainType: + var richTextPlain RichTextPlain + err := json.Unmarshal(*rawMsg, &richTextPlain) + return &richTextPlain, err + + case RichTextBoldType: + var richTextBold RichTextBold + err := json.Unmarshal(*rawMsg, &richTextBold) + return &richTextBold, err + + case RichTextItalicType: + var richTextItalic RichTextItalic + err := json.Unmarshal(*rawMsg, &richTextItalic) + return &richTextItalic, err + + case RichTextUnderlineType: + var richTextUnderline RichTextUnderline + err := json.Unmarshal(*rawMsg, &richTextUnderline) + return &richTextUnderline, err + + case RichTextStrikethroughType: + var richTextStrikethrough RichTextStrikethrough + err := json.Unmarshal(*rawMsg, &richTextStrikethrough) + return &richTextStrikethrough, err + + case RichTextFixedType: + var richTextFixed RichTextFixed + err := json.Unmarshal(*rawMsg, &richTextFixed) + return &richTextFixed, err + + case RichTextURLType: + var richTextURL RichTextURL + err := json.Unmarshal(*rawMsg, &richTextURL) + return &richTextURL, err + + case RichTextEmailAddressType: + var richTextEmailAddress RichTextEmailAddress + err := json.Unmarshal(*rawMsg, &richTextEmailAddress) + return &richTextEmailAddress, err + + case RichTextsType: + var richTexts RichTexts + err := json.Unmarshal(*rawMsg, &richTexts) + return &richTexts, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalPageBlock(rawMsg *json.RawMessage) (PageBlock, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PageBlockEnum(objMap["@type"].(string)) { + case PageBlockTitleType: + var pageBlockTitle PageBlockTitle + err := json.Unmarshal(*rawMsg, &pageBlockTitle) + return &pageBlockTitle, err + + case PageBlockSubtitleType: + var pageBlockSubtitle PageBlockSubtitle + err := json.Unmarshal(*rawMsg, &pageBlockSubtitle) + return &pageBlockSubtitle, err + + case PageBlockAuthorDateType: + var pageBlockAuthorDate PageBlockAuthorDate + err := json.Unmarshal(*rawMsg, &pageBlockAuthorDate) + return &pageBlockAuthorDate, err + + case PageBlockHeaderType: + var pageBlockHeader PageBlockHeader + err := json.Unmarshal(*rawMsg, &pageBlockHeader) + return &pageBlockHeader, err + + case PageBlockSubheaderType: + var pageBlockSubheader PageBlockSubheader + err := json.Unmarshal(*rawMsg, &pageBlockSubheader) + return &pageBlockSubheader, err + + case PageBlockParagraphType: + var pageBlockParagraph PageBlockParagraph + err := json.Unmarshal(*rawMsg, &pageBlockParagraph) + return &pageBlockParagraph, err + + case PageBlockPreformattedType: + var pageBlockPreformatted PageBlockPreformatted + err := json.Unmarshal(*rawMsg, &pageBlockPreformatted) + return &pageBlockPreformatted, err + + case PageBlockFooterType: + var pageBlockFooter PageBlockFooter + err := json.Unmarshal(*rawMsg, &pageBlockFooter) + return &pageBlockFooter, err + + case PageBlockDividerType: + var pageBlockDivider PageBlockDivider + err := json.Unmarshal(*rawMsg, &pageBlockDivider) + return &pageBlockDivider, err + + case PageBlockAnchorType: + var pageBlockAnchor PageBlockAnchor + err := json.Unmarshal(*rawMsg, &pageBlockAnchor) + return &pageBlockAnchor, err + + case PageBlockListType: + var pageBlockList PageBlockList + err := json.Unmarshal(*rawMsg, &pageBlockList) + return &pageBlockList, err + + case PageBlockBlockQuoteType: + var pageBlockBlockQuote PageBlockBlockQuote + err := json.Unmarshal(*rawMsg, &pageBlockBlockQuote) + return &pageBlockBlockQuote, err + + case PageBlockPullQuoteType: + var pageBlockPullQuote PageBlockPullQuote + err := json.Unmarshal(*rawMsg, &pageBlockPullQuote) + return &pageBlockPullQuote, err + + case PageBlockAnimationType: + var pageBlockAnimation PageBlockAnimation + err := json.Unmarshal(*rawMsg, &pageBlockAnimation) + return &pageBlockAnimation, err + + case PageBlockAudioType: + var pageBlockAudio PageBlockAudio + err := json.Unmarshal(*rawMsg, &pageBlockAudio) + return &pageBlockAudio, err + + case PageBlockPhotoType: + var pageBlockPhoto PageBlockPhoto + err := json.Unmarshal(*rawMsg, &pageBlockPhoto) + return &pageBlockPhoto, err + + case PageBlockVideoType: + var pageBlockVideo PageBlockVideo + err := json.Unmarshal(*rawMsg, &pageBlockVideo) + return &pageBlockVideo, err + + case PageBlockCoverType: + var pageBlockCover PageBlockCover + err := json.Unmarshal(*rawMsg, &pageBlockCover) + return &pageBlockCover, err + + case PageBlockEmbeddedType: + var pageBlockEmbedded PageBlockEmbedded + err := json.Unmarshal(*rawMsg, &pageBlockEmbedded) + return &pageBlockEmbedded, err + + case PageBlockEmbeddedPostType: + var pageBlockEmbeddedPost PageBlockEmbeddedPost + err := json.Unmarshal(*rawMsg, &pageBlockEmbeddedPost) + return &pageBlockEmbeddedPost, err + + case PageBlockCollageType: + var pageBlockCollage PageBlockCollage + err := json.Unmarshal(*rawMsg, &pageBlockCollage) + return &pageBlockCollage, err + + case PageBlockSlideshowType: + var pageBlockSlideshow PageBlockSlideshow + err := json.Unmarshal(*rawMsg, &pageBlockSlideshow) + return &pageBlockSlideshow, err + + case PageBlockChatLinkType: + var pageBlockChatLink PageBlockChatLink + err := json.Unmarshal(*rawMsg, &pageBlockChatLink) + return &pageBlockChatLink, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInputCredentials(rawMsg *json.RawMessage) (InputCredentials, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputCredentialsEnum(objMap["@type"].(string)) { + case InputCredentialsSavedType: + var inputCredentialsSaved InputCredentialsSaved + err := json.Unmarshal(*rawMsg, &inputCredentialsSaved) + return &inputCredentialsSaved, err + + case InputCredentialsNewType: + var inputCredentialsNew InputCredentialsNew + err := json.Unmarshal(*rawMsg, &inputCredentialsNew) + return &inputCredentialsNew, err + + case InputCredentialsAndroidPayType: + var inputCredentialsAndroidPay InputCredentialsAndroidPay + err := json.Unmarshal(*rawMsg, &inputCredentialsAndroidPay) + return &inputCredentialsAndroidPay, err + + case InputCredentialsApplePayType: + var inputCredentialsApplePay InputCredentialsApplePay + err := json.Unmarshal(*rawMsg, &inputCredentialsApplePay) + return &inputCredentialsApplePay, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalPassportElementType(rawMsg *json.RawMessage) (PassportElementType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PassportElementTypeEnum(objMap["@type"].(string)) { + case PassportElementTypePersonalDetailsType: + var passportElementTypePersonalDetails PassportElementTypePersonalDetails + err := json.Unmarshal(*rawMsg, &passportElementTypePersonalDetails) + return &passportElementTypePersonalDetails, err + + case PassportElementTypePassportType: + var passportElementTypePassport PassportElementTypePassport + err := json.Unmarshal(*rawMsg, &passportElementTypePassport) + return &passportElementTypePassport, err + + case PassportElementTypeDriverLicenseType: + var passportElementTypeDriverLicense PassportElementTypeDriverLicense + err := json.Unmarshal(*rawMsg, &passportElementTypeDriverLicense) + return &passportElementTypeDriverLicense, err + + case PassportElementTypeIDentityCardType: + var passportElementTypeIDentityCard PassportElementTypeIDentityCard + err := json.Unmarshal(*rawMsg, &passportElementTypeIDentityCard) + return &passportElementTypeIDentityCard, err + + case PassportElementTypeInternalPassportType: + var passportElementTypeInternalPassport PassportElementTypeInternalPassport + err := json.Unmarshal(*rawMsg, &passportElementTypeInternalPassport) + return &passportElementTypeInternalPassport, err + + case PassportElementTypeAddressType: + var passportElementTypeAddress PassportElementTypeAddress + err := json.Unmarshal(*rawMsg, &passportElementTypeAddress) + return &passportElementTypeAddress, err + + case PassportElementTypeUtilityBillType: + var passportElementTypeUtilityBill PassportElementTypeUtilityBill + err := json.Unmarshal(*rawMsg, &passportElementTypeUtilityBill) + return &passportElementTypeUtilityBill, err + + case PassportElementTypeBankStatementType: + var passportElementTypeBankStatement PassportElementTypeBankStatement + err := json.Unmarshal(*rawMsg, &passportElementTypeBankStatement) + return &passportElementTypeBankStatement, err + + case PassportElementTypeRentalAgreementType: + var passportElementTypeRentalAgreement PassportElementTypeRentalAgreement + err := json.Unmarshal(*rawMsg, &passportElementTypeRentalAgreement) + return &passportElementTypeRentalAgreement, err + + case PassportElementTypePassportRegistrationType: + var passportElementTypePassportRegistration PassportElementTypePassportRegistration + err := json.Unmarshal(*rawMsg, &passportElementTypePassportRegistration) + return &passportElementTypePassportRegistration, err + + case PassportElementTypeTemporaryRegistrationType: + var passportElementTypeTemporaryRegistration PassportElementTypeTemporaryRegistration + err := json.Unmarshal(*rawMsg, &passportElementTypeTemporaryRegistration) + return &passportElementTypeTemporaryRegistration, err + + case PassportElementTypePhoneNumberType: + var passportElementTypePhoneNumber PassportElementTypePhoneNumber + err := json.Unmarshal(*rawMsg, &passportElementTypePhoneNumber) + return &passportElementTypePhoneNumber, err + + case PassportElementTypeEmailAddressType: + var passportElementTypeEmailAddress PassportElementTypeEmailAddress + err := json.Unmarshal(*rawMsg, &passportElementTypeEmailAddress) + return &passportElementTypeEmailAddress, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalPassportElement(rawMsg *json.RawMessage) (PassportElement, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PassportElementEnum(objMap["@type"].(string)) { + case PassportElementPersonalDetailsType: + var passportElementPersonalDetails PassportElementPersonalDetails + err := json.Unmarshal(*rawMsg, &passportElementPersonalDetails) + return &passportElementPersonalDetails, err + + case PassportElementPassportType: + var passportElementPassport PassportElementPassport + err := json.Unmarshal(*rawMsg, &passportElementPassport) + return &passportElementPassport, err + + case PassportElementDriverLicenseType: + var passportElementDriverLicense PassportElementDriverLicense + err := json.Unmarshal(*rawMsg, &passportElementDriverLicense) + return &passportElementDriverLicense, err + + case PassportElementIDentityCardType: + var passportElementIDentityCard PassportElementIDentityCard + err := json.Unmarshal(*rawMsg, &passportElementIDentityCard) + return &passportElementIDentityCard, err + + case PassportElementInternalPassportType: + var passportElementInternalPassport PassportElementInternalPassport + err := json.Unmarshal(*rawMsg, &passportElementInternalPassport) + return &passportElementInternalPassport, err + + case PassportElementAddressType: + var passportElementAddress PassportElementAddress + err := json.Unmarshal(*rawMsg, &passportElementAddress) + return &passportElementAddress, err + + case PassportElementUtilityBillType: + var passportElementUtilityBill PassportElementUtilityBill + err := json.Unmarshal(*rawMsg, &passportElementUtilityBill) + return &passportElementUtilityBill, err + + case PassportElementBankStatementType: + var passportElementBankStatement PassportElementBankStatement + err := json.Unmarshal(*rawMsg, &passportElementBankStatement) + return &passportElementBankStatement, err + + case PassportElementRentalAgreementType: + var passportElementRentalAgreement PassportElementRentalAgreement + err := json.Unmarshal(*rawMsg, &passportElementRentalAgreement) + return &passportElementRentalAgreement, err + + case PassportElementPassportRegistrationType: + var passportElementPassportRegistration PassportElementPassportRegistration + err := json.Unmarshal(*rawMsg, &passportElementPassportRegistration) + return &passportElementPassportRegistration, err + + case PassportElementTemporaryRegistrationType: + var passportElementTemporaryRegistration PassportElementTemporaryRegistration + err := json.Unmarshal(*rawMsg, &passportElementTemporaryRegistration) + return &passportElementTemporaryRegistration, err + + case PassportElementPhoneNumberType: + var passportElementPhoneNumber PassportElementPhoneNumber + err := json.Unmarshal(*rawMsg, &passportElementPhoneNumber) + return &passportElementPhoneNumber, err + + case PassportElementEmailAddressType: + var passportElementEmailAddress PassportElementEmailAddress + err := json.Unmarshal(*rawMsg, &passportElementEmailAddress) + return &passportElementEmailAddress, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInputPassportElement(rawMsg *json.RawMessage) (InputPassportElement, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputPassportElementEnum(objMap["@type"].(string)) { + case InputPassportElementPersonalDetailsType: + var inputPassportElementPersonalDetails InputPassportElementPersonalDetails + err := json.Unmarshal(*rawMsg, &inputPassportElementPersonalDetails) + return &inputPassportElementPersonalDetails, err + + case InputPassportElementPassportType: + var inputPassportElementPassport InputPassportElementPassport + err := json.Unmarshal(*rawMsg, &inputPassportElementPassport) + return &inputPassportElementPassport, err + + case InputPassportElementDriverLicenseType: + var inputPassportElementDriverLicense InputPassportElementDriverLicense + err := json.Unmarshal(*rawMsg, &inputPassportElementDriverLicense) + return &inputPassportElementDriverLicense, err + + case InputPassportElementIDentityCardType: + var inputPassportElementIDentityCard InputPassportElementIDentityCard + err := json.Unmarshal(*rawMsg, &inputPassportElementIDentityCard) + return &inputPassportElementIDentityCard, err + + case InputPassportElementInternalPassportType: + var inputPassportElementInternalPassport InputPassportElementInternalPassport + err := json.Unmarshal(*rawMsg, &inputPassportElementInternalPassport) + return &inputPassportElementInternalPassport, err + + case InputPassportElementAddressType: + var inputPassportElementAddress InputPassportElementAddress + err := json.Unmarshal(*rawMsg, &inputPassportElementAddress) + return &inputPassportElementAddress, err + + case InputPassportElementUtilityBillType: + var inputPassportElementUtilityBill InputPassportElementUtilityBill + err := json.Unmarshal(*rawMsg, &inputPassportElementUtilityBill) + return &inputPassportElementUtilityBill, err + + case InputPassportElementBankStatementType: + var inputPassportElementBankStatement InputPassportElementBankStatement + err := json.Unmarshal(*rawMsg, &inputPassportElementBankStatement) + return &inputPassportElementBankStatement, err + + case InputPassportElementRentalAgreementType: + var inputPassportElementRentalAgreement InputPassportElementRentalAgreement + err := json.Unmarshal(*rawMsg, &inputPassportElementRentalAgreement) + return &inputPassportElementRentalAgreement, err + + case InputPassportElementPassportRegistrationType: + var inputPassportElementPassportRegistration InputPassportElementPassportRegistration + err := json.Unmarshal(*rawMsg, &inputPassportElementPassportRegistration) + return &inputPassportElementPassportRegistration, err + + case InputPassportElementTemporaryRegistrationType: + var inputPassportElementTemporaryRegistration InputPassportElementTemporaryRegistration + err := json.Unmarshal(*rawMsg, &inputPassportElementTemporaryRegistration) + return &inputPassportElementTemporaryRegistration, err + + case InputPassportElementPhoneNumberType: + var inputPassportElementPhoneNumber InputPassportElementPhoneNumber + err := json.Unmarshal(*rawMsg, &inputPassportElementPhoneNumber) + return &inputPassportElementPhoneNumber, err + + case InputPassportElementEmailAddressType: + var inputPassportElementEmailAddress InputPassportElementEmailAddress + err := json.Unmarshal(*rawMsg, &inputPassportElementEmailAddress) + return &inputPassportElementEmailAddress, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalPassportElementErrorSource(rawMsg *json.RawMessage) (PassportElementErrorSource, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PassportElementErrorSourceEnum(objMap["@type"].(string)) { + case PassportElementErrorSourceUnspecifiedType: + var passportElementErrorSourceUnspecified PassportElementErrorSourceUnspecified + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceUnspecified) + return &passportElementErrorSourceUnspecified, err + + case PassportElementErrorSourceDataFieldType: + var passportElementErrorSourceDataField PassportElementErrorSourceDataField + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceDataField) + return &passportElementErrorSourceDataField, err + + case PassportElementErrorSourceFrontSideType: + var passportElementErrorSourceFrontSide PassportElementErrorSourceFrontSide + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceFrontSide) + return &passportElementErrorSourceFrontSide, err + + case PassportElementErrorSourceReverseSideType: + var passportElementErrorSourceReverseSide PassportElementErrorSourceReverseSide + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceReverseSide) + return &passportElementErrorSourceReverseSide, err + + case PassportElementErrorSourceSelfieType: + var passportElementErrorSourceSelfie PassportElementErrorSourceSelfie + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceSelfie) + return &passportElementErrorSourceSelfie, err + + case PassportElementErrorSourceTranslationFileType: + var passportElementErrorSourceTranslationFile PassportElementErrorSourceTranslationFile + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceTranslationFile) + return &passportElementErrorSourceTranslationFile, err + + case PassportElementErrorSourceTranslationFilesType: + var passportElementErrorSourceTranslationFiles PassportElementErrorSourceTranslationFiles + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceTranslationFiles) + return &passportElementErrorSourceTranslationFiles, err + + case PassportElementErrorSourceFileType: + var passportElementErrorSourceFile PassportElementErrorSourceFile + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceFile) + return &passportElementErrorSourceFile, err + + case PassportElementErrorSourceFilesType: + var passportElementErrorSourceFiles PassportElementErrorSourceFiles + err := json.Unmarshal(*rawMsg, &passportElementErrorSourceFiles) + return &passportElementErrorSourceFiles, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInputPassportElementErrorSource(rawMsg *json.RawMessage) (InputPassportElementErrorSource, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputPassportElementErrorSourceEnum(objMap["@type"].(string)) { + case InputPassportElementErrorSourceUnspecifiedType: + var inputPassportElementErrorSourceUnspecified InputPassportElementErrorSourceUnspecified + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceUnspecified) + return &inputPassportElementErrorSourceUnspecified, err + + case InputPassportElementErrorSourceDataFieldType: + var inputPassportElementErrorSourceDataField InputPassportElementErrorSourceDataField + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceDataField) + return &inputPassportElementErrorSourceDataField, err + + case InputPassportElementErrorSourceFrontSideType: + var inputPassportElementErrorSourceFrontSide InputPassportElementErrorSourceFrontSide + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceFrontSide) + return &inputPassportElementErrorSourceFrontSide, err + + case InputPassportElementErrorSourceReverseSideType: + var inputPassportElementErrorSourceReverseSide InputPassportElementErrorSourceReverseSide + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceReverseSide) + return &inputPassportElementErrorSourceReverseSide, err + + case InputPassportElementErrorSourceSelfieType: + var inputPassportElementErrorSourceSelfie InputPassportElementErrorSourceSelfie + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceSelfie) + return &inputPassportElementErrorSourceSelfie, err + + case InputPassportElementErrorSourceTranslationFileType: + var inputPassportElementErrorSourceTranslationFile InputPassportElementErrorSourceTranslationFile + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceTranslationFile) + return &inputPassportElementErrorSourceTranslationFile, err + + case InputPassportElementErrorSourceTranslationFilesType: + var inputPassportElementErrorSourceTranslationFiles InputPassportElementErrorSourceTranslationFiles + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceTranslationFiles) + return &inputPassportElementErrorSourceTranslationFiles, err + + case InputPassportElementErrorSourceFileType: + var inputPassportElementErrorSourceFile InputPassportElementErrorSourceFile + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceFile) + return &inputPassportElementErrorSourceFile, err + + case InputPassportElementErrorSourceFilesType: + var inputPassportElementErrorSourceFiles InputPassportElementErrorSourceFiles + err := json.Unmarshal(*rawMsg, &inputPassportElementErrorSourceFiles) + return &inputPassportElementErrorSourceFiles, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalMessageContent(rawMsg *json.RawMessage) (MessageContent, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MessageContentEnum(objMap["@type"].(string)) { + case MessageTextType: + var messageText MessageText + err := json.Unmarshal(*rawMsg, &messageText) + return &messageText, err + + case MessageAnimationType: + var messageAnimation MessageAnimation + err := json.Unmarshal(*rawMsg, &messageAnimation) + return &messageAnimation, err + + case MessageAudioType: + var messageAudio MessageAudio + err := json.Unmarshal(*rawMsg, &messageAudio) + return &messageAudio, err + + case MessageDocumentType: + var messageDocument MessageDocument + err := json.Unmarshal(*rawMsg, &messageDocument) + return &messageDocument, err + + case MessagePhotoType: + var messagePhoto MessagePhoto + err := json.Unmarshal(*rawMsg, &messagePhoto) + return &messagePhoto, err + + case MessageExpiredPhotoType: + var messageExpiredPhoto MessageExpiredPhoto + err := json.Unmarshal(*rawMsg, &messageExpiredPhoto) + return &messageExpiredPhoto, err + + case MessageStickerType: + var messageSticker MessageSticker + err := json.Unmarshal(*rawMsg, &messageSticker) + return &messageSticker, err + + case MessageVideoType: + var messageVideo MessageVideo + err := json.Unmarshal(*rawMsg, &messageVideo) + return &messageVideo, err + + case MessageExpiredVideoType: + var messageExpiredVideo MessageExpiredVideo + err := json.Unmarshal(*rawMsg, &messageExpiredVideo) + return &messageExpiredVideo, err + + case MessageVideoNoteType: + var messageVideoNote MessageVideoNote + err := json.Unmarshal(*rawMsg, &messageVideoNote) + return &messageVideoNote, err + + case MessageVoiceNoteType: + var messageVoiceNote MessageVoiceNote + err := json.Unmarshal(*rawMsg, &messageVoiceNote) + return &messageVoiceNote, err + + case MessageLocationType: + var messageLocation MessageLocation + err := json.Unmarshal(*rawMsg, &messageLocation) + return &messageLocation, err + + case MessageVenueType: + var messageVenue MessageVenue + err := json.Unmarshal(*rawMsg, &messageVenue) + return &messageVenue, err + + case MessageContactType: + var messageContact MessageContact + err := json.Unmarshal(*rawMsg, &messageContact) + return &messageContact, err + + case MessageGameType: + var messageGame MessageGame + err := json.Unmarshal(*rawMsg, &messageGame) + return &messageGame, err + + case MessageInvoiceType: + var messageInvoice MessageInvoice + err := json.Unmarshal(*rawMsg, &messageInvoice) + return &messageInvoice, err + + case MessageCallType: + var messageCall MessageCall + err := json.Unmarshal(*rawMsg, &messageCall) + return &messageCall, err + + case MessageBasicGroupChatCreateType: + var messageBasicGroupChatCreate MessageBasicGroupChatCreate + err := json.Unmarshal(*rawMsg, &messageBasicGroupChatCreate) + return &messageBasicGroupChatCreate, err + + case MessageSupergroupChatCreateType: + var messageSupergroupChatCreate MessageSupergroupChatCreate + err := json.Unmarshal(*rawMsg, &messageSupergroupChatCreate) + return &messageSupergroupChatCreate, err + + case MessageChatChangeTitleType: + var messageChatChangeTitle MessageChatChangeTitle + err := json.Unmarshal(*rawMsg, &messageChatChangeTitle) + return &messageChatChangeTitle, err + + case MessageChatChangePhotoType: + var messageChatChangePhoto MessageChatChangePhoto + err := json.Unmarshal(*rawMsg, &messageChatChangePhoto) + return &messageChatChangePhoto, err + + case MessageChatDeletePhotoType: + var messageChatDeletePhoto MessageChatDeletePhoto + err := json.Unmarshal(*rawMsg, &messageChatDeletePhoto) + return &messageChatDeletePhoto, err + + case MessageChatAddMembersType: + var messageChatAddMembers MessageChatAddMembers + err := json.Unmarshal(*rawMsg, &messageChatAddMembers) + return &messageChatAddMembers, err + + case MessageChatJoinByLinkType: + var messageChatJoinByLink MessageChatJoinByLink + err := json.Unmarshal(*rawMsg, &messageChatJoinByLink) + return &messageChatJoinByLink, err + + case MessageChatDeleteMemberType: + var messageChatDeleteMember MessageChatDeleteMember + err := json.Unmarshal(*rawMsg, &messageChatDeleteMember) + return &messageChatDeleteMember, err + + case MessageChatUpgradeToType: + var messageChatUpgradeTo MessageChatUpgradeTo + err := json.Unmarshal(*rawMsg, &messageChatUpgradeTo) + return &messageChatUpgradeTo, err + + case MessageChatUpgradeFromType: + var messageChatUpgradeFrom MessageChatUpgradeFrom + err := json.Unmarshal(*rawMsg, &messageChatUpgradeFrom) + return &messageChatUpgradeFrom, err + + case MessagePinMessageType: + var messagePinMessage MessagePinMessage + err := json.Unmarshal(*rawMsg, &messagePinMessage) + return &messagePinMessage, err + + case MessageScreenshotTakenType: + var messageScreenshotTaken MessageScreenshotTaken + err := json.Unmarshal(*rawMsg, &messageScreenshotTaken) + return &messageScreenshotTaken, err + + case MessageChatSetTTLType: + var messageChatSetTTL MessageChatSetTTL + err := json.Unmarshal(*rawMsg, &messageChatSetTTL) + return &messageChatSetTTL, err + + case MessageCustomServiceActionType: + var messageCustomServiceAction MessageCustomServiceAction + err := json.Unmarshal(*rawMsg, &messageCustomServiceAction) + return &messageCustomServiceAction, err + + case MessageGameScoreType: + var messageGameScore MessageGameScore + err := json.Unmarshal(*rawMsg, &messageGameScore) + return &messageGameScore, err + + case MessagePaymentSuccessfulType: + var messagePaymentSuccessful MessagePaymentSuccessful + err := json.Unmarshal(*rawMsg, &messagePaymentSuccessful) + return &messagePaymentSuccessful, err + + case MessagePaymentSuccessfulBotType: + var messagePaymentSuccessfulBot MessagePaymentSuccessfulBot + err := json.Unmarshal(*rawMsg, &messagePaymentSuccessfulBot) + return &messagePaymentSuccessfulBot, err + + case MessageContactRegisteredType: + var messageContactRegistered MessageContactRegistered + err := json.Unmarshal(*rawMsg, &messageContactRegistered) + return &messageContactRegistered, err + + case MessageWebsiteConnectedType: + var messageWebsiteConnected MessageWebsiteConnected + err := json.Unmarshal(*rawMsg, &messageWebsiteConnected) + return &messageWebsiteConnected, err + + case MessagePassportDataSentType: + var messagePassportDataSent MessagePassportDataSent + err := json.Unmarshal(*rawMsg, &messagePassportDataSent) + return &messagePassportDataSent, err + + case MessagePassportDataReceivedType: + var messagePassportDataReceived MessagePassportDataReceived + err := json.Unmarshal(*rawMsg, &messagePassportDataReceived) + return &messagePassportDataReceived, err + + case MessageUnsupportedType: + var messageUnsupported MessageUnsupported + err := json.Unmarshal(*rawMsg, &messageUnsupported) + return &messageUnsupported, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalTextEntityType(rawMsg *json.RawMessage) (TextEntityType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch TextEntityTypeEnum(objMap["@type"].(string)) { + case TextEntityTypeMentionType: + var textEntityTypeMention TextEntityTypeMention + err := json.Unmarshal(*rawMsg, &textEntityTypeMention) + return &textEntityTypeMention, err + + case TextEntityTypeHashtagType: + var textEntityTypeHashtag TextEntityTypeHashtag + err := json.Unmarshal(*rawMsg, &textEntityTypeHashtag) + return &textEntityTypeHashtag, err + + case TextEntityTypeCashtagType: + var textEntityTypeCashtag TextEntityTypeCashtag + err := json.Unmarshal(*rawMsg, &textEntityTypeCashtag) + return &textEntityTypeCashtag, err + + case TextEntityTypeBotCommandType: + var textEntityTypeBotCommand TextEntityTypeBotCommand + err := json.Unmarshal(*rawMsg, &textEntityTypeBotCommand) + return &textEntityTypeBotCommand, err + + case TextEntityTypeURLType: + var textEntityTypeURL TextEntityTypeURL + err := json.Unmarshal(*rawMsg, &textEntityTypeURL) + return &textEntityTypeURL, err + + case TextEntityTypeEmailAddressType: + var textEntityTypeEmailAddress TextEntityTypeEmailAddress + err := json.Unmarshal(*rawMsg, &textEntityTypeEmailAddress) + return &textEntityTypeEmailAddress, err + + case TextEntityTypeBoldType: + var textEntityTypeBold TextEntityTypeBold + err := json.Unmarshal(*rawMsg, &textEntityTypeBold) + return &textEntityTypeBold, err + + case TextEntityTypeItalicType: + var textEntityTypeItalic TextEntityTypeItalic + err := json.Unmarshal(*rawMsg, &textEntityTypeItalic) + return &textEntityTypeItalic, err + + case TextEntityTypeCodeType: + var textEntityTypeCode TextEntityTypeCode + err := json.Unmarshal(*rawMsg, &textEntityTypeCode) + return &textEntityTypeCode, err + + case TextEntityTypePreType: + var textEntityTypePre TextEntityTypePre + err := json.Unmarshal(*rawMsg, &textEntityTypePre) + return &textEntityTypePre, err + + case TextEntityTypePreCodeType: + var textEntityTypePreCode TextEntityTypePreCode + err := json.Unmarshal(*rawMsg, &textEntityTypePreCode) + return &textEntityTypePreCode, err + + case TextEntityTypeTextURLType: + var textEntityTypeTextURL TextEntityTypeTextURL + err := json.Unmarshal(*rawMsg, &textEntityTypeTextURL) + return &textEntityTypeTextURL, err + + case TextEntityTypeMentionNameType: + var textEntityTypeMentionName TextEntityTypeMentionName + err := json.Unmarshal(*rawMsg, &textEntityTypeMentionName) + return &textEntityTypeMentionName, err + + case TextEntityTypePhoneNumberType: + var textEntityTypePhoneNumber TextEntityTypePhoneNumber + err := json.Unmarshal(*rawMsg, &textEntityTypePhoneNumber) + return &textEntityTypePhoneNumber, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInputMessageContent(rawMsg *json.RawMessage) (InputMessageContent, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputMessageContentEnum(objMap["@type"].(string)) { + case InputMessageTextType: + var inputMessageText InputMessageText + err := json.Unmarshal(*rawMsg, &inputMessageText) + return &inputMessageText, err + + case InputMessageAnimationType: + var inputMessageAnimation InputMessageAnimation + err := json.Unmarshal(*rawMsg, &inputMessageAnimation) + return &inputMessageAnimation, err + + case InputMessageAudioType: + var inputMessageAudio InputMessageAudio + err := json.Unmarshal(*rawMsg, &inputMessageAudio) + return &inputMessageAudio, err + + case InputMessageDocumentType: + var inputMessageDocument InputMessageDocument + err := json.Unmarshal(*rawMsg, &inputMessageDocument) + return &inputMessageDocument, err + + case InputMessagePhotoType: + var inputMessagePhoto InputMessagePhoto + err := json.Unmarshal(*rawMsg, &inputMessagePhoto) + return &inputMessagePhoto, err + + case InputMessageStickerType: + var inputMessageSticker InputMessageSticker + err := json.Unmarshal(*rawMsg, &inputMessageSticker) + return &inputMessageSticker, err + + case InputMessageVideoType: + var inputMessageVideo InputMessageVideo + err := json.Unmarshal(*rawMsg, &inputMessageVideo) + return &inputMessageVideo, err + + case InputMessageVideoNoteType: + var inputMessageVideoNote InputMessageVideoNote + err := json.Unmarshal(*rawMsg, &inputMessageVideoNote) + return &inputMessageVideoNote, err + + case InputMessageVoiceNoteType: + var inputMessageVoiceNote InputMessageVoiceNote + err := json.Unmarshal(*rawMsg, &inputMessageVoiceNote) + return &inputMessageVoiceNote, err + + case InputMessageLocationType: + var inputMessageLocation InputMessageLocation + err := json.Unmarshal(*rawMsg, &inputMessageLocation) + return &inputMessageLocation, err + + case InputMessageVenueType: + var inputMessageVenue InputMessageVenue + err := json.Unmarshal(*rawMsg, &inputMessageVenue) + return &inputMessageVenue, err + + case InputMessageContactType: + var inputMessageContact InputMessageContact + err := json.Unmarshal(*rawMsg, &inputMessageContact) + return &inputMessageContact, err + + case InputMessageGameType: + var inputMessageGame InputMessageGame + err := json.Unmarshal(*rawMsg, &inputMessageGame) + return &inputMessageGame, err + + case InputMessageInvoiceType: + var inputMessageInvoice InputMessageInvoice + err := json.Unmarshal(*rawMsg, &inputMessageInvoice) + return &inputMessageInvoice, err + + case InputMessageForwardedType: + var inputMessageForwarded InputMessageForwarded + err := json.Unmarshal(*rawMsg, &inputMessageForwarded) + return &inputMessageForwarded, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalSearchMessagesFilter(rawMsg *json.RawMessage) (SearchMessagesFilter, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch SearchMessagesFilterEnum(objMap["@type"].(string)) { + case SearchMessagesFilterEmptyType: + var searchMessagesFilterEmpty SearchMessagesFilterEmpty + err := json.Unmarshal(*rawMsg, &searchMessagesFilterEmpty) + return &searchMessagesFilterEmpty, err + + case SearchMessagesFilterAnimationType: + var searchMessagesFilterAnimation SearchMessagesFilterAnimation + err := json.Unmarshal(*rawMsg, &searchMessagesFilterAnimation) + return &searchMessagesFilterAnimation, err + + case SearchMessagesFilterAudioType: + var searchMessagesFilterAudio SearchMessagesFilterAudio + err := json.Unmarshal(*rawMsg, &searchMessagesFilterAudio) + return &searchMessagesFilterAudio, err + + case SearchMessagesFilterDocumentType: + var searchMessagesFilterDocument SearchMessagesFilterDocument + err := json.Unmarshal(*rawMsg, &searchMessagesFilterDocument) + return &searchMessagesFilterDocument, err + + case SearchMessagesFilterPhotoType: + var searchMessagesFilterPhoto SearchMessagesFilterPhoto + err := json.Unmarshal(*rawMsg, &searchMessagesFilterPhoto) + return &searchMessagesFilterPhoto, err + + case SearchMessagesFilterVideoType: + var searchMessagesFilterVideo SearchMessagesFilterVideo + err := json.Unmarshal(*rawMsg, &searchMessagesFilterVideo) + return &searchMessagesFilterVideo, err + + case SearchMessagesFilterVoiceNoteType: + var searchMessagesFilterVoiceNote SearchMessagesFilterVoiceNote + err := json.Unmarshal(*rawMsg, &searchMessagesFilterVoiceNote) + return &searchMessagesFilterVoiceNote, err + + case SearchMessagesFilterPhotoAndVideoType: + var searchMessagesFilterPhotoAndVideo SearchMessagesFilterPhotoAndVideo + err := json.Unmarshal(*rawMsg, &searchMessagesFilterPhotoAndVideo) + return &searchMessagesFilterPhotoAndVideo, err + + case SearchMessagesFilterURLType: + var searchMessagesFilterURL SearchMessagesFilterURL + err := json.Unmarshal(*rawMsg, &searchMessagesFilterURL) + return &searchMessagesFilterURL, err + + case SearchMessagesFilterChatPhotoType: + var searchMessagesFilterChatPhoto SearchMessagesFilterChatPhoto + err := json.Unmarshal(*rawMsg, &searchMessagesFilterChatPhoto) + return &searchMessagesFilterChatPhoto, err + + case SearchMessagesFilterCallType: + var searchMessagesFilterCall SearchMessagesFilterCall + err := json.Unmarshal(*rawMsg, &searchMessagesFilterCall) + return &searchMessagesFilterCall, err + + case SearchMessagesFilterMissedCallType: + var searchMessagesFilterMissedCall SearchMessagesFilterMissedCall + err := json.Unmarshal(*rawMsg, &searchMessagesFilterMissedCall) + return &searchMessagesFilterMissedCall, err + + case SearchMessagesFilterVideoNoteType: + var searchMessagesFilterVideoNote SearchMessagesFilterVideoNote + err := json.Unmarshal(*rawMsg, &searchMessagesFilterVideoNote) + return &searchMessagesFilterVideoNote, err + + case SearchMessagesFilterVoiceAndVideoNoteType: + var searchMessagesFilterVoiceAndVideoNote SearchMessagesFilterVoiceAndVideoNote + err := json.Unmarshal(*rawMsg, &searchMessagesFilterVoiceAndVideoNote) + return &searchMessagesFilterVoiceAndVideoNote, err + + case SearchMessagesFilterMentionType: + var searchMessagesFilterMention SearchMessagesFilterMention + err := json.Unmarshal(*rawMsg, &searchMessagesFilterMention) + return &searchMessagesFilterMention, err + + case SearchMessagesFilterUnreadMentionType: + var searchMessagesFilterUnreadMention SearchMessagesFilterUnreadMention + err := json.Unmarshal(*rawMsg, &searchMessagesFilterUnreadMention) + return &searchMessagesFilterUnreadMention, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalChatAction(rawMsg *json.RawMessage) (ChatAction, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatActionEnum(objMap["@type"].(string)) { + case ChatActionTypingType: + var chatActionTyping ChatActionTyping + err := json.Unmarshal(*rawMsg, &chatActionTyping) + return &chatActionTyping, err + + case ChatActionRecordingVideoType: + var chatActionRecordingVideo ChatActionRecordingVideo + err := json.Unmarshal(*rawMsg, &chatActionRecordingVideo) + return &chatActionRecordingVideo, err + + case ChatActionUploadingVideoType: + var chatActionUploadingVideo ChatActionUploadingVideo + err := json.Unmarshal(*rawMsg, &chatActionUploadingVideo) + return &chatActionUploadingVideo, err + + case ChatActionRecordingVoiceNoteType: + var chatActionRecordingVoiceNote ChatActionRecordingVoiceNote + err := json.Unmarshal(*rawMsg, &chatActionRecordingVoiceNote) + return &chatActionRecordingVoiceNote, err + + case ChatActionUploadingVoiceNoteType: + var chatActionUploadingVoiceNote ChatActionUploadingVoiceNote + err := json.Unmarshal(*rawMsg, &chatActionUploadingVoiceNote) + return &chatActionUploadingVoiceNote, err + + case ChatActionUploadingPhotoType: + var chatActionUploadingPhoto ChatActionUploadingPhoto + err := json.Unmarshal(*rawMsg, &chatActionUploadingPhoto) + return &chatActionUploadingPhoto, err + + case ChatActionUploadingDocumentType: + var chatActionUploadingDocument ChatActionUploadingDocument + err := json.Unmarshal(*rawMsg, &chatActionUploadingDocument) + return &chatActionUploadingDocument, err + + case ChatActionChoosingLocationType: + var chatActionChoosingLocation ChatActionChoosingLocation + err := json.Unmarshal(*rawMsg, &chatActionChoosingLocation) + return &chatActionChoosingLocation, err + + case ChatActionChoosingContactType: + var chatActionChoosingContact ChatActionChoosingContact + err := json.Unmarshal(*rawMsg, &chatActionChoosingContact) + return &chatActionChoosingContact, err + + case ChatActionStartPlayingGameType: + var chatActionStartPlayingGame ChatActionStartPlayingGame + err := json.Unmarshal(*rawMsg, &chatActionStartPlayingGame) + return &chatActionStartPlayingGame, err + + case ChatActionRecordingVideoNoteType: + var chatActionRecordingVideoNote ChatActionRecordingVideoNote + err := json.Unmarshal(*rawMsg, &chatActionRecordingVideoNote) + return &chatActionRecordingVideoNote, err + + case ChatActionUploadingVideoNoteType: + var chatActionUploadingVideoNote ChatActionUploadingVideoNote + err := json.Unmarshal(*rawMsg, &chatActionUploadingVideoNote) + return &chatActionUploadingVideoNote, err + + case ChatActionCancelType: + var chatActionCancel ChatActionCancel + err := json.Unmarshal(*rawMsg, &chatActionCancel) + return &chatActionCancel, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalUserStatus(rawMsg *json.RawMessage) (UserStatus, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch UserStatusEnum(objMap["@type"].(string)) { + case UserStatusEmptyType: + var userStatusEmpty UserStatusEmpty + err := json.Unmarshal(*rawMsg, &userStatusEmpty) + return &userStatusEmpty, err + + case UserStatusOnlineType: + var userStatusOnline UserStatusOnline + err := json.Unmarshal(*rawMsg, &userStatusOnline) + return &userStatusOnline, err + + case UserStatusOfflineType: + var userStatusOffline UserStatusOffline + err := json.Unmarshal(*rawMsg, &userStatusOffline) + return &userStatusOffline, err + + case UserStatusRecentlyType: + var userStatusRecently UserStatusRecently + err := json.Unmarshal(*rawMsg, &userStatusRecently) + return &userStatusRecently, err + + case UserStatusLastWeekType: + var userStatusLastWeek UserStatusLastWeek + err := json.Unmarshal(*rawMsg, &userStatusLastWeek) + return &userStatusLastWeek, err + + case UserStatusLastMonthType: + var userStatusLastMonth UserStatusLastMonth + err := json.Unmarshal(*rawMsg, &userStatusLastMonth) + return &userStatusLastMonth, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalCallDiscardReason(rawMsg *json.RawMessage) (CallDiscardReason, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CallDiscardReasonEnum(objMap["@type"].(string)) { + case CallDiscardReasonEmptyType: + var callDiscardReasonEmpty CallDiscardReasonEmpty + err := json.Unmarshal(*rawMsg, &callDiscardReasonEmpty) + return &callDiscardReasonEmpty, err + + case CallDiscardReasonMissedType: + var callDiscardReasonMissed CallDiscardReasonMissed + err := json.Unmarshal(*rawMsg, &callDiscardReasonMissed) + return &callDiscardReasonMissed, err + + case CallDiscardReasonDeclinedType: + var callDiscardReasonDeclined CallDiscardReasonDeclined + err := json.Unmarshal(*rawMsg, &callDiscardReasonDeclined) + return &callDiscardReasonDeclined, err + + case CallDiscardReasonDisconnectedType: + var callDiscardReasonDisconnected CallDiscardReasonDisconnected + err := json.Unmarshal(*rawMsg, &callDiscardReasonDisconnected) + return &callDiscardReasonDisconnected, err + + case CallDiscardReasonHungUpType: + var callDiscardReasonHungUp CallDiscardReasonHungUp + err := json.Unmarshal(*rawMsg, &callDiscardReasonHungUp) + return &callDiscardReasonHungUp, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalCallState(rawMsg *json.RawMessage) (CallState, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CallStateEnum(objMap["@type"].(string)) { + case CallStatePendingType: + var callStatePending CallStatePending + err := json.Unmarshal(*rawMsg, &callStatePending) + return &callStatePending, err + + case CallStateExchangingKeysType: + var callStateExchangingKeys CallStateExchangingKeys + err := json.Unmarshal(*rawMsg, &callStateExchangingKeys) + return &callStateExchangingKeys, err + + case CallStateReadyType: + var callStateReady CallStateReady + err := json.Unmarshal(*rawMsg, &callStateReady) + return &callStateReady, err + + case CallStateHangingUpType: + var callStateHangingUp CallStateHangingUp + err := json.Unmarshal(*rawMsg, &callStateHangingUp) + return &callStateHangingUp, err + + case CallStateDiscardedType: + var callStateDiscarded CallStateDiscarded + err := json.Unmarshal(*rawMsg, &callStateDiscarded) + return &callStateDiscarded, err + + case CallStateErrorType: + var callStateError CallStateError + err := json.Unmarshal(*rawMsg, &callStateError) + return &callStateError, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInputInlineQueryResult(rawMsg *json.RawMessage) (InputInlineQueryResult, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputInlineQueryResultEnum(objMap["@type"].(string)) { + case InputInlineQueryResultAnimatedGifType: + var inputInlineQueryResultAnimatedGif InputInlineQueryResultAnimatedGif + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultAnimatedGif) + return &inputInlineQueryResultAnimatedGif, err + + case InputInlineQueryResultAnimatedMpeg4Type: + var inputInlineQueryResultAnimatedMpeg4 InputInlineQueryResultAnimatedMpeg4 + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultAnimatedMpeg4) + return &inputInlineQueryResultAnimatedMpeg4, err + + case InputInlineQueryResultArticleType: + var inputInlineQueryResultArticle InputInlineQueryResultArticle + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultArticle) + return &inputInlineQueryResultArticle, err + + case InputInlineQueryResultAudioType: + var inputInlineQueryResultAudio InputInlineQueryResultAudio + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultAudio) + return &inputInlineQueryResultAudio, err + + case InputInlineQueryResultContactType: + var inputInlineQueryResultContact InputInlineQueryResultContact + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultContact) + return &inputInlineQueryResultContact, err + + case InputInlineQueryResultDocumentType: + var inputInlineQueryResultDocument InputInlineQueryResultDocument + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultDocument) + return &inputInlineQueryResultDocument, err + + case InputInlineQueryResultGameType: + var inputInlineQueryResultGame InputInlineQueryResultGame + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultGame) + return &inputInlineQueryResultGame, err + + case InputInlineQueryResultLocationType: + var inputInlineQueryResultLocation InputInlineQueryResultLocation + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultLocation) + return &inputInlineQueryResultLocation, err + + case InputInlineQueryResultPhotoType: + var inputInlineQueryResultPhoto InputInlineQueryResultPhoto + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultPhoto) + return &inputInlineQueryResultPhoto, err + + case InputInlineQueryResultStickerType: + var inputInlineQueryResultSticker InputInlineQueryResultSticker + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultSticker) + return &inputInlineQueryResultSticker, err + + case InputInlineQueryResultVenueType: + var inputInlineQueryResultVenue InputInlineQueryResultVenue + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultVenue) + return &inputInlineQueryResultVenue, err + + case InputInlineQueryResultVideoType: + var inputInlineQueryResultVideo InputInlineQueryResultVideo + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultVideo) + return &inputInlineQueryResultVideo, err + + case InputInlineQueryResultVoiceNoteType: + var inputInlineQueryResultVoiceNote InputInlineQueryResultVoiceNote + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultVoiceNote) + return &inputInlineQueryResultVoiceNote, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalInlineQueryResult(rawMsg *json.RawMessage) (InlineQueryResult, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InlineQueryResultEnum(objMap["@type"].(string)) { + case InlineQueryResultArticleType: + var inlineQueryResultArticle InlineQueryResultArticle + err := json.Unmarshal(*rawMsg, &inlineQueryResultArticle) + return &inlineQueryResultArticle, err + + case InlineQueryResultContactType: + var inlineQueryResultContact InlineQueryResultContact + err := json.Unmarshal(*rawMsg, &inlineQueryResultContact) + return &inlineQueryResultContact, err + + case InlineQueryResultLocationType: + var inlineQueryResultLocation InlineQueryResultLocation + err := json.Unmarshal(*rawMsg, &inlineQueryResultLocation) + return &inlineQueryResultLocation, err + + case InlineQueryResultVenueType: + var inlineQueryResultVenue InlineQueryResultVenue + err := json.Unmarshal(*rawMsg, &inlineQueryResultVenue) + return &inlineQueryResultVenue, err + + case InlineQueryResultGameType: + var inlineQueryResultGame InlineQueryResultGame + err := json.Unmarshal(*rawMsg, &inlineQueryResultGame) + return &inlineQueryResultGame, err + + case InlineQueryResultAnimationType: + var inlineQueryResultAnimation InlineQueryResultAnimation + err := json.Unmarshal(*rawMsg, &inlineQueryResultAnimation) + return &inlineQueryResultAnimation, err + + case InlineQueryResultAudioType: + var inlineQueryResultAudio InlineQueryResultAudio + err := json.Unmarshal(*rawMsg, &inlineQueryResultAudio) + return &inlineQueryResultAudio, err + + case InlineQueryResultDocumentType: + var inlineQueryResultDocument InlineQueryResultDocument + err := json.Unmarshal(*rawMsg, &inlineQueryResultDocument) + return &inlineQueryResultDocument, err + + case InlineQueryResultPhotoType: + var inlineQueryResultPhoto InlineQueryResultPhoto + err := json.Unmarshal(*rawMsg, &inlineQueryResultPhoto) + return &inlineQueryResultPhoto, err + + case InlineQueryResultStickerType: + var inlineQueryResultSticker InlineQueryResultSticker + err := json.Unmarshal(*rawMsg, &inlineQueryResultSticker) + return &inlineQueryResultSticker, err + + case InlineQueryResultVideoType: + var inlineQueryResultVideo InlineQueryResultVideo + err := json.Unmarshal(*rawMsg, &inlineQueryResultVideo) + return &inlineQueryResultVideo, err + + case InlineQueryResultVoiceNoteType: + var inlineQueryResultVoiceNote InlineQueryResultVoiceNote + err := json.Unmarshal(*rawMsg, &inlineQueryResultVoiceNote) + return &inlineQueryResultVoiceNote, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalCallbackQueryPayload(rawMsg *json.RawMessage) (CallbackQueryPayload, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CallbackQueryPayloadEnum(objMap["@type"].(string)) { + case CallbackQueryPayloadDataType: + var callbackQueryPayloadData CallbackQueryPayloadData + err := json.Unmarshal(*rawMsg, &callbackQueryPayloadData) + return &callbackQueryPayloadData, err + + case CallbackQueryPayloadGameType: + var callbackQueryPayloadGame CallbackQueryPayloadGame + err := json.Unmarshal(*rawMsg, &callbackQueryPayloadGame) + return &callbackQueryPayloadGame, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalChatEventAction(rawMsg *json.RawMessage) (ChatEventAction, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatEventActionEnum(objMap["@type"].(string)) { + case ChatEventMessageEditedType: + var chatEventMessageEdited ChatEventMessageEdited + err := json.Unmarshal(*rawMsg, &chatEventMessageEdited) + return &chatEventMessageEdited, err + + case ChatEventMessageDeletedType: + var chatEventMessageDeleted ChatEventMessageDeleted + err := json.Unmarshal(*rawMsg, &chatEventMessageDeleted) + return &chatEventMessageDeleted, err + + case ChatEventMessagePinnedType: + var chatEventMessagePinned ChatEventMessagePinned + err := json.Unmarshal(*rawMsg, &chatEventMessagePinned) + return &chatEventMessagePinned, err + + case ChatEventMessageUnpinnedType: + var chatEventMessageUnpinned ChatEventMessageUnpinned + err := json.Unmarshal(*rawMsg, &chatEventMessageUnpinned) + return &chatEventMessageUnpinned, err + + case ChatEventMemberJoinedType: + var chatEventMemberJoined ChatEventMemberJoined + err := json.Unmarshal(*rawMsg, &chatEventMemberJoined) + return &chatEventMemberJoined, err + + case ChatEventMemberLeftType: + var chatEventMemberLeft ChatEventMemberLeft + err := json.Unmarshal(*rawMsg, &chatEventMemberLeft) + return &chatEventMemberLeft, err + + case ChatEventMemberInvitedType: + var chatEventMemberInvited ChatEventMemberInvited + err := json.Unmarshal(*rawMsg, &chatEventMemberInvited) + return &chatEventMemberInvited, err + + case ChatEventMemberPromotedType: + var chatEventMemberPromoted ChatEventMemberPromoted + err := json.Unmarshal(*rawMsg, &chatEventMemberPromoted) + return &chatEventMemberPromoted, err + + case ChatEventMemberRestrictedType: + var chatEventMemberRestricted ChatEventMemberRestricted + err := json.Unmarshal(*rawMsg, &chatEventMemberRestricted) + return &chatEventMemberRestricted, err + + case ChatEventTitleChangedType: + var chatEventTitleChanged ChatEventTitleChanged + err := json.Unmarshal(*rawMsg, &chatEventTitleChanged) + return &chatEventTitleChanged, err + + case ChatEventDescriptionChangedType: + var chatEventDescriptionChanged ChatEventDescriptionChanged + err := json.Unmarshal(*rawMsg, &chatEventDescriptionChanged) + return &chatEventDescriptionChanged, err + + case ChatEventUsernameChangedType: + var chatEventUsernameChanged ChatEventUsernameChanged + err := json.Unmarshal(*rawMsg, &chatEventUsernameChanged) + return &chatEventUsernameChanged, err + + case ChatEventPhotoChangedType: + var chatEventPhotoChanged ChatEventPhotoChanged + err := json.Unmarshal(*rawMsg, &chatEventPhotoChanged) + return &chatEventPhotoChanged, err + + case ChatEventInvitesToggledType: + var chatEventInvitesToggled ChatEventInvitesToggled + err := json.Unmarshal(*rawMsg, &chatEventInvitesToggled) + return &chatEventInvitesToggled, err + + case ChatEventSignMessagesToggledType: + var chatEventSignMessagesToggled ChatEventSignMessagesToggled + err := json.Unmarshal(*rawMsg, &chatEventSignMessagesToggled) + return &chatEventSignMessagesToggled, err + + case ChatEventStickerSetChangedType: + var chatEventStickerSetChanged ChatEventStickerSetChanged + err := json.Unmarshal(*rawMsg, &chatEventStickerSetChanged) + return &chatEventStickerSetChanged, err + + case ChatEventIsAllHistoryAvailableToggledType: + var chatEventIsAllHistoryAvailableToggled ChatEventIsAllHistoryAvailableToggled + err := json.Unmarshal(*rawMsg, &chatEventIsAllHistoryAvailableToggled) + return &chatEventIsAllHistoryAvailableToggled, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalLanguagePackStringValue(rawMsg *json.RawMessage) (LanguagePackStringValue, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch LanguagePackStringValueEnum(objMap["@type"].(string)) { + case LanguagePackStringValueOrdinaryType: + var languagePackStringValueOrdinary LanguagePackStringValueOrdinary + err := json.Unmarshal(*rawMsg, &languagePackStringValueOrdinary) + return &languagePackStringValueOrdinary, err + + case LanguagePackStringValuePluralizedType: + var languagePackStringValuePluralized LanguagePackStringValuePluralized + err := json.Unmarshal(*rawMsg, &languagePackStringValuePluralized) + return &languagePackStringValuePluralized, err + + case LanguagePackStringValueDeletedType: + var languagePackStringValueDeleted LanguagePackStringValueDeleted + err := json.Unmarshal(*rawMsg, &languagePackStringValueDeleted) + return &languagePackStringValueDeleted, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalDeviceToken(rawMsg *json.RawMessage) (DeviceToken, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch DeviceTokenEnum(objMap["@type"].(string)) { + case DeviceTokenGoogleCloudMessagingType: + var deviceTokenGoogleCloudMessaging DeviceTokenGoogleCloudMessaging + err := json.Unmarshal(*rawMsg, &deviceTokenGoogleCloudMessaging) + return &deviceTokenGoogleCloudMessaging, err + + case DeviceTokenApplePushType: + var deviceTokenApplePush DeviceTokenApplePush + err := json.Unmarshal(*rawMsg, &deviceTokenApplePush) + return &deviceTokenApplePush, err + + case DeviceTokenApplePushVoIPType: + var deviceTokenApplePushVoIP DeviceTokenApplePushVoIP + err := json.Unmarshal(*rawMsg, &deviceTokenApplePushVoIP) + return &deviceTokenApplePushVoIP, err + + case DeviceTokenWindowsPushType: + var deviceTokenWindowsPush DeviceTokenWindowsPush + err := json.Unmarshal(*rawMsg, &deviceTokenWindowsPush) + return &deviceTokenWindowsPush, err + + case DeviceTokenMicrosoftPushType: + var deviceTokenMicrosoftPush DeviceTokenMicrosoftPush + err := json.Unmarshal(*rawMsg, &deviceTokenMicrosoftPush) + return &deviceTokenMicrosoftPush, err + + case DeviceTokenMicrosoftPushVoIPType: + var deviceTokenMicrosoftPushVoIP DeviceTokenMicrosoftPushVoIP + err := json.Unmarshal(*rawMsg, &deviceTokenMicrosoftPushVoIP) + return &deviceTokenMicrosoftPushVoIP, err + + case DeviceTokenWebPushType: + var deviceTokenWebPush DeviceTokenWebPush + err := json.Unmarshal(*rawMsg, &deviceTokenWebPush) + return &deviceTokenWebPush, err + + case DeviceTokenSimplePushType: + var deviceTokenSimplePush DeviceTokenSimplePush + err := json.Unmarshal(*rawMsg, &deviceTokenSimplePush) + return &deviceTokenSimplePush, err + + case DeviceTokenUbuntuPushType: + var deviceTokenUbuntuPush DeviceTokenUbuntuPush + err := json.Unmarshal(*rawMsg, &deviceTokenUbuntuPush) + return &deviceTokenUbuntuPush, err + + case DeviceTokenBlackBerryPushType: + var deviceTokenBlackBerryPush DeviceTokenBlackBerryPush + err := json.Unmarshal(*rawMsg, &deviceTokenBlackBerryPush) + return &deviceTokenBlackBerryPush, err + + case DeviceTokenTizenPushType: + var deviceTokenTizenPush DeviceTokenTizenPush + err := json.Unmarshal(*rawMsg, &deviceTokenTizenPush) + return &deviceTokenTizenPush, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalCheckChatUsernameResult(rawMsg *json.RawMessage) (CheckChatUsernameResult, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CheckChatUsernameResultEnum(objMap["@type"].(string)) { + case CheckChatUsernameResultOkType: + var checkChatUsernameResultOk CheckChatUsernameResultOk + err := json.Unmarshal(*rawMsg, &checkChatUsernameResultOk) + return &checkChatUsernameResultOk, err + + case CheckChatUsernameResultUsernameInvalidType: + var checkChatUsernameResultUsernameInvalid CheckChatUsernameResultUsernameInvalid + err := json.Unmarshal(*rawMsg, &checkChatUsernameResultUsernameInvalid) + return &checkChatUsernameResultUsernameInvalid, err + + case CheckChatUsernameResultUsernameOccupiedType: + var checkChatUsernameResultUsernameOccupied CheckChatUsernameResultUsernameOccupied + err := json.Unmarshal(*rawMsg, &checkChatUsernameResultUsernameOccupied) + return &checkChatUsernameResultUsernameOccupied, err + + case CheckChatUsernameResultPublicChatsTooMuchType: + var checkChatUsernameResultPublicChatsTooMuch CheckChatUsernameResultPublicChatsTooMuch + err := json.Unmarshal(*rawMsg, &checkChatUsernameResultPublicChatsTooMuch) + return &checkChatUsernameResultPublicChatsTooMuch, err + + case CheckChatUsernameResultPublicGroupsUnavailableType: + var checkChatUsernameResultPublicGroupsUnavailable CheckChatUsernameResultPublicGroupsUnavailable + err := json.Unmarshal(*rawMsg, &checkChatUsernameResultPublicGroupsUnavailable) + return &checkChatUsernameResultPublicGroupsUnavailable, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalOptionValue(rawMsg *json.RawMessage) (OptionValue, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch OptionValueEnum(objMap["@type"].(string)) { + case OptionValueBooleanType: + var optionValueBoolean OptionValueBoolean + err := json.Unmarshal(*rawMsg, &optionValueBoolean) + return &optionValueBoolean, err + + case OptionValueEmptyType: + var optionValueEmpty OptionValueEmpty + err := json.Unmarshal(*rawMsg, &optionValueEmpty) + return &optionValueEmpty, err + + case OptionValueIntegerType: + var optionValueInteger OptionValueInteger + err := json.Unmarshal(*rawMsg, &optionValueInteger) + return &optionValueInteger, err + + case OptionValueStringType: + var optionValueString OptionValueString + err := json.Unmarshal(*rawMsg, &optionValueString) + return &optionValueString, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalUserPrivacySettingRule(rawMsg *json.RawMessage) (UserPrivacySettingRule, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch UserPrivacySettingRuleEnum(objMap["@type"].(string)) { + case UserPrivacySettingRuleAllowAllType: + var userPrivacySettingRuleAllowAll UserPrivacySettingRuleAllowAll + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleAllowAll) + return &userPrivacySettingRuleAllowAll, err + + case UserPrivacySettingRuleAllowContactsType: + var userPrivacySettingRuleAllowContacts UserPrivacySettingRuleAllowContacts + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleAllowContacts) + return &userPrivacySettingRuleAllowContacts, err + + case UserPrivacySettingRuleAllowUsersType: + var userPrivacySettingRuleAllowUsers UserPrivacySettingRuleAllowUsers + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleAllowUsers) + return &userPrivacySettingRuleAllowUsers, err + + case UserPrivacySettingRuleRestrictAllType: + var userPrivacySettingRuleRestrictAll UserPrivacySettingRuleRestrictAll + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleRestrictAll) + return &userPrivacySettingRuleRestrictAll, err + + case UserPrivacySettingRuleRestrictContactsType: + var userPrivacySettingRuleRestrictContacts UserPrivacySettingRuleRestrictContacts + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleRestrictContacts) + return &userPrivacySettingRuleRestrictContacts, err + + case UserPrivacySettingRuleRestrictUsersType: + var userPrivacySettingRuleRestrictUsers UserPrivacySettingRuleRestrictUsers + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleRestrictUsers) + return &userPrivacySettingRuleRestrictUsers, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalUserPrivacySetting(rawMsg *json.RawMessage) (UserPrivacySetting, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch UserPrivacySettingEnum(objMap["@type"].(string)) { + case UserPrivacySettingShowStatusType: + var userPrivacySettingShowStatus UserPrivacySettingShowStatus + err := json.Unmarshal(*rawMsg, &userPrivacySettingShowStatus) + return &userPrivacySettingShowStatus, err + + case UserPrivacySettingAllowChatInvitesType: + var userPrivacySettingAllowChatInvites UserPrivacySettingAllowChatInvites + err := json.Unmarshal(*rawMsg, &userPrivacySettingAllowChatInvites) + return &userPrivacySettingAllowChatInvites, err + + case UserPrivacySettingAllowCallsType: + var userPrivacySettingAllowCalls UserPrivacySettingAllowCalls + err := json.Unmarshal(*rawMsg, &userPrivacySettingAllowCalls) + return &userPrivacySettingAllowCalls, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalChatReportReason(rawMsg *json.RawMessage) (ChatReportReason, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatReportReasonEnum(objMap["@type"].(string)) { + case ChatReportReasonSpamType: + var chatReportReasonSpam ChatReportReasonSpam + err := json.Unmarshal(*rawMsg, &chatReportReasonSpam) + return &chatReportReasonSpam, err + + case ChatReportReasonViolenceType: + var chatReportReasonViolence ChatReportReasonViolence + err := json.Unmarshal(*rawMsg, &chatReportReasonViolence) + return &chatReportReasonViolence, err + + case ChatReportReasonPornographyType: + var chatReportReasonPornography ChatReportReasonPornography + err := json.Unmarshal(*rawMsg, &chatReportReasonPornography) + return &chatReportReasonPornography, err + + case ChatReportReasonCopyrightType: + var chatReportReasonCopyright ChatReportReasonCopyright + err := json.Unmarshal(*rawMsg, &chatReportReasonCopyright) + return &chatReportReasonCopyright, err + + case ChatReportReasonCustomType: + var chatReportReasonCustom ChatReportReasonCustom + err := json.Unmarshal(*rawMsg, &chatReportReasonCustom) + return &chatReportReasonCustom, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalFileType(rawMsg *json.RawMessage) (FileType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch FileTypeEnum(objMap["@type"].(string)) { + case FileTypeNoneType: + var fileTypeNone FileTypeNone + err := json.Unmarshal(*rawMsg, &fileTypeNone) + return &fileTypeNone, err + + case FileTypeAnimationType: + var fileTypeAnimation FileTypeAnimation + err := json.Unmarshal(*rawMsg, &fileTypeAnimation) + return &fileTypeAnimation, err + + case FileTypeAudioType: + var fileTypeAudio FileTypeAudio + err := json.Unmarshal(*rawMsg, &fileTypeAudio) + return &fileTypeAudio, err + + case FileTypeDocumentType: + var fileTypeDocument FileTypeDocument + err := json.Unmarshal(*rawMsg, &fileTypeDocument) + return &fileTypeDocument, err + + case FileTypePhotoType: + var fileTypePhoto FileTypePhoto + err := json.Unmarshal(*rawMsg, &fileTypePhoto) + return &fileTypePhoto, err + + case FileTypeProfilePhotoType: + var fileTypeProfilePhoto FileTypeProfilePhoto + err := json.Unmarshal(*rawMsg, &fileTypeProfilePhoto) + return &fileTypeProfilePhoto, err + + case FileTypeSecretType: + var fileTypeSecret FileTypeSecret + err := json.Unmarshal(*rawMsg, &fileTypeSecret) + return &fileTypeSecret, err + + case FileTypeSecretThumbnailType: + var fileTypeSecretThumbnail FileTypeSecretThumbnail + err := json.Unmarshal(*rawMsg, &fileTypeSecretThumbnail) + return &fileTypeSecretThumbnail, err + + case FileTypeSecureType: + var fileTypeSecure FileTypeSecure + err := json.Unmarshal(*rawMsg, &fileTypeSecure) + return &fileTypeSecure, err + + case FileTypeStickerType: + var fileTypeSticker FileTypeSticker + err := json.Unmarshal(*rawMsg, &fileTypeSticker) + return &fileTypeSticker, err + + case FileTypeThumbnailType: + var fileTypeThumbnail FileTypeThumbnail + err := json.Unmarshal(*rawMsg, &fileTypeThumbnail) + return &fileTypeThumbnail, err + + case FileTypeUnknownType: + var fileTypeUnknown FileTypeUnknown + err := json.Unmarshal(*rawMsg, &fileTypeUnknown) + return &fileTypeUnknown, err + + case FileTypeVideoType: + var fileTypeVideo FileTypeVideo + err := json.Unmarshal(*rawMsg, &fileTypeVideo) + return &fileTypeVideo, err + + case FileTypeVideoNoteType: + var fileTypeVideoNote FileTypeVideoNote + err := json.Unmarshal(*rawMsg, &fileTypeVideoNote) + return &fileTypeVideoNote, err + + case FileTypeVoiceNoteType: + var fileTypeVoiceNote FileTypeVoiceNote + err := json.Unmarshal(*rawMsg, &fileTypeVoiceNote) + return &fileTypeVoiceNote, err + + case FileTypeWallpaperType: + var fileTypeWallpaper FileTypeWallpaper + err := json.Unmarshal(*rawMsg, &fileTypeWallpaper) + return &fileTypeWallpaper, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalNetworkType(rawMsg *json.RawMessage) (NetworkType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch NetworkTypeEnum(objMap["@type"].(string)) { + case NetworkTypeNoneType: + var networkTypeNone NetworkTypeNone + err := json.Unmarshal(*rawMsg, &networkTypeNone) + return &networkTypeNone, err + + case NetworkTypeMobileType: + var networkTypeMobile NetworkTypeMobile + err := json.Unmarshal(*rawMsg, &networkTypeMobile) + return &networkTypeMobile, err + + case NetworkTypeMobileRoamingType: + var networkTypeMobileRoaming NetworkTypeMobileRoaming + err := json.Unmarshal(*rawMsg, &networkTypeMobileRoaming) + return &networkTypeMobileRoaming, err + + case NetworkTypeWiFiType: + var networkTypeWiFi NetworkTypeWiFi + err := json.Unmarshal(*rawMsg, &networkTypeWiFi) + return &networkTypeWiFi, err + + case NetworkTypeOtherType: + var networkTypeOther NetworkTypeOther + err := json.Unmarshal(*rawMsg, &networkTypeOther) + return &networkTypeOther, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalNetworkStatisticsEntry(rawMsg *json.RawMessage) (NetworkStatisticsEntry, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch NetworkStatisticsEntryEnum(objMap["@type"].(string)) { + case NetworkStatisticsEntryFileType: + var networkStatisticsEntryFile NetworkStatisticsEntryFile + err := json.Unmarshal(*rawMsg, &networkStatisticsEntryFile) + return &networkStatisticsEntryFile, err + + case NetworkStatisticsEntryCallType: + var networkStatisticsEntryCall NetworkStatisticsEntryCall + err := json.Unmarshal(*rawMsg, &networkStatisticsEntryCall) + return &networkStatisticsEntryCall, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalConnectionState(rawMsg *json.RawMessage) (ConnectionState, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ConnectionStateEnum(objMap["@type"].(string)) { + case ConnectionStateWaitingForNetworkType: + var connectionStateWaitingForNetwork ConnectionStateWaitingForNetwork + err := json.Unmarshal(*rawMsg, &connectionStateWaitingForNetwork) + return &connectionStateWaitingForNetwork, err + + case ConnectionStateConnectingToProxyType: + var connectionStateConnectingToProxy ConnectionStateConnectingToProxy + err := json.Unmarshal(*rawMsg, &connectionStateConnectingToProxy) + return &connectionStateConnectingToProxy, err + + case ConnectionStateConnectingType: + var connectionStateConnecting ConnectionStateConnecting + err := json.Unmarshal(*rawMsg, &connectionStateConnecting) + return &connectionStateConnecting, err + + case ConnectionStateUpdatingType: + var connectionStateUpdating ConnectionStateUpdating + err := json.Unmarshal(*rawMsg, &connectionStateUpdating) + return &connectionStateUpdating, err + + case ConnectionStateReadyType: + var connectionStateReady ConnectionStateReady + err := json.Unmarshal(*rawMsg, &connectionStateReady) + return &connectionStateReady, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalTopChatCategory(rawMsg *json.RawMessage) (TopChatCategory, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch TopChatCategoryEnum(objMap["@type"].(string)) { + case TopChatCategoryUsersType: + var topChatCategoryUsers TopChatCategoryUsers + err := json.Unmarshal(*rawMsg, &topChatCategoryUsers) + return &topChatCategoryUsers, err + + case TopChatCategoryBotsType: + var topChatCategoryBots TopChatCategoryBots + err := json.Unmarshal(*rawMsg, &topChatCategoryBots) + return &topChatCategoryBots, err + + case TopChatCategoryGroupsType: + var topChatCategoryGroups TopChatCategoryGroups + err := json.Unmarshal(*rawMsg, &topChatCategoryGroups) + return &topChatCategoryGroups, err + + case TopChatCategoryChannelsType: + var topChatCategoryChannels TopChatCategoryChannels + err := json.Unmarshal(*rawMsg, &topChatCategoryChannels) + return &topChatCategoryChannels, err + + case TopChatCategoryInlineBotsType: + var topChatCategoryInlineBots TopChatCategoryInlineBots + err := json.Unmarshal(*rawMsg, &topChatCategoryInlineBots) + return &topChatCategoryInlineBots, err + + case TopChatCategoryCallsType: + var topChatCategoryCalls TopChatCategoryCalls + err := json.Unmarshal(*rawMsg, &topChatCategoryCalls) + return &topChatCategoryCalls, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalTMeURLType(rawMsg *json.RawMessage) (TMeURLType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch TMeURLTypeEnum(objMap["@type"].(string)) { + case TMeURLTypeUserType: + var tMeURLTypeUser TMeURLTypeUser + err := json.Unmarshal(*rawMsg, &tMeURLTypeUser) + return &tMeURLTypeUser, err + + case TMeURLTypeSupergroupType: + var tMeURLTypeSupergroup TMeURLTypeSupergroup + err := json.Unmarshal(*rawMsg, &tMeURLTypeSupergroup) + return &tMeURLTypeSupergroup, err + + case TMeURLTypeChatInviteType: + var tMeURLTypeChatInvite TMeURLTypeChatInvite + err := json.Unmarshal(*rawMsg, &tMeURLTypeChatInvite) + return &tMeURLTypeChatInvite, err + + case TMeURLTypeStickerSetType: + var tMeURLTypeStickerSet TMeURLTypeStickerSet + err := json.Unmarshal(*rawMsg, &tMeURLTypeStickerSet) + return &tMeURLTypeStickerSet, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalTextParseMode(rawMsg *json.RawMessage) (TextParseMode, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch TextParseModeEnum(objMap["@type"].(string)) { + case TextParseModeMarkdownType: + var textParseModeMarkdown TextParseModeMarkdown + err := json.Unmarshal(*rawMsg, &textParseModeMarkdown) + return &textParseModeMarkdown, err + + case TextParseModeHTMLType: + var textParseModeHTML TextParseModeHTML + err := json.Unmarshal(*rawMsg, &textParseModeHTML) + return &textParseModeHTML, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalProxyType(rawMsg *json.RawMessage) (ProxyType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ProxyTypeEnum(objMap["@type"].(string)) { + case ProxyTypeSocks5Type: + var proxyTypeSocks5 ProxyTypeSocks5 + err := json.Unmarshal(*rawMsg, &proxyTypeSocks5) + return &proxyTypeSocks5, err + + case ProxyTypeHttpType: + var proxyTypeHttp ProxyTypeHttp + err := json.Unmarshal(*rawMsg, &proxyTypeHttp) + return &proxyTypeHttp, err + + case ProxyTypeMtprotoType: + var proxyTypeMtproto ProxyTypeMtproto + err := json.Unmarshal(*rawMsg, &proxyTypeMtproto) + return &proxyTypeMtproto, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalUpdate(rawMsg *json.RawMessage) (Update, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch UpdateEnum(objMap["@type"].(string)) { + case UpdateAuthorizationStateType: + var updateAuthorizationState UpdateAuthorizationState + err := json.Unmarshal(*rawMsg, &updateAuthorizationState) + return &updateAuthorizationState, err + + case UpdateNewMessageType: + var updateNewMessage UpdateNewMessage + err := json.Unmarshal(*rawMsg, &updateNewMessage) + return &updateNewMessage, err + + case UpdateMessageSendAcknowledgedType: + var updateMessageSendAcknowledged UpdateMessageSendAcknowledged + err := json.Unmarshal(*rawMsg, &updateMessageSendAcknowledged) + return &updateMessageSendAcknowledged, err + + case UpdateMessageSendSucceededType: + var updateMessageSendSucceeded UpdateMessageSendSucceeded + err := json.Unmarshal(*rawMsg, &updateMessageSendSucceeded) + return &updateMessageSendSucceeded, err + + case UpdateMessageSendFailedType: + var updateMessageSendFailed UpdateMessageSendFailed + err := json.Unmarshal(*rawMsg, &updateMessageSendFailed) + return &updateMessageSendFailed, err + + case UpdateMessageContentType: + var updateMessageContent UpdateMessageContent + err := json.Unmarshal(*rawMsg, &updateMessageContent) + return &updateMessageContent, err + + case UpdateMessageEditedType: + var updateMessageEdited UpdateMessageEdited + err := json.Unmarshal(*rawMsg, &updateMessageEdited) + return &updateMessageEdited, err + + case UpdateMessageViewsType: + var updateMessageViews UpdateMessageViews + err := json.Unmarshal(*rawMsg, &updateMessageViews) + return &updateMessageViews, err + + case UpdateMessageContentOpenedType: + var updateMessageContentOpened UpdateMessageContentOpened + err := json.Unmarshal(*rawMsg, &updateMessageContentOpened) + return &updateMessageContentOpened, err + + case UpdateMessageMentionReadType: + var updateMessageMentionRead UpdateMessageMentionRead + err := json.Unmarshal(*rawMsg, &updateMessageMentionRead) + return &updateMessageMentionRead, err + + case UpdateNewChatType: + var updateNewChat UpdateNewChat + err := json.Unmarshal(*rawMsg, &updateNewChat) + return &updateNewChat, err + + case UpdateChatTitleType: + var updateChatTitle UpdateChatTitle + err := json.Unmarshal(*rawMsg, &updateChatTitle) + return &updateChatTitle, err + + case UpdateChatPhotoType: + var updateChatPhoto UpdateChatPhoto + err := json.Unmarshal(*rawMsg, &updateChatPhoto) + return &updateChatPhoto, err + + case UpdateChatLastMessageType: + var updateChatLastMessage UpdateChatLastMessage + err := json.Unmarshal(*rawMsg, &updateChatLastMessage) + return &updateChatLastMessage, err + + case UpdateChatOrderType: + var updateChatOrder UpdateChatOrder + err := json.Unmarshal(*rawMsg, &updateChatOrder) + return &updateChatOrder, err + + case UpdateChatIsPinnedType: + var updateChatIsPinned UpdateChatIsPinned + err := json.Unmarshal(*rawMsg, &updateChatIsPinned) + return &updateChatIsPinned, err + + case UpdateChatIsMarkedAsUnreadType: + var updateChatIsMarkedAsUnread UpdateChatIsMarkedAsUnread + err := json.Unmarshal(*rawMsg, &updateChatIsMarkedAsUnread) + return &updateChatIsMarkedAsUnread, err + + case UpdateChatIsSponsoredType: + var updateChatIsSponsored UpdateChatIsSponsored + err := json.Unmarshal(*rawMsg, &updateChatIsSponsored) + return &updateChatIsSponsored, err + + case UpdateChatDefaultDisableNotificationType: + var updateChatDefaultDisableNotification UpdateChatDefaultDisableNotification + err := json.Unmarshal(*rawMsg, &updateChatDefaultDisableNotification) + return &updateChatDefaultDisableNotification, err + + case UpdateChatReadInboxType: + var updateChatReadInbox UpdateChatReadInbox + err := json.Unmarshal(*rawMsg, &updateChatReadInbox) + return &updateChatReadInbox, err + + case UpdateChatReadOutboxType: + var updateChatReadOutbox UpdateChatReadOutbox + err := json.Unmarshal(*rawMsg, &updateChatReadOutbox) + return &updateChatReadOutbox, err + + case UpdateChatUnreadMentionCountType: + var updateChatUnreadMentionCount UpdateChatUnreadMentionCount + err := json.Unmarshal(*rawMsg, &updateChatUnreadMentionCount) + return &updateChatUnreadMentionCount, err + + case UpdateChatNotificationSettingsType: + var updateChatNotificationSettings UpdateChatNotificationSettings + err := json.Unmarshal(*rawMsg, &updateChatNotificationSettings) + return &updateChatNotificationSettings, err + + case UpdateScopeNotificationSettingsType: + var updateScopeNotificationSettings UpdateScopeNotificationSettings + err := json.Unmarshal(*rawMsg, &updateScopeNotificationSettings) + return &updateScopeNotificationSettings, err + + case UpdateChatReplyMarkupType: + var updateChatReplyMarkup UpdateChatReplyMarkup + err := json.Unmarshal(*rawMsg, &updateChatReplyMarkup) + return &updateChatReplyMarkup, err + + case UpdateChatDraftMessageType: + var updateChatDraftMessage UpdateChatDraftMessage + err := json.Unmarshal(*rawMsg, &updateChatDraftMessage) + return &updateChatDraftMessage, err + + case UpdateDeleteMessagesType: + var updateDeleteMessages UpdateDeleteMessages + err := json.Unmarshal(*rawMsg, &updateDeleteMessages) + return &updateDeleteMessages, err + + case UpdateUserChatActionType: + var updateUserChatAction UpdateUserChatAction + err := json.Unmarshal(*rawMsg, &updateUserChatAction) + return &updateUserChatAction, err + + case UpdateUserStatusType: + var updateUserStatus UpdateUserStatus + err := json.Unmarshal(*rawMsg, &updateUserStatus) + return &updateUserStatus, err + + case UpdateUserType: + var updateUser UpdateUser + err := json.Unmarshal(*rawMsg, &updateUser) + return &updateUser, err + + case UpdateBasicGroupType: + var updateBasicGroup UpdateBasicGroup + err := json.Unmarshal(*rawMsg, &updateBasicGroup) + return &updateBasicGroup, err + + case UpdateSupergroupType: + var updateSupergroup UpdateSupergroup + err := json.Unmarshal(*rawMsg, &updateSupergroup) + return &updateSupergroup, err + + case UpdateSecretChatType: + var updateSecretChat UpdateSecretChat + err := json.Unmarshal(*rawMsg, &updateSecretChat) + return &updateSecretChat, err + + case UpdateUserFullInfoType: + var updateUserFullInfo UpdateUserFullInfo + err := json.Unmarshal(*rawMsg, &updateUserFullInfo) + return &updateUserFullInfo, err + + case UpdateBasicGroupFullInfoType: + var updateBasicGroupFullInfo UpdateBasicGroupFullInfo + err := json.Unmarshal(*rawMsg, &updateBasicGroupFullInfo) + return &updateBasicGroupFullInfo, err + + case UpdateSupergroupFullInfoType: + var updateSupergroupFullInfo UpdateSupergroupFullInfo + err := json.Unmarshal(*rawMsg, &updateSupergroupFullInfo) + return &updateSupergroupFullInfo, err + + case UpdateServiceNotificationType: + var updateServiceNotification UpdateServiceNotification + err := json.Unmarshal(*rawMsg, &updateServiceNotification) + return &updateServiceNotification, err + + case UpdateFileType: + var updateFile UpdateFile + err := json.Unmarshal(*rawMsg, &updateFile) + return &updateFile, err + + case UpdateFileGenerationStartType: + var updateFileGenerationStart UpdateFileGenerationStart + err := json.Unmarshal(*rawMsg, &updateFileGenerationStart) + return &updateFileGenerationStart, err + + case UpdateFileGenerationStopType: + var updateFileGenerationStop UpdateFileGenerationStop + err := json.Unmarshal(*rawMsg, &updateFileGenerationStop) + return &updateFileGenerationStop, err + + case UpdateCallType: + var updateCall UpdateCall + err := json.Unmarshal(*rawMsg, &updateCall) + return &updateCall, err + + case UpdateUserPrivacySettingRulesType: + var updateUserPrivacySettingRules UpdateUserPrivacySettingRules + err := json.Unmarshal(*rawMsg, &updateUserPrivacySettingRules) + return &updateUserPrivacySettingRules, err + + case UpdateUnreadMessageCountType: + var updateUnreadMessageCount UpdateUnreadMessageCount + err := json.Unmarshal(*rawMsg, &updateUnreadMessageCount) + return &updateUnreadMessageCount, err + + case UpdateUnreadChatCountType: + var updateUnreadChatCount UpdateUnreadChatCount + err := json.Unmarshal(*rawMsg, &updateUnreadChatCount) + return &updateUnreadChatCount, err + + case UpdateOptionType: + var updateOption UpdateOption + err := json.Unmarshal(*rawMsg, &updateOption) + return &updateOption, err + + case UpdateInstalledStickerSetsType: + var updateInstalledStickerSets UpdateInstalledStickerSets + err := json.Unmarshal(*rawMsg, &updateInstalledStickerSets) + return &updateInstalledStickerSets, err + + case UpdateTrendingStickerSetsType: + var updateTrendingStickerSets UpdateTrendingStickerSets + err := json.Unmarshal(*rawMsg, &updateTrendingStickerSets) + return &updateTrendingStickerSets, err + + case UpdateRecentStickersType: + var updateRecentStickers UpdateRecentStickers + err := json.Unmarshal(*rawMsg, &updateRecentStickers) + return &updateRecentStickers, err + + case UpdateFavoriteStickersType: + var updateFavoriteStickers UpdateFavoriteStickers + err := json.Unmarshal(*rawMsg, &updateFavoriteStickers) + return &updateFavoriteStickers, err + + case UpdateSavedAnimationsType: + var updateSavedAnimations UpdateSavedAnimations + err := json.Unmarshal(*rawMsg, &updateSavedAnimations) + return &updateSavedAnimations, err + + case UpdateLanguagePackStringsType: + var updateLanguagePackStrings UpdateLanguagePackStrings + err := json.Unmarshal(*rawMsg, &updateLanguagePackStrings) + return &updateLanguagePackStrings, err + + case UpdateConnectionStateType: + var updateConnectionState UpdateConnectionState + err := json.Unmarshal(*rawMsg, &updateConnectionState) + return &updateConnectionState, err + + case UpdateTermsOfServiceType: + var updateTermsOfService UpdateTermsOfService + err := json.Unmarshal(*rawMsg, &updateTermsOfService) + return &updateTermsOfService, err + + case UpdateNewInlineQueryType: + var updateNewInlineQuery UpdateNewInlineQuery + err := json.Unmarshal(*rawMsg, &updateNewInlineQuery) + return &updateNewInlineQuery, err + + case UpdateNewChosenInlineResultType: + var updateNewChosenInlineResult UpdateNewChosenInlineResult + err := json.Unmarshal(*rawMsg, &updateNewChosenInlineResult) + return &updateNewChosenInlineResult, err + + case UpdateNewCallbackQueryType: + var updateNewCallbackQuery UpdateNewCallbackQuery + err := json.Unmarshal(*rawMsg, &updateNewCallbackQuery) + return &updateNewCallbackQuery, err + + case UpdateNewInlineCallbackQueryType: + var updateNewInlineCallbackQuery UpdateNewInlineCallbackQuery + err := json.Unmarshal(*rawMsg, &updateNewInlineCallbackQuery) + return &updateNewInlineCallbackQuery, err + + case UpdateNewShippingQueryType: + var updateNewShippingQuery UpdateNewShippingQuery + err := json.Unmarshal(*rawMsg, &updateNewShippingQuery) + return &updateNewShippingQuery, err + + case UpdateNewPreCheckoutQueryType: + var updateNewPreCheckoutQuery UpdateNewPreCheckoutQuery + err := json.Unmarshal(*rawMsg, &updateNewPreCheckoutQuery) + return &updateNewPreCheckoutQuery, err + + case UpdateNewCustomEventType: + var updateNewCustomEvent UpdateNewCustomEvent + err := json.Unmarshal(*rawMsg, &updateNewCustomEvent) + return &updateNewCustomEvent, err + + case UpdateNewCustomQueryType: + var updateNewCustomQuery UpdateNewCustomQuery + err := json.Unmarshal(*rawMsg, &updateNewCustomQuery) + return &updateNewCustomQuery, err + + default: + return nil, fmt.Errorf("Error unmarshaling, unknown type:" + objMap["@type"].(string)) + } +} diff --git a/vendor/github.com/rs/zerolog/.gitignore b/vendor/github.com/rs/zerolog/.gitignore new file mode 100644 index 0000000..8ebe58b --- /dev/null +++ b/vendor/github.com/rs/zerolog/.gitignore @@ -0,0 +1,25 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test +tmp + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/vendor/github.com/rs/zerolog/.travis.yml b/vendor/github.com/rs/zerolog/.travis.yml new file mode 100644 index 0000000..64d202a --- /dev/null +++ b/vendor/github.com/rs/zerolog/.travis.yml @@ -0,0 +1,13 @@ +language: go +go: +- "1.7" +- "1.8" +- "1.9" +- "1.10" +- "master" +matrix: + allow_failures: + - go: "master" +script: + - go test -v -race -cpu=1,2,4 -bench . -benchmem ./... + - go test -v -tags binary_log -race -cpu=1,2,4 -bench . -benchmem ./... diff --git a/vendor/github.com/rs/zerolog/CNAME b/vendor/github.com/rs/zerolog/CNAME new file mode 100644 index 0000000..9ce57a6 --- /dev/null +++ b/vendor/github.com/rs/zerolog/CNAME @@ -0,0 +1 @@ +zerolog.io \ No newline at end of file diff --git a/vendor/github.com/rs/zerolog/LICENSE b/vendor/github.com/rs/zerolog/LICENSE new file mode 100644 index 0000000..677e07f --- /dev/null +++ b/vendor/github.com/rs/zerolog/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Olivier Poitrey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/rs/zerolog/README.md b/vendor/github.com/rs/zerolog/README.md new file mode 100644 index 0000000..eefc1f6 --- /dev/null +++ b/vendor/github.com/rs/zerolog/README.md @@ -0,0 +1,591 @@ +# Zero Allocation JSON Logger + +[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/zerolog) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/zerolog/master/LICENSE) [![Build Status](https://travis-ci.org/rs/zerolog.svg?branch=master)](https://travis-ci.org/rs/zerolog) [![Coverage](http://gocover.io/_badge/github.com/rs/zerolog)](http://gocover.io/github.com/rs/zerolog) + +The zerolog package provides a fast and simple logger dedicated to JSON output. + +Zerolog's API is designed to provide both a great developer experience and stunning [performance](#benchmarks). Its unique chaining API allows zerolog to write JSON (or CBOR) log events by avoiding allocations and reflection. + +Uber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance. + +To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) [`zerolog.ConsoleWriter`](#pretty-logging). + +![Pretty Logging Image](pretty.png) + +## Who uses zerolog + +Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog) and add your company / project to the list. + +## Features + +* Blazing fast +* Low to zero allocation +* Level logging +* Sampling +* Hooks +* Contextual fields +* `context.Context` integration +* `net/http` helpers +* JSON and CBOR encoding formats +* Pretty logging for development + +## Installation + +```go +go get -u github.com/rs/zerolog/log +``` + +## Getting Started + +### Simple Logging Example + +For simple logging, import the global logger package **github.com/rs/zerolog/log** + +```go +package main + +import ( + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +func main() { + // UNIX Time is faster and smaller than most timestamps + // If you set zerolog.TimeFieldFormat to an empty string, + // logs will write with UNIX time + zerolog.TimeFieldFormat = "" + + log.Print("hello world") +} + +// Output: {"time":1516134303,"level":"debug","message":"hello world"} +``` +> Note: By default log writes to `os.Stderr` +> Note: The default log level for `log.Print` is *debug* + +### Contextual Logging + +**zerolog** allows data to be added to log messages in the form of key:value pairs. The data added to the message adds "context" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below: + +```go +package main + +import ( + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +func main() { + zerolog.TimeFieldFormat = "" + + log.Debug(). + Str("Scale", "833 cents"). + Float64("Interval", 833.09). + Msg("Fibonacci is everywhere") +} + +// Output: {"time":1524104936,"level":"debug","Scale":"833 cents","Interval":833.09,"message":"Fibonacci is everywhere"} +``` + +> You'll note in the above example that when adding contextual fields, the fields are strongly typed. You can find the full list of supported fields [here](#standard-types) + +### Leveled Logging + +#### Simple Leveled Logging Example + +```go +package main + +import ( + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +func main() { + zerolog.TimeFieldFormat = "" + + log.Info().Msg("hello world") +} + +// Output: {"time":1516134303,"level":"info","message":"hello world"} +``` + +> It is very important to note that when using the **zerolog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this. + +**zerolog** allows for logging at the following levels (from highest to lowest): + +* panic (`zerolog.PanicLevel`, 5) +* fatal (`zerolog.FatalLevel`, 4) +* error (`zerolog.ErrorLevel`, 3) +* warn (`zerolog.WarnLevel`, 2) +* info (`zerolog.InfoLevel`, 1) +* debug (`zerolog.DebugLevel`, 0) + +You can set the Global logging level to any of these options using the `SetGlobalLevel` function in the zerolog package, passing in one of the given constants above, e.g. `zerolog.InfoLevel` would be the "info" level. Whichever level is chosen, all logs with a level greater than or equal to that level will be written. To turn off logging entirely, pass the `zerolog.Disabled` constant. + +#### Setting Global Log Level + +This example uses command-line flags to demonstrate various outputs depending on the chosen log level. + +```go +package main + +import ( + "flag" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +func main() { + zerolog.TimeFieldFormat = "" + debug := flag.Bool("debug", false, "sets log level to debug") + + flag.Parse() + + // Default level for this example is info, unless debug flag is present + zerolog.SetGlobalLevel(zerolog.InfoLevel) + if *debug { + zerolog.SetGlobalLevel(zerolog.DebugLevel) + } + + log.Debug().Msg("This message appears only when log level set to Debug") + log.Info().Msg("This message appears when log level set to Debug or Info") + + if e := log.Debug(); e.Enabled() { + // Compute log output only if enabled. + value := "bar" + e.Str("foo", value).Msg("some debug message") + } +} +``` + +Info Output (no flag) + +```bash +$ ./logLevelExample +{"time":1516387492,"level":"info","message":"This message appears when log level set to Debug or Info"} +``` + +Debug Output (debug flag set) + +```bash +$ ./logLevelExample -debug +{"time":1516387573,"level":"debug","message":"This message appears only when log level set to Debug"} +{"time":1516387573,"level":"info","message":"This message appears when log level set to Debug or Info"} +{"time":1516387573,"level":"debug","foo":"bar","message":"some debug message"} +``` + +#### Logging without Level or Message + +You may choose to log without a specific level by using the `Log` method. You may also write without a message by setting an empty string in the `msg string` parameter of the `Msg` method. Both are demonstrated in the example below. + +```go +package main + +import ( + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +func main() { + zerolog.TimeFieldFormat = "" + + log.Log(). + Str("foo", "bar"). + Msg("") +} + +// Output: {"time":1494567715,"foo":"bar"} +``` + +#### Logging Fatal Messages + +```go +package main + +import ( + "errors" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +func main() { + err := errors.New("A repo man spends his life getting into tense situations") + service := "myservice" + + zerolog.TimeFieldFormat = "" + + log.Fatal(). + Err(err). + Str("service", service). + Msgf("Cannot start %s", service) +} + +// Output: {"time":1516133263,"level":"fatal","error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"} +// exit status 1 +``` + +> NOTE: Using `Msgf` generates one allocation even when the logger is disabled. + +### Create logger instance to manage different outputs + +```go +logger := zerolog.New(os.Stderr).With().Timestamp().Logger() + +logger.Info().Str("foo", "bar").Msg("hello world") + +// Output: {"level":"info","time":1494567715,"message":"hello world","foo":"bar"} +``` + +### Sub-loggers let you chain loggers with additional context + +```go +sublogger := log.With(). + Str("component", "foo"). + Logger() +sublogger.Info().Msg("hello world") + +// Output: {"level":"info","time":1494567715,"message":"hello world","component":"foo"} +``` + +### Pretty logging + +To log a human-friendly, colorized output, use `zerolog.ConsoleWriter`: + +```go +log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) + +log.Info().Str("foo", "bar").Msg("Hello world") + +// Output: 3:04PM INF Hello World foo=bar +``` + +To customize the configuration and formatting: + +```go +output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339} +output.FormatLevel = func(i interface{}) string { + return strings.ToUpper(fmt.Sprintf("| %-6s|", i)) +} +output.FormatMessage = func(i interface{}) string { + return fmt.Sprintf("***%s****", i) +} +output.FormatFieldName = func(i interface{}) string { + return fmt.Sprintf("%s:", i) +} +output.FormatFieldValue = func(i interface{}) string { + return strings.ToUpper(fmt.Sprintf("%s", i)) +} + +log := zerolog.New(output).With().Timestamp().Logger() + +log.Info().Str("foo", "bar").Msg("Hello World") + +// Output: 2006-01-02T15:04:05Z07:00 | INFO | ***Hello World**** foo:BAR +``` + +### Sub dictionary + +```go +log.Info(). + Str("foo", "bar"). + Dict("dict", zerolog.Dict(). + Str("bar", "baz"). + Int("n", 1), + ).Msg("hello world") + +// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"} +``` + +### Customize automatic field names + +```go +zerolog.TimestampFieldName = "t" +zerolog.LevelFieldName = "l" +zerolog.MessageFieldName = "m" + +log.Info().Msg("hello world") + +// Output: {"l":"info","t":1494567715,"m":"hello world"} +``` + +### Add contextual fields to the global logger + +```go +log.Logger = log.With().Str("foo", "bar").Logger() +``` + +### Add file and line number to log + +```go +log.Logger = log.With().Caller().Logger() +log.Info().Msg("hello world") + +// Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"} +``` + + +### Thread-safe, lock-free, non-blocking writer + +If your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follow: + +```go +wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) { + fmt.Printf("Logger Dropped %d messages", missed) + }) +log := zerolog.New(w) +log.Print("test") +``` + +You will need to install `code.cloudfoundry.org/go-diodes` to use this feature. + +### Log Sampling + +```go +sampled := log.Sample(&zerolog.BasicSampler{N: 10}) +sampled.Info().Msg("will be logged every 10 messages") + +// Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"} +``` + +More advanced sampling: + +```go +// Will let 5 debug messages per period of 1 second. +// Over 5 debug message, 1 every 100 debug messages are logged. +// Other levels are not sampled. +sampled := log.Sample(zerolog.LevelSampler{ + DebugSampler: &zerolog.BurstSampler{ + Burst: 5, + Period: 1*time.Second, + NextSampler: &zerolog.BasicSampler{N: 100}, + }, +}) +sampled.Debug().Msg("hello world") + +// Output: {"time":1494567715,"level":"debug","message":"hello world"} +``` + +### Hooks + +```go +type SeverityHook struct{} + +func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { + if level != zerolog.NoLevel { + e.Str("severity", level.String()) + } +} + +hooked := log.Hook(SeverityHook{}) +hooked.Warn().Msg("") + +// Output: {"level":"warn","severity":"warn"} +``` + +### Pass a sub-logger by context + +```go +ctx := log.With().Str("component", "module").Logger().WithContext(ctx) + +log.Ctx(ctx).Info().Msg("hello world") + +// Output: {"component":"module","level":"info","message":"hello world"} +``` + +### Set as standard logger output + +```go +log := zerolog.New(os.Stdout).With(). + Str("foo", "bar"). + Logger() + +stdlog.SetFlags(0) +stdlog.SetOutput(log) + +stdlog.Print("hello world") + +// Output: {"foo":"bar","message":"hello world"} +``` + +### Integration with `net/http` + +The `github.com/rs/zerolog/hlog` package provides some helpers to integrate zerolog with `http.Handler`. + +In this example we use [alice](https://github.com/justinas/alice) to install logger for better readability. + +```go +log := zerolog.New(os.Stdout).With(). + Timestamp(). + Str("role", "my-service"). + Str("host", host). + Logger() + +c := alice.New() + +// Install the logger handler with default output on the console +c = c.Append(hlog.NewHandler(log)) + +// Install some provided extra handler to set some request's context fields. +// Thanks to those handler, all our logs will come with some pre-populated fields. +c = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) { + hlog.FromRequest(r).Info(). + Str("method", r.Method). + Str("url", r.URL.String()). + Int("status", status). + Int("size", size). + Dur("duration", duration). + Msg("") +})) +c = c.Append(hlog.RemoteAddrHandler("ip")) +c = c.Append(hlog.UserAgentHandler("user_agent")) +c = c.Append(hlog.RefererHandler("referer")) +c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id")) + +// Here is your final handler +h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Get the logger from the request's context. You can safely assume it + // will be always there: if the handler is removed, hlog.FromRequest + // will return a no-op logger. + hlog.FromRequest(r).Info(). + Str("user", "current user"). + Str("status", "ok"). + Msg("Something happened") + + // Output: {"level":"info","time":"2001-02-03T04:05:06Z","role":"my-service","host":"local-hostname","req_id":"b4g0l5t6tfid6dtrapu0","user":"current user","status":"ok","message":"Something happened"} +})) +http.Handle("/", h) + +if err := http.ListenAndServe(":8080", nil); err != nil { + log.Fatal().Err(err).Msg("Startup failed") +} +``` + +## Global Settings + +Some settings can be changed and will by applied to all loggers: + +* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods). +* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Set this to `zerolog.Disabled` to disable logging altogether (quiet mode). +* `zerolog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events. +* `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name. +* `zerolog.LevelFieldName`: Can be set to customize level field name. +* `zerolog.MessageFieldName`: Can be set to customize message field name. +* `zerolog.ErrorFieldName`: Can be set to customize `Err` field name. +* `zerolog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with an empty string, times are formated as UNIX timestamp. + // DurationFieldUnit defines the unit for time.Duration type fields added + // using the Dur method. +* `DurationFieldUnit`: Sets the unit of the fields added by `Dur` (default: `time.Millisecond`). +* `DurationFieldInteger`: If set to true, `Dur` fields are formatted as integers instead of floats. +* `ErrorHandler`: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking. + +## Field Types + +### Standard Types + +* `Str` +* `Bool` +* `Int`, `Int8`, `Int16`, `Int32`, `Int64` +* `Uint`, `Uint8`, `Uint16`, `Uint32`, `Uint64` +* `Float32`, `Float64` + +### Advanced Fields + +* `Err`: Takes an `error` and render it as a string using the `zerolog.ErrorFieldName` field name. +* `Timestamp`: Insert a timestamp field with `zerolog.TimestampFieldName` field name and formatted using `zerolog.TimeFieldFormat`. +* `Time`: Adds a field with the time formated with the `zerolog.TimeFieldFormat`. +* `Dur`: Adds a field with a `time.Duration`. +* `Dict`: Adds a sub-key/value as a field of the event. +* `Interface`: Uses reflection to marshal the type. + +## Binary Encoding + +In addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](http://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows: + +```bash +go build -tags binary_log . +``` + +To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work +with zerolog library is [CSD](https://github.com/toravir/csd/). + +## Related Projects + +* [grpc-zerolog](https://github.com/cheapRoc/grpc-zerolog): Implementation of `grpclog.LoggerV2` interface using `zerolog` + +## Benchmarks + +See [logbench](http://hackemist.com/logbench/) for more comprehensive and up-to-date benchmarks. + +All operations are allocation free (those numbers *include* JSON encoding): + +```text +BenchmarkLogEmpty-8 100000000 19.1 ns/op 0 B/op 0 allocs/op +BenchmarkDisabled-8 500000000 4.07 ns/op 0 B/op 0 allocs/op +BenchmarkInfo-8 30000000 42.5 ns/op 0 B/op 0 allocs/op +BenchmarkContextFields-8 30000000 44.9 ns/op 0 B/op 0 allocs/op +BenchmarkLogFields-8 10000000 184 ns/op 0 B/op 0 allocs/op +``` + +There are a few Go logging benchmarks and comparisons that include zerolog. + +* [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) +* [uber-common/zap](https://github.com/uber-go/zap#performance) + +Using Uber's zap comparison benchmark: + +Log a message and 10 fields: + +| Library | Time | Bytes Allocated | Objects Allocated | +| :--- | :---: | :---: | :---: | +| zerolog | 767 ns/op | 552 B/op | 6 allocs/op | +| :zap: zap | 848 ns/op | 704 B/op | 2 allocs/op | +| :zap: zap (sugared) | 1363 ns/op | 1610 B/op | 20 allocs/op | +| go-kit | 3614 ns/op | 2895 B/op | 66 allocs/op | +| lion | 5392 ns/op | 5807 B/op | 63 allocs/op | +| logrus | 5661 ns/op | 6092 B/op | 78 allocs/op | +| apex/log | 15332 ns/op | 3832 B/op | 65 allocs/op | +| log15 | 20657 ns/op | 5632 B/op | 93 allocs/op | + +Log a message with a logger that already has 10 fields of context: + +| Library | Time | Bytes Allocated | Objects Allocated | +| :--- | :---: | :---: | :---: | +| zerolog | 52 ns/op | 0 B/op | 0 allocs/op | +| :zap: zap | 283 ns/op | 0 B/op | 0 allocs/op | +| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | +| lion | 2702 ns/op | 4074 B/op | 38 allocs/op | +| go-kit | 3378 ns/op | 3046 B/op | 52 allocs/op | +| logrus | 4309 ns/op | 4564 B/op | 63 allocs/op | +| apex/log | 13456 ns/op | 2898 B/op | 51 allocs/op | +| log15 | 14179 ns/op | 2642 B/op | 44 allocs/op | + +Log a static string, without any context or `printf`-style templating: + +| Library | Time | Bytes Allocated | Objects Allocated | +| :--- | :---: | :---: | :---: | +| zerolog | 50 ns/op | 0 B/op | 0 allocs/op | +| :zap: zap | 236 ns/op | 0 B/op | 0 allocs/op | +| standard library | 453 ns/op | 80 B/op | 2 allocs/op | +| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | +| go-kit | 508 ns/op | 656 B/op | 13 allocs/op | +| lion | 771 ns/op | 1224 B/op | 10 allocs/op | +| logrus | 1244 ns/op | 1505 B/op | 27 allocs/op | +| apex/log | 2751 ns/op | 584 B/op | 11 allocs/op | +| log15 | 5181 ns/op | 1592 B/op | 26 allocs/op | + +## Caveats + +Note that zerolog does de-duplication fields. Using the same key multiple times creates multiple keys in final JSON: + +```go +logger := zerolog.New(os.Stderr).With().Timestamp().Logger() +logger.Info(). + Timestamp(). + Msg("dup") +// Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"} +``` + +However, it’s not a big deal as JSON accepts dup keys; the last one prevails. diff --git a/vendor/github.com/rs/zerolog/_config.yml b/vendor/github.com/rs/zerolog/_config.yml new file mode 100644 index 0000000..a1e896d --- /dev/null +++ b/vendor/github.com/rs/zerolog/_config.yml @@ -0,0 +1 @@ +remote_theme: rs/gh-readme diff --git a/vendor/github.com/rs/zerolog/array.go b/vendor/github.com/rs/zerolog/array.go new file mode 100644 index 0000000..aa4f623 --- /dev/null +++ b/vendor/github.com/rs/zerolog/array.go @@ -0,0 +1,224 @@ +package zerolog + +import ( + "net" + "sync" + "time" +) + +var arrayPool = &sync.Pool{ + New: func() interface{} { + return &Array{ + buf: make([]byte, 0, 500), + } + }, +} + +// Array is used to prepopulate an array of items +// which can be re-used to add to log messages. +type Array struct { + buf []byte +} + +func putArray(a *Array) { + // Proper usage of a sync.Pool requires each entry to have approximately + // the same memory cost. To obtain this property when the stored type + // contains a variably-sized buffer, we add a hard limit on the maximum buffer + // to place back in the pool. + // + // See https://golang.org/issue/23199 + const maxSize = 1 << 16 // 64KiB + if cap(a.buf) > maxSize { + return + } + arrayPool.Put(a) +} + +// Arr creates an array to be added to an Event or Context. +func Arr() *Array { + a := arrayPool.Get().(*Array) + a.buf = a.buf[:0] + return a +} + +// MarshalZerologArray method here is no-op - since data is +// already in the needed format. +func (*Array) MarshalZerologArray(*Array) { +} + +func (a *Array) write(dst []byte) []byte { + dst = enc.AppendArrayStart(dst) + if len(a.buf) > 0 { + dst = append(append(dst, a.buf...)) + } + dst = enc.AppendArrayEnd(dst) + putArray(a) + return dst +} + +// Object marshals an object that implement the LogObjectMarshaler +// interface and append append it to the array. +func (a *Array) Object(obj LogObjectMarshaler) *Array { + e := Dict() + obj.MarshalZerologObject(e) + e.buf = enc.AppendEndMarker(e.buf) + a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...) + putEvent(e) + return a +} + +// Str append append the val as a string to the array. +func (a *Array) Str(val string) *Array { + a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), val) + return a +} + +// Bytes append append the val as a string to the array. +func (a *Array) Bytes(val []byte) *Array { + a.buf = enc.AppendBytes(enc.AppendArrayDelim(a.buf), val) + return a +} + +// Hex append append the val as a hex string to the array. +func (a *Array) Hex(val []byte) *Array { + a.buf = enc.AppendHex(enc.AppendArrayDelim(a.buf), val) + return a +} + +// Err serializes and appends the err to the array. +func (a *Array) Err(err error) *Array { + marshaled := ErrorMarshalFunc(err) + switch m := marshaled.(type) { + case LogObjectMarshaler: + e := newEvent(nil, 0) + e.buf = e.buf[:0] + e.appendObject(m) + a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...) + putEvent(e) + case error: + a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m.Error()) + case string: + a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m) + default: + a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), m) + } + + return a +} + +// Bool append append the val as a bool to the array. +func (a *Array) Bool(b bool) *Array { + a.buf = enc.AppendBool(enc.AppendArrayDelim(a.buf), b) + return a +} + +// Int append append i as a int to the array. +func (a *Array) Int(i int) *Array { + a.buf = enc.AppendInt(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Int8 append append i as a int8 to the array. +func (a *Array) Int8(i int8) *Array { + a.buf = enc.AppendInt8(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Int16 append append i as a int16 to the array. +func (a *Array) Int16(i int16) *Array { + a.buf = enc.AppendInt16(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Int32 append append i as a int32 to the array. +func (a *Array) Int32(i int32) *Array { + a.buf = enc.AppendInt32(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Int64 append append i as a int64 to the array. +func (a *Array) Int64(i int64) *Array { + a.buf = enc.AppendInt64(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Uint append append i as a uint to the array. +func (a *Array) Uint(i uint) *Array { + a.buf = enc.AppendUint(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Uint8 append append i as a uint8 to the array. +func (a *Array) Uint8(i uint8) *Array { + a.buf = enc.AppendUint8(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Uint16 append append i as a uint16 to the array. +func (a *Array) Uint16(i uint16) *Array { + a.buf = enc.AppendUint16(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Uint32 append append i as a uint32 to the array. +func (a *Array) Uint32(i uint32) *Array { + a.buf = enc.AppendUint32(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Uint64 append append i as a uint64 to the array. +func (a *Array) Uint64(i uint64) *Array { + a.buf = enc.AppendUint64(enc.AppendArrayDelim(a.buf), i) + return a +} + +// Float32 append append f as a float32 to the array. +func (a *Array) Float32(f float32) *Array { + a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f) + return a +} + +// Float64 append append f as a float64 to the array. +func (a *Array) Float64(f float64) *Array { + a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f) + return a +} + +// Time append append t formated as string using zerolog.TimeFieldFormat. +func (a *Array) Time(t time.Time) *Array { + a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat) + return a +} + +// Dur append append d to the array. +func (a *Array) Dur(d time.Duration) *Array { + a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger) + return a +} + +// Interface append append i marshaled using reflection. +func (a *Array) Interface(i interface{}) *Array { + if obj, ok := i.(LogObjectMarshaler); ok { + return a.Object(obj) + } + a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), i) + return a +} + +// IPAddr adds IPv4 or IPv6 address to the array +func (a *Array) IPAddr(ip net.IP) *Array { + a.buf = enc.AppendIPAddr(enc.AppendArrayDelim(a.buf), ip) + return a +} + +// IPPrefix adds IPv4 or IPv6 Prefix (IP + mask) to the array +func (a *Array) IPPrefix(pfx net.IPNet) *Array { + a.buf = enc.AppendIPPrefix(enc.AppendArrayDelim(a.buf), pfx) + return a +} + +// MACAddr adds a MAC (Ethernet) address to the array +func (a *Array) MACAddr(ha net.HardwareAddr) *Array { + a.buf = enc.AppendMACAddr(enc.AppendArrayDelim(a.buf), ha) + return a +} diff --git a/vendor/github.com/rs/zerolog/console.go b/vendor/github.com/rs/zerolog/console.go new file mode 100644 index 0000000..f25bc32 --- /dev/null +++ b/vendor/github.com/rs/zerolog/console.go @@ -0,0 +1,369 @@ +package zerolog + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +const ( + colorBold = iota + 1 + colorFaint +) + +const ( + colorBlack = iota + 30 + colorRed + colorGreen + colorYellow + colorBlue + colorMagenta + colorCyan + colorWhite +) + +var ( + consoleBufPool = sync.Pool{ + New: func() interface{} { + return bytes.NewBuffer(make([]byte, 0, 100)) + }, + } + + consoleDefaultTimeFormat = time.Kitchen + consoleDefaultFormatter = func(i interface{}) string { return fmt.Sprintf("%s", i) } + consoleDefaultPartsOrder = func() []string { + return []string{ + TimestampFieldName, + LevelFieldName, + CallerFieldName, + MessageFieldName, + } + } + + consoleNoColor = false + consoleTimeFormat = consoleDefaultTimeFormat +) + +// Formatter transforms the input into a formatted string. +type Formatter func(interface{}) string + +// ConsoleWriter parses the JSON input and writes it in an +// (optionally) colorized, human-friendly format to Out. +type ConsoleWriter struct { + // Out is the output destination. + Out io.Writer + + // NoColor disables the colorized output. + NoColor bool + + // TimeFormat specifies the format for timestamp in output. + TimeFormat string + + // PartsOrder defines the order of parts in output. + PartsOrder []string + + FormatTimestamp Formatter + FormatLevel Formatter + FormatCaller Formatter + FormatMessage Formatter + FormatFieldName Formatter + FormatFieldValue Formatter + FormatErrFieldName Formatter + FormatErrFieldValue Formatter +} + +// NewConsoleWriter creates and initializes a new ConsoleWriter. +func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter { + w := ConsoleWriter{ + Out: os.Stdout, + TimeFormat: consoleDefaultTimeFormat, + PartsOrder: consoleDefaultPartsOrder(), + } + + for _, opt := range options { + opt(&w) + } + + return w +} + +// Write transforms the JSON input with formatters and appends to w.Out. +func (w ConsoleWriter) Write(p []byte) (n int, err error) { + if w.PartsOrder == nil { + w.PartsOrder = consoleDefaultPartsOrder() + } + if w.TimeFormat == "" && consoleTimeFormat != consoleDefaultTimeFormat { + consoleTimeFormat = consoleDefaultTimeFormat + } + if w.TimeFormat != "" && consoleTimeFormat != w.TimeFormat { + consoleTimeFormat = w.TimeFormat + } + if w.NoColor == false && consoleNoColor != false { + consoleNoColor = false + } + if w.NoColor == true && consoleNoColor != w.NoColor { + consoleNoColor = w.NoColor + } + + var buf = consoleBufPool.Get().(*bytes.Buffer) + defer consoleBufPool.Put(buf) + + var evt map[string]interface{} + p = decodeIfBinaryToBytes(p) + d := json.NewDecoder(bytes.NewReader(p)) + d.UseNumber() + err = d.Decode(&evt) + if err != nil { + return n, fmt.Errorf("cannot decode event: %s", err) + } + + for _, p := range w.PartsOrder { + w.writePart(buf, evt, p) + } + + w.writeFields(evt, buf) + + buf.WriteByte('\n') + buf.WriteTo(w.Out) + return len(p), nil +} + +// writeFields appends formatted key-value pairs to buf. +func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer) { + var fields = make([]string, 0, len(evt)) + for field := range evt { + switch field { + case LevelFieldName, TimestampFieldName, MessageFieldName, CallerFieldName: + continue + } + fields = append(fields, field) + } + sort.Strings(fields) + + if len(fields) > 0 { + buf.WriteByte(' ') + } + + // Move the "error" field to the front + ei := sort.Search(len(fields), func(i int) bool { return fields[i] >= ErrorFieldName }) + if ei < len(fields) && fields[ei] == ErrorFieldName { + fields[ei] = "" + fields = append([]string{ErrorFieldName}, fields...) + var xfields = make([]string, 0, len(fields)) + for _, field := range fields { + if field == "" { // Skip empty fields + continue + } + xfields = append(xfields, field) + } + fields = xfields + } + + for i, field := range fields { + var fn Formatter + var fv Formatter + + if field == ErrorFieldName { + if w.FormatErrFieldName == nil { + fn = consoleDefaultFormatErrFieldName + } else { + fn = w.FormatErrFieldName + } + + if w.FormatErrFieldValue == nil { + fv = consoleDefaultFormatErrFieldValue + } else { + fv = w.FormatErrFieldValue + } + } else { + if w.FormatFieldName == nil { + fn = consoleDefaultFormatFieldName + } else { + fn = w.FormatFieldName + } + + if w.FormatFieldValue == nil { + fv = consoleDefaultFormatFieldValue + } else { + fv = w.FormatFieldValue + } + } + + buf.WriteString(fn(field)) + + switch fValue := evt[field].(type) { + case string: + if needsQuote(fValue) { + buf.WriteString(fv(strconv.Quote(fValue))) + } else { + buf.WriteString(fv(fValue)) + } + case json.Number: + buf.WriteString(fv(fValue)) + default: + b, err := json.Marshal(fValue) + if err != nil { + fmt.Fprintf(buf, colorize("[error: %v]", colorRed, w.NoColor), err) + } else { + fmt.Fprint(buf, fv(b)) + } + } + + if i < len(fields)-1 { // Skip space for last field + buf.WriteByte(' ') + } + } +} + +// writePart appends a formatted part to buf. +func (w ConsoleWriter) writePart(buf *bytes.Buffer, evt map[string]interface{}, p string) { + var f Formatter + + switch p { + case LevelFieldName: + if w.FormatLevel == nil { + f = consoleDefaultFormatLevel + } else { + f = w.FormatLevel + } + case TimestampFieldName: + if w.FormatTimestamp == nil { + f = consoleDefaultFormatTimestamp + } else { + f = w.FormatTimestamp + } + case MessageFieldName: + if w.FormatMessage == nil { + f = consoleDefaultFormatMessage + } else { + f = w.FormatMessage + } + case CallerFieldName: + if w.FormatCaller == nil { + f = consoleDefaultFormatCaller + } else { + f = w.FormatCaller + } + default: + if w.FormatFieldValue == nil { + f = consoleDefaultFormatFieldValue + } else { + f = w.FormatFieldValue + } + } + + var s = f(evt[p]) + + if len(s) > 0 { + buf.WriteString(s) + if p != w.PartsOrder[len(w.PartsOrder)-1] { // Skip space for last part + buf.WriteByte(' ') + } + } +} + +// needsQuote returns true when the string s should be quoted in output. +func needsQuote(s string) bool { + for i := range s { + if s[i] < 0x20 || s[i] > 0x7e || s[i] == ' ' || s[i] == '\\' || s[i] == '"' { + return true + } + } + return false +} + +// colorize returns the string s wrapped in ANSI code c, unless disabled is true. +func colorize(s interface{}, c int, disabled bool) string { + if disabled { + return fmt.Sprintf("%s", s) + } + return fmt.Sprintf("\x1b[%dm%v\x1b[0m", c, s) +} + +// ----- DEFAULT FORMATTERS --------------------------------------------------- + +var ( + consoleDefaultFormatTimestamp = func(i interface{}) string { + t := "" + switch tt := i.(type) { + case string: + ts, err := time.Parse(time.RFC3339, tt) + if err != nil { + t = tt + } else { + t = ts.Format(consoleTimeFormat) + } + case json.Number: + t = tt.String() + } + return colorize(t, colorFaint, consoleNoColor) + } + + consoleDefaultFormatLevel = func(i interface{}) string { + var l string + if ll, ok := i.(string); ok { + switch ll { + case "debug": + l = colorize("DBG", colorYellow, consoleNoColor) + case "info": + l = colorize("INF", colorGreen, consoleNoColor) + case "warn": + l = colorize("WRN", colorRed, consoleNoColor) + case "error": + l = colorize(colorize("ERR", colorRed, consoleNoColor), colorBold, consoleNoColor) + case "fatal": + l = colorize(colorize("FTL", colorRed, consoleNoColor), colorBold, consoleNoColor) + case "panic": + l = colorize(colorize("PNC", colorRed, consoleNoColor), colorBold, consoleNoColor) + default: + l = colorize("???", colorBold, consoleNoColor) + } + } else { + l = strings.ToUpper(fmt.Sprintf("%s", i))[0:3] + } + return l + } + + consoleDefaultFormatCaller = func(i interface{}) string { + var c string + if cc, ok := i.(string); ok { + c = cc + } + if len(c) > 0 { + cwd, err := os.Getwd() + if err == nil { + c = strings.TrimPrefix(c, cwd) + c = strings.TrimPrefix(c, "/") + } + c = colorize(c, colorBold, consoleNoColor) + colorize(" >", colorFaint, consoleNoColor) + } + return c + } + + consoleDefaultFormatMessage = func(i interface{}) string { + return fmt.Sprintf("%s", i) + } + + consoleDefaultFormatFieldName = func(i interface{}) string { + return colorize(fmt.Sprintf("%s=", i), colorFaint, consoleNoColor) + } + + consoleDefaultFormatFieldValue = func(i interface{}) string { + return fmt.Sprintf("%s", i) + } + + consoleDefaultFormatErrFieldName = func(i interface{}) string { + return colorize(fmt.Sprintf("%s=", i), colorRed, consoleNoColor) + } + + consoleDefaultFormatErrFieldValue = func(i interface{}) string { + return colorize(fmt.Sprintf("%s", i), colorRed, consoleNoColor) + } +) diff --git a/vendor/github.com/rs/zerolog/context.go b/vendor/github.com/rs/zerolog/context.go new file mode 100644 index 0000000..b843179 --- /dev/null +++ b/vendor/github.com/rs/zerolog/context.go @@ -0,0 +1,381 @@ +package zerolog + +import ( + "io/ioutil" + "net" + "time" +) + +// Context configures a new sub-logger with contextual fields. +type Context struct { + l Logger +} + +// Logger returns the logger with the context previously set. +func (c Context) Logger() Logger { + return c.l +} + +// Fields is a helper function to use a map to set fields using type assertion. +func (c Context) Fields(fields map[string]interface{}) Context { + c.l.context = appendFields(c.l.context, fields) + return c +} + +// Dict adds the field key with the dict to the logger context. +func (c Context) Dict(key string, dict *Event) Context { + dict.buf = enc.AppendEndMarker(dict.buf) + c.l.context = append(enc.AppendKey(c.l.context, key), dict.buf...) + putEvent(dict) + return c +} + +// Array adds the field key with an array to the event context. +// Use zerolog.Arr() to create the array or pass a type that +// implement the LogArrayMarshaler interface. +func (c Context) Array(key string, arr LogArrayMarshaler) Context { + c.l.context = enc.AppendKey(c.l.context, key) + if arr, ok := arr.(*Array); ok { + c.l.context = arr.write(c.l.context) + return c + } + var a *Array + if aa, ok := arr.(*Array); ok { + a = aa + } else { + a = Arr() + arr.MarshalZerologArray(a) + } + c.l.context = a.write(c.l.context) + return c +} + +// Object marshals an object that implement the LogObjectMarshaler interface. +func (c Context) Object(key string, obj LogObjectMarshaler) Context { + e := newEvent(levelWriterAdapter{ioutil.Discard}, 0) + e.Object(key, obj) + c.l.context = enc.AppendObjectData(c.l.context, e.buf) + putEvent(e) + return c +} + +// EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface. +func (c Context) EmbedObject(obj LogObjectMarshaler) Context { + e := newEvent(levelWriterAdapter{ioutil.Discard}, 0) + e.EmbedObject(obj) + c.l.context = enc.AppendObjectData(c.l.context, e.buf) + putEvent(e) + return c +} + +// Str adds the field key with val as a string to the logger context. +func (c Context) Str(key, val string) Context { + c.l.context = enc.AppendString(enc.AppendKey(c.l.context, key), val) + return c +} + +// Strs adds the field key with val as a string to the logger context. +func (c Context) Strs(key string, vals []string) Context { + c.l.context = enc.AppendStrings(enc.AppendKey(c.l.context, key), vals) + return c +} + +// Bytes adds the field key with val as a []byte to the logger context. +func (c Context) Bytes(key string, val []byte) Context { + c.l.context = enc.AppendBytes(enc.AppendKey(c.l.context, key), val) + return c +} + +// Hex adds the field key with val as a hex string to the logger context. +func (c Context) Hex(key string, val []byte) Context { + c.l.context = enc.AppendHex(enc.AppendKey(c.l.context, key), val) + return c +} + +// RawJSON adds already encoded JSON to context. +// +// No sanity check is performed on b; it must not contain carriage returns and +// be valid JSON. +func (c Context) RawJSON(key string, b []byte) Context { + c.l.context = appendJSON(enc.AppendKey(c.l.context, key), b) + return c +} + +// AnErr adds the field key with serialized err to the logger context. +func (c Context) AnErr(key string, err error) Context { + marshaled := ErrorMarshalFunc(err) + switch m := marshaled.(type) { + case nil: + return c + case LogObjectMarshaler: + return c.Object(key, m) + case error: + return c.Str(key, m.Error()) + case string: + return c.Str(key, m) + default: + return c.Interface(key, m) + } +} + +// Errs adds the field key with errs as an array of serialized errors to the +// logger context. +func (c Context) Errs(key string, errs []error) Context { + arr := Arr() + for _, err := range errs { + marshaled := ErrorMarshalFunc(err) + switch m := marshaled.(type) { + case LogObjectMarshaler: + arr = arr.Object(m) + case error: + arr = arr.Str(m.Error()) + case string: + arr = arr.Str(m) + default: + arr = arr.Interface(m) + } + } + + return c.Array(key, arr) +} + +// Err adds the field "error" with serialized err to the logger context. +func (c Context) Err(err error) Context { + return c.AnErr(ErrorFieldName, err) +} + +// Bool adds the field key with val as a bool to the logger context. +func (c Context) Bool(key string, b bool) Context { + c.l.context = enc.AppendBool(enc.AppendKey(c.l.context, key), b) + return c +} + +// Bools adds the field key with val as a []bool to the logger context. +func (c Context) Bools(key string, b []bool) Context { + c.l.context = enc.AppendBools(enc.AppendKey(c.l.context, key), b) + return c +} + +// Int adds the field key with i as a int to the logger context. +func (c Context) Int(key string, i int) Context { + c.l.context = enc.AppendInt(enc.AppendKey(c.l.context, key), i) + return c +} + +// Ints adds the field key with i as a []int to the logger context. +func (c Context) Ints(key string, i []int) Context { + c.l.context = enc.AppendInts(enc.AppendKey(c.l.context, key), i) + return c +} + +// Int8 adds the field key with i as a int8 to the logger context. +func (c Context) Int8(key string, i int8) Context { + c.l.context = enc.AppendInt8(enc.AppendKey(c.l.context, key), i) + return c +} + +// Ints8 adds the field key with i as a []int8 to the logger context. +func (c Context) Ints8(key string, i []int8) Context { + c.l.context = enc.AppendInts8(enc.AppendKey(c.l.context, key), i) + return c +} + +// Int16 adds the field key with i as a int16 to the logger context. +func (c Context) Int16(key string, i int16) Context { + c.l.context = enc.AppendInt16(enc.AppendKey(c.l.context, key), i) + return c +} + +// Ints16 adds the field key with i as a []int16 to the logger context. +func (c Context) Ints16(key string, i []int16) Context { + c.l.context = enc.AppendInts16(enc.AppendKey(c.l.context, key), i) + return c +} + +// Int32 adds the field key with i as a int32 to the logger context. +func (c Context) Int32(key string, i int32) Context { + c.l.context = enc.AppendInt32(enc.AppendKey(c.l.context, key), i) + return c +} + +// Ints32 adds the field key with i as a []int32 to the logger context. +func (c Context) Ints32(key string, i []int32) Context { + c.l.context = enc.AppendInts32(enc.AppendKey(c.l.context, key), i) + return c +} + +// Int64 adds the field key with i as a int64 to the logger context. +func (c Context) Int64(key string, i int64) Context { + c.l.context = enc.AppendInt64(enc.AppendKey(c.l.context, key), i) + return c +} + +// Ints64 adds the field key with i as a []int64 to the logger context. +func (c Context) Ints64(key string, i []int64) Context { + c.l.context = enc.AppendInts64(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uint adds the field key with i as a uint to the logger context. +func (c Context) Uint(key string, i uint) Context { + c.l.context = enc.AppendUint(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uints adds the field key with i as a []uint to the logger context. +func (c Context) Uints(key string, i []uint) Context { + c.l.context = enc.AppendUints(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uint8 adds the field key with i as a uint8 to the logger context. +func (c Context) Uint8(key string, i uint8) Context { + c.l.context = enc.AppendUint8(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uints8 adds the field key with i as a []uint8 to the logger context. +func (c Context) Uints8(key string, i []uint8) Context { + c.l.context = enc.AppendUints8(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uint16 adds the field key with i as a uint16 to the logger context. +func (c Context) Uint16(key string, i uint16) Context { + c.l.context = enc.AppendUint16(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uints16 adds the field key with i as a []uint16 to the logger context. +func (c Context) Uints16(key string, i []uint16) Context { + c.l.context = enc.AppendUints16(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uint32 adds the field key with i as a uint32 to the logger context. +func (c Context) Uint32(key string, i uint32) Context { + c.l.context = enc.AppendUint32(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uints32 adds the field key with i as a []uint32 to the logger context. +func (c Context) Uints32(key string, i []uint32) Context { + c.l.context = enc.AppendUints32(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uint64 adds the field key with i as a uint64 to the logger context. +func (c Context) Uint64(key string, i uint64) Context { + c.l.context = enc.AppendUint64(enc.AppendKey(c.l.context, key), i) + return c +} + +// Uints64 adds the field key with i as a []uint64 to the logger context. +func (c Context) Uints64(key string, i []uint64) Context { + c.l.context = enc.AppendUints64(enc.AppendKey(c.l.context, key), i) + return c +} + +// Float32 adds the field key with f as a float32 to the logger context. +func (c Context) Float32(key string, f float32) Context { + c.l.context = enc.AppendFloat32(enc.AppendKey(c.l.context, key), f) + return c +} + +// Floats32 adds the field key with f as a []float32 to the logger context. +func (c Context) Floats32(key string, f []float32) Context { + c.l.context = enc.AppendFloats32(enc.AppendKey(c.l.context, key), f) + return c +} + +// Float64 adds the field key with f as a float64 to the logger context. +func (c Context) Float64(key string, f float64) Context { + c.l.context = enc.AppendFloat64(enc.AppendKey(c.l.context, key), f) + return c +} + +// Floats64 adds the field key with f as a []float64 to the logger context. +func (c Context) Floats64(key string, f []float64) Context { + c.l.context = enc.AppendFloats64(enc.AppendKey(c.l.context, key), f) + return c +} + +type timestampHook struct{} + +func (ts timestampHook) Run(e *Event, level Level, msg string) { + e.Timestamp() +} + +var th = timestampHook{} + +// Timestamp adds the current local time as UNIX timestamp to the logger context with the "time" key. +// To customize the key name, change zerolog.TimestampFieldName. +// +// NOTE: It won't dedupe the "time" key if the *Context has one already. +func (c Context) Timestamp() Context { + c.l = c.l.Hook(th) + return c +} + +// Time adds the field key with t formated as string using zerolog.TimeFieldFormat. +func (c Context) Time(key string, t time.Time) Context { + c.l.context = enc.AppendTime(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) + return c +} + +// Times adds the field key with t formated as string using zerolog.TimeFieldFormat. +func (c Context) Times(key string, t []time.Time) Context { + c.l.context = enc.AppendTimes(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) + return c +} + +// Dur adds the fields key with d divided by unit and stored as a float. +func (c Context) Dur(key string, d time.Duration) Context { + c.l.context = enc.AppendDuration(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger) + return c +} + +// Durs adds the fields key with d divided by unit and stored as a float. +func (c Context) Durs(key string, d []time.Duration) Context { + c.l.context = enc.AppendDurations(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger) + return c +} + +// Interface adds the field key with obj marshaled using reflection. +func (c Context) Interface(key string, i interface{}) Context { + c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i) + return c +} + +type callerHook struct{} + +func (ch callerHook) Run(e *Event, level Level, msg string) { + // Three extra frames to skip (added by hook infra). + e.caller(CallerSkipFrameCount + 3) +} + +var ch = callerHook{} + +// Caller adds the file:line of the caller with the zerolog.CallerFieldName key. +func (c Context) Caller() Context { + c.l = c.l.Hook(ch) + return c +} + +// IPAddr adds IPv4 or IPv6 Address to the context +func (c Context) IPAddr(key string, ip net.IP) Context { + c.l.context = enc.AppendIPAddr(enc.AppendKey(c.l.context, key), ip) + return c +} + +// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the context +func (c Context) IPPrefix(key string, pfx net.IPNet) Context { + c.l.context = enc.AppendIPPrefix(enc.AppendKey(c.l.context, key), pfx) + return c +} + +// MACAddr adds MAC address to the context +func (c Context) MACAddr(key string, ha net.HardwareAddr) Context { + c.l.context = enc.AppendMACAddr(enc.AppendKey(c.l.context, key), ha) + return c +} diff --git a/vendor/github.com/rs/zerolog/ctx.go b/vendor/github.com/rs/zerolog/ctx.go new file mode 100644 index 0000000..2b7a682 --- /dev/null +++ b/vendor/github.com/rs/zerolog/ctx.go @@ -0,0 +1,47 @@ +package zerolog + +import ( + "context" +) + +var disabledLogger *Logger + +func init() { + l := Nop() + disabledLogger = &l +} + +type ctxKey struct{} + +// WithContext returns a copy of ctx with l associated. If an instance of Logger +// is already in the context, the context is not updated. +// +// For instance, to add a field to an existing logger in the context, use this +// notation: +// +// ctx := r.Context() +// l := zerolog.Ctx(ctx) +// l.UpdateContext(func(c Context) Context { +// return c.Str("bar", "baz") +// }) +func (l *Logger) WithContext(ctx context.Context) context.Context { + if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok { + if lp == l { + // Do not store same logger. + return ctx + } + } else if l.level == Disabled { + // Do not store disabled logger. + return ctx + } + return context.WithValue(ctx, ctxKey{}, l) +} + +// Ctx returns the Logger associated with the ctx. If no logger +// is associated, a disabled logger is returned. +func Ctx(ctx context.Context) *Logger { + if l, ok := ctx.Value(ctxKey{}).(*Logger); ok { + return l + } + return disabledLogger +} diff --git a/vendor/github.com/rs/zerolog/encoder.go b/vendor/github.com/rs/zerolog/encoder.go new file mode 100644 index 0000000..09b24e8 --- /dev/null +++ b/vendor/github.com/rs/zerolog/encoder.go @@ -0,0 +1,56 @@ +package zerolog + +import ( + "net" + "time" +) + +type encoder interface { + AppendArrayDelim(dst []byte) []byte + AppendArrayEnd(dst []byte) []byte + AppendArrayStart(dst []byte) []byte + AppendBeginMarker(dst []byte) []byte + AppendBool(dst []byte, val bool) []byte + AppendBools(dst []byte, vals []bool) []byte + AppendBytes(dst, s []byte) []byte + AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte + AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte + AppendEndMarker(dst []byte) []byte + AppendFloat32(dst []byte, val float32) []byte + AppendFloat64(dst []byte, val float64) []byte + AppendFloats32(dst []byte, vals []float32) []byte + AppendFloats64(dst []byte, vals []float64) []byte + AppendHex(dst, s []byte) []byte + AppendIPAddr(dst []byte, ip net.IP) []byte + AppendIPPrefix(dst []byte, pfx net.IPNet) []byte + AppendInt(dst []byte, val int) []byte + AppendInt16(dst []byte, val int16) []byte + AppendInt32(dst []byte, val int32) []byte + AppendInt64(dst []byte, val int64) []byte + AppendInt8(dst []byte, val int8) []byte + AppendInterface(dst []byte, i interface{}) []byte + AppendInts(dst []byte, vals []int) []byte + AppendInts16(dst []byte, vals []int16) []byte + AppendInts32(dst []byte, vals []int32) []byte + AppendInts64(dst []byte, vals []int64) []byte + AppendInts8(dst []byte, vals []int8) []byte + AppendKey(dst []byte, key string) []byte + AppendLineBreak(dst []byte) []byte + AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte + AppendNil(dst []byte) []byte + AppendObjectData(dst []byte, o []byte) []byte + AppendString(dst []byte, s string) []byte + AppendStrings(dst []byte, vals []string) []byte + AppendTime(dst []byte, t time.Time, format string) []byte + AppendTimes(dst []byte, vals []time.Time, format string) []byte + AppendUint(dst []byte, val uint) []byte + AppendUint16(dst []byte, val uint16) []byte + AppendUint32(dst []byte, val uint32) []byte + AppendUint64(dst []byte, val uint64) []byte + AppendUint8(dst []byte, val uint8) []byte + AppendUints(dst []byte, vals []uint) []byte + AppendUints16(dst []byte, vals []uint16) []byte + AppendUints32(dst []byte, vals []uint32) []byte + AppendUints64(dst []byte, vals []uint64) []byte + AppendUints8(dst []byte, vals []uint8) []byte +} diff --git a/vendor/github.com/rs/zerolog/encoder_cbor.go b/vendor/github.com/rs/zerolog/encoder_cbor.go new file mode 100644 index 0000000..f8d3fe9 --- /dev/null +++ b/vendor/github.com/rs/zerolog/encoder_cbor.go @@ -0,0 +1,35 @@ +// +build binary_log + +package zerolog + +// This file contains bindings to do binary encoding. + +import ( + "github.com/rs/zerolog/internal/cbor" +) + +var ( + _ encoder = (*cbor.Encoder)(nil) + + enc = cbor.Encoder{} +) + +func appendJSON(dst []byte, j []byte) []byte { + return cbor.AppendEmbeddedJSON(dst, j) +} + +// decodeIfBinaryToString - converts a binary formatted log msg to a +// JSON formatted String Log message. +func decodeIfBinaryToString(in []byte) string { + return cbor.DecodeIfBinaryToString(in) +} + +func decodeObjectToStr(in []byte) string { + return cbor.DecodeObjectToStr(in) +} + +// decodeIfBinaryToBytes - converts a binary formatted log msg to a +// JSON formatted Bytes Log message. +func decodeIfBinaryToBytes(in []byte) []byte { + return cbor.DecodeIfBinaryToBytes(in) +} diff --git a/vendor/github.com/rs/zerolog/encoder_json.go b/vendor/github.com/rs/zerolog/encoder_json.go new file mode 100644 index 0000000..fe580f5 --- /dev/null +++ b/vendor/github.com/rs/zerolog/encoder_json.go @@ -0,0 +1,32 @@ +// +build !binary_log + +package zerolog + +// encoder_json.go file contains bindings to generate +// JSON encoded byte stream. + +import ( + "github.com/rs/zerolog/internal/json" +) + +var ( + _ encoder = (*json.Encoder)(nil) + + enc = json.Encoder{} +) + +func appendJSON(dst []byte, j []byte) []byte { + return append(dst, j...) +} + +func decodeIfBinaryToString(in []byte) string { + return string(in) +} + +func decodeObjectToStr(in []byte) string { + return string(in) +} + +func decodeIfBinaryToBytes(in []byte) []byte { + return in +} diff --git a/vendor/github.com/rs/zerolog/event.go b/vendor/github.com/rs/zerolog/event.go new file mode 100644 index 0000000..a0e090a --- /dev/null +++ b/vendor/github.com/rs/zerolog/event.go @@ -0,0 +1,677 @@ +package zerolog + +import ( + "fmt" + "net" + "os" + "runtime" + "strconv" + "sync" + "time" +) + +var eventPool = &sync.Pool{ + New: func() interface{} { + return &Event{ + buf: make([]byte, 0, 500), + } + }, +} + +// ErrorMarshalFunc allows customization of global error marshaling +var ErrorMarshalFunc = func(err error) interface{} { + return err +} + +// Event represents a log event. It is instanced by one of the level method of +// Logger and finalized by the Msg or Msgf method. +type Event struct { + buf []byte + w LevelWriter + level Level + done func(msg string) + ch []Hook // hooks from context +} + +func putEvent(e *Event) { + // Proper usage of a sync.Pool requires each entry to have approximately + // the same memory cost. To obtain this property when the stored type + // contains a variably-sized buffer, we add a hard limit on the maximum buffer + // to place back in the pool. + // + // See https://golang.org/issue/23199 + const maxSize = 1 << 16 // 64KiB + if cap(e.buf) > maxSize { + return + } + eventPool.Put(e) +} + +// LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface +// to be implemented by types used with Event/Context's Object methods. +type LogObjectMarshaler interface { + MarshalZerologObject(e *Event) +} + +// LogArrayMarshaler provides a strongly-typed and encoding-agnostic interface +// to be implemented by types used with Event/Context's Array methods. +type LogArrayMarshaler interface { + MarshalZerologArray(a *Array) +} + +func newEvent(w LevelWriter, level Level) *Event { + e := eventPool.Get().(*Event) + e.buf = e.buf[:0] + e.ch = nil + e.buf = enc.AppendBeginMarker(e.buf) + e.w = w + e.level = level + return e +} + +func (e *Event) write() (err error) { + if e == nil { + return nil + } + if e.level != Disabled { + e.buf = enc.AppendEndMarker(e.buf) + e.buf = enc.AppendLineBreak(e.buf) + if e.w != nil { + _, err = e.w.WriteLevel(e.level, e.buf) + } + } + putEvent(e) + return +} + +// Enabled return false if the *Event is going to be filtered out by +// log level or sampling. +func (e *Event) Enabled() bool { + return e != nil && e.level != Disabled +} + +// Discard disables the event so Msg(f) won't print it. +func (e *Event) Discard() *Event { + if e == nil { + return e + } + e.level = Disabled + return nil +} + +// Msg sends the *Event with msg added as the message field if not empty. +// +// NOTICE: once this method is called, the *Event should be disposed. +// Calling Msg twice can have unexpected result. +func (e *Event) Msg(msg string) { + if e == nil { + return + } + e.msg(msg) +} + +// Msgf sends the event with formated msg added as the message field if not empty. +// +// NOTICE: once this methid is called, the *Event should be disposed. +// Calling Msg twice can have unexpected result. +func (e *Event) Msgf(format string, v ...interface{}) { + if e == nil { + return + } + e.msg(fmt.Sprintf(format, v...)) +} + +func (e *Event) msg(msg string) { + if len(e.ch) > 0 { + e.ch[0].Run(e, e.level, msg) + if len(e.ch) > 1 { + for _, hook := range e.ch[1:] { + hook.Run(e, e.level, msg) + } + } + } + if msg != "" { + e.buf = enc.AppendString(enc.AppendKey(e.buf, MessageFieldName), msg) + } + if e.done != nil { + defer e.done(msg) + } + if err := e.write(); err != nil { + if ErrorHandler != nil { + ErrorHandler(err) + } else { + fmt.Fprintf(os.Stderr, "zerolog: could not write event: %v\n", err) + } + } +} + +// Fields is a helper function to use a map to set fields using type assertion. +func (e *Event) Fields(fields map[string]interface{}) *Event { + if e == nil { + return e + } + e.buf = appendFields(e.buf, fields) + return e +} + +// Dict adds the field key with a dict to the event context. +// Use zerolog.Dict() to create the dictionary. +func (e *Event) Dict(key string, dict *Event) *Event { + if e == nil { + return e + } + dict.buf = enc.AppendEndMarker(dict.buf) + e.buf = append(enc.AppendKey(e.buf, key), dict.buf...) + putEvent(dict) + return e +} + +// Dict creates an Event to be used with the *Event.Dict method. +// Call usual field methods like Str, Int etc to add fields to this +// event and give it as argument the *Event.Dict method. +func Dict() *Event { + return newEvent(nil, 0) +} + +// Array adds the field key with an array to the event context. +// Use zerolog.Arr() to create the array or pass a type that +// implement the LogArrayMarshaler interface. +func (e *Event) Array(key string, arr LogArrayMarshaler) *Event { + if e == nil { + return e + } + e.buf = enc.AppendKey(e.buf, key) + var a *Array + if aa, ok := arr.(*Array); ok { + a = aa + } else { + a = Arr() + arr.MarshalZerologArray(a) + } + e.buf = a.write(e.buf) + return e +} + +func (e *Event) appendObject(obj LogObjectMarshaler) { + e.buf = enc.AppendBeginMarker(e.buf) + obj.MarshalZerologObject(e) + e.buf = enc.AppendEndMarker(e.buf) +} + +// Object marshals an object that implement the LogObjectMarshaler interface. +func (e *Event) Object(key string, obj LogObjectMarshaler) *Event { + if e == nil { + return e + } + e.buf = enc.AppendKey(e.buf, key) + e.appendObject(obj) + return e +} + +// Object marshals an object that implement the LogObjectMarshaler interface. +func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event { + if e == nil { + return e + } + obj.MarshalZerologObject(e) + return e +} + +// Str adds the field key with val as a string to the *Event context. +func (e *Event) Str(key, val string) *Event { + if e == nil { + return e + } + e.buf = enc.AppendString(enc.AppendKey(e.buf, key), val) + return e +} + +// Strs adds the field key with vals as a []string to the *Event context. +func (e *Event) Strs(key string, vals []string) *Event { + if e == nil { + return e + } + e.buf = enc.AppendStrings(enc.AppendKey(e.buf, key), vals) + return e +} + +// Bytes adds the field key with val as a string to the *Event context. +// +// Runes outside of normal ASCII ranges will be hex-encoded in the resulting +// JSON. +func (e *Event) Bytes(key string, val []byte) *Event { + if e == nil { + return e + } + e.buf = enc.AppendBytes(enc.AppendKey(e.buf, key), val) + return e +} + +// Hex adds the field key with val as a hex string to the *Event context. +func (e *Event) Hex(key string, val []byte) *Event { + if e == nil { + return e + } + e.buf = enc.AppendHex(enc.AppendKey(e.buf, key), val) + return e +} + +// RawJSON adds already encoded JSON to the log line under key. +// +// No sanity check is performed on b; it must not contain carriage returns and +// be valid JSON. +func (e *Event) RawJSON(key string, b []byte) *Event { + if e == nil { + return e + } + e.buf = appendJSON(enc.AppendKey(e.buf, key), b) + return e +} + +// AnErr adds the field key with serialized err to the *Event context. +// If err is nil, no field is added. +func (e *Event) AnErr(key string, err error) *Event { + marshaled := ErrorMarshalFunc(err) + switch m := marshaled.(type) { + case nil: + return e + case LogObjectMarshaler: + return e.Object(key, m) + case error: + return e.Str(key, m.Error()) + case string: + return e.Str(key, m) + default: + return e.Interface(key, m) + } +} + +// Errs adds the field key with errs as an array of serialized errors to the +// *Event context. +func (e *Event) Errs(key string, errs []error) *Event { + if e == nil { + return e + } + + arr := Arr() + for _, err := range errs { + marshaled := ErrorMarshalFunc(err) + switch m := marshaled.(type) { + case LogObjectMarshaler: + arr = arr.Object(m) + case error: + arr = arr.Err(m) + case string: + arr = arr.Str(m) + default: + arr = arr.Interface(m) + } + } + + return e.Array(key, arr) +} + +// Err adds the field "error" with serialized err to the *Event context. +// If err is nil, no field is added. +// To customize the key name, change zerolog.ErrorFieldName. +func (e *Event) Err(err error) *Event { + return e.AnErr(ErrorFieldName, err) +} + +// Bool adds the field key with val as a bool to the *Event context. +func (e *Event) Bool(key string, b bool) *Event { + if e == nil { + return e + } + e.buf = enc.AppendBool(enc.AppendKey(e.buf, key), b) + return e +} + +// Bools adds the field key with val as a []bool to the *Event context. +func (e *Event) Bools(key string, b []bool) *Event { + if e == nil { + return e + } + e.buf = enc.AppendBools(enc.AppendKey(e.buf, key), b) + return e +} + +// Int adds the field key with i as a int to the *Event context. +func (e *Event) Int(key string, i int) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInt(enc.AppendKey(e.buf, key), i) + return e +} + +// Ints adds the field key with i as a []int to the *Event context. +func (e *Event) Ints(key string, i []int) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInts(enc.AppendKey(e.buf, key), i) + return e +} + +// Int8 adds the field key with i as a int8 to the *Event context. +func (e *Event) Int8(key string, i int8) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInt8(enc.AppendKey(e.buf, key), i) + return e +} + +// Ints8 adds the field key with i as a []int8 to the *Event context. +func (e *Event) Ints8(key string, i []int8) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInts8(enc.AppendKey(e.buf, key), i) + return e +} + +// Int16 adds the field key with i as a int16 to the *Event context. +func (e *Event) Int16(key string, i int16) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInt16(enc.AppendKey(e.buf, key), i) + return e +} + +// Ints16 adds the field key with i as a []int16 to the *Event context. +func (e *Event) Ints16(key string, i []int16) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInts16(enc.AppendKey(e.buf, key), i) + return e +} + +// Int32 adds the field key with i as a int32 to the *Event context. +func (e *Event) Int32(key string, i int32) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInt32(enc.AppendKey(e.buf, key), i) + return e +} + +// Ints32 adds the field key with i as a []int32 to the *Event context. +func (e *Event) Ints32(key string, i []int32) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInts32(enc.AppendKey(e.buf, key), i) + return e +} + +// Int64 adds the field key with i as a int64 to the *Event context. +func (e *Event) Int64(key string, i int64) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInt64(enc.AppendKey(e.buf, key), i) + return e +} + +// Ints64 adds the field key with i as a []int64 to the *Event context. +func (e *Event) Ints64(key string, i []int64) *Event { + if e == nil { + return e + } + e.buf = enc.AppendInts64(enc.AppendKey(e.buf, key), i) + return e +} + +// Uint adds the field key with i as a uint to the *Event context. +func (e *Event) Uint(key string, i uint) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUint(enc.AppendKey(e.buf, key), i) + return e +} + +// Uints adds the field key with i as a []int to the *Event context. +func (e *Event) Uints(key string, i []uint) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUints(enc.AppendKey(e.buf, key), i) + return e +} + +// Uint8 adds the field key with i as a uint8 to the *Event context. +func (e *Event) Uint8(key string, i uint8) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUint8(enc.AppendKey(e.buf, key), i) + return e +} + +// Uints8 adds the field key with i as a []int8 to the *Event context. +func (e *Event) Uints8(key string, i []uint8) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUints8(enc.AppendKey(e.buf, key), i) + return e +} + +// Uint16 adds the field key with i as a uint16 to the *Event context. +func (e *Event) Uint16(key string, i uint16) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUint16(enc.AppendKey(e.buf, key), i) + return e +} + +// Uints16 adds the field key with i as a []int16 to the *Event context. +func (e *Event) Uints16(key string, i []uint16) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUints16(enc.AppendKey(e.buf, key), i) + return e +} + +// Uint32 adds the field key with i as a uint32 to the *Event context. +func (e *Event) Uint32(key string, i uint32) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUint32(enc.AppendKey(e.buf, key), i) + return e +} + +// Uints32 adds the field key with i as a []int32 to the *Event context. +func (e *Event) Uints32(key string, i []uint32) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUints32(enc.AppendKey(e.buf, key), i) + return e +} + +// Uint64 adds the field key with i as a uint64 to the *Event context. +func (e *Event) Uint64(key string, i uint64) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUint64(enc.AppendKey(e.buf, key), i) + return e +} + +// Uints64 adds the field key with i as a []int64 to the *Event context. +func (e *Event) Uints64(key string, i []uint64) *Event { + if e == nil { + return e + } + e.buf = enc.AppendUints64(enc.AppendKey(e.buf, key), i) + return e +} + +// Float32 adds the field key with f as a float32 to the *Event context. +func (e *Event) Float32(key string, f float32) *Event { + if e == nil { + return e + } + e.buf = enc.AppendFloat32(enc.AppendKey(e.buf, key), f) + return e +} + +// Floats32 adds the field key with f as a []float32 to the *Event context. +func (e *Event) Floats32(key string, f []float32) *Event { + if e == nil { + return e + } + e.buf = enc.AppendFloats32(enc.AppendKey(e.buf, key), f) + return e +} + +// Float64 adds the field key with f as a float64 to the *Event context. +func (e *Event) Float64(key string, f float64) *Event { + if e == nil { + return e + } + e.buf = enc.AppendFloat64(enc.AppendKey(e.buf, key), f) + return e +} + +// Floats64 adds the field key with f as a []float64 to the *Event context. +func (e *Event) Floats64(key string, f []float64) *Event { + if e == nil { + return e + } + e.buf = enc.AppendFloats64(enc.AppendKey(e.buf, key), f) + return e +} + +// Timestamp adds the current local time as UNIX timestamp to the *Event context with the "time" key. +// To customize the key name, change zerolog.TimestampFieldName. +// +// NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one +// already. +func (e *Event) Timestamp() *Event { + if e == nil { + return e + } + e.buf = enc.AppendTime(enc.AppendKey(e.buf, TimestampFieldName), TimestampFunc(), TimeFieldFormat) + return e +} + +// Time adds the field key with t formated as string using zerolog.TimeFieldFormat. +func (e *Event) Time(key string, t time.Time) *Event { + if e == nil { + return e + } + e.buf = enc.AppendTime(enc.AppendKey(e.buf, key), t, TimeFieldFormat) + return e +} + +// Times adds the field key with t formated as string using zerolog.TimeFieldFormat. +func (e *Event) Times(key string, t []time.Time) *Event { + if e == nil { + return e + } + e.buf = enc.AppendTimes(enc.AppendKey(e.buf, key), t, TimeFieldFormat) + return e +} + +// Dur adds the field key with duration d stored as zerolog.DurationFieldUnit. +// If zerolog.DurationFieldInteger is true, durations are rendered as integer +// instead of float. +func (e *Event) Dur(key string, d time.Duration) *Event { + if e == nil { + return e + } + e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger) + return e +} + +// Durs adds the field key with duration d stored as zerolog.DurationFieldUnit. +// If zerolog.DurationFieldInteger is true, durations are rendered as integer +// instead of float. +func (e *Event) Durs(key string, d []time.Duration) *Event { + if e == nil { + return e + } + e.buf = enc.AppendDurations(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger) + return e +} + +// TimeDiff adds the field key with positive duration between time t and start. +// If time t is not greater than start, duration will be 0. +// Duration format follows the same principle as Dur(). +func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event { + if e == nil { + return e + } + var d time.Duration + if t.After(start) { + d = t.Sub(start) + } + e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger) + return e +} + +// Interface adds the field key with i marshaled using reflection. +func (e *Event) Interface(key string, i interface{}) *Event { + if e == nil { + return e + } + if obj, ok := i.(LogObjectMarshaler); ok { + return e.Object(key, obj) + } + e.buf = enc.AppendInterface(enc.AppendKey(e.buf, key), i) + return e +} + +// Caller adds the file:line of the caller with the zerolog.CallerFieldName key. +func (e *Event) Caller() *Event { + return e.caller(CallerSkipFrameCount) +} + +func (e *Event) caller(skip int) *Event { + if e == nil { + return e + } + _, file, line, ok := runtime.Caller(skip) + if !ok { + return e + } + e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), file+":"+strconv.Itoa(line)) + return e +} + +// IPAddr adds IPv4 or IPv6 Address to the event +func (e *Event) IPAddr(key string, ip net.IP) *Event { + if e == nil { + return e + } + e.buf = enc.AppendIPAddr(enc.AppendKey(e.buf, key), ip) + return e +} + +// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the event +func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event { + if e == nil { + return e + } + e.buf = enc.AppendIPPrefix(enc.AppendKey(e.buf, key), pfx) + return e +} + +// MACAddr adds MAC address to the event +func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event { + if e == nil { + return e + } + e.buf = enc.AppendMACAddr(enc.AppendKey(e.buf, key), ha) + return e +} diff --git a/vendor/github.com/rs/zerolog/fields.go b/vendor/github.com/rs/zerolog/fields.go new file mode 100644 index 0000000..6b62ecc --- /dev/null +++ b/vendor/github.com/rs/zerolog/fields.go @@ -0,0 +1,242 @@ +package zerolog + +import ( + "net" + "sort" + "time" +) + +func appendFields(dst []byte, fields map[string]interface{}) []byte { + keys := make([]string, 0, len(fields)) + for key := range fields { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + dst = enc.AppendKey(dst, key) + val := fields[key] + if val, ok := val.(LogObjectMarshaler); ok { + e := newEvent(nil, 0) + e.buf = e.buf[:0] + e.appendObject(val) + dst = append(dst, e.buf...) + putEvent(e) + continue + } + switch val := val.(type) { + case string: + dst = enc.AppendString(dst, val) + case []byte: + dst = enc.AppendBytes(dst, val) + case error: + marshaled := ErrorMarshalFunc(val) + switch m := marshaled.(type) { + case LogObjectMarshaler: + e := newEvent(nil, 0) + e.buf = e.buf[:0] + e.appendObject(m) + dst = append(dst, e.buf...) + putEvent(e) + case error: + dst = enc.AppendString(dst, m.Error()) + case string: + dst = enc.AppendString(dst, m) + default: + dst = enc.AppendInterface(dst, m) + } + case []error: + dst = enc.AppendArrayStart(dst) + for i, err := range val { + marshaled := ErrorMarshalFunc(err) + switch m := marshaled.(type) { + case LogObjectMarshaler: + e := newEvent(nil, 0) + e.buf = e.buf[:0] + e.appendObject(m) + dst = append(dst, e.buf...) + putEvent(e) + case error: + dst = enc.AppendString(dst, m.Error()) + case string: + dst = enc.AppendString(dst, m) + default: + dst = enc.AppendInterface(dst, m) + } + + if i < (len(val) - 1) { + enc.AppendArrayDelim(dst) + } + } + dst = enc.AppendArrayEnd(dst) + case bool: + dst = enc.AppendBool(dst, val) + case int: + dst = enc.AppendInt(dst, val) + case int8: + dst = enc.AppendInt8(dst, val) + case int16: + dst = enc.AppendInt16(dst, val) + case int32: + dst = enc.AppendInt32(dst, val) + case int64: + dst = enc.AppendInt64(dst, val) + case uint: + dst = enc.AppendUint(dst, val) + case uint8: + dst = enc.AppendUint8(dst, val) + case uint16: + dst = enc.AppendUint16(dst, val) + case uint32: + dst = enc.AppendUint32(dst, val) + case uint64: + dst = enc.AppendUint64(dst, val) + case float32: + dst = enc.AppendFloat32(dst, val) + case float64: + dst = enc.AppendFloat64(dst, val) + case time.Time: + dst = enc.AppendTime(dst, val, TimeFieldFormat) + case time.Duration: + dst = enc.AppendDuration(dst, val, DurationFieldUnit, DurationFieldInteger) + case *string: + if val != nil { + dst = enc.AppendString(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *bool: + if val != nil { + dst = enc.AppendBool(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *int: + if val != nil { + dst = enc.AppendInt(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *int8: + if val != nil { + dst = enc.AppendInt8(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *int16: + if val != nil { + dst = enc.AppendInt16(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *int32: + if val != nil { + dst = enc.AppendInt32(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *int64: + if val != nil { + dst = enc.AppendInt64(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *uint: + if val != nil { + dst = enc.AppendUint(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *uint8: + if val != nil { + dst = enc.AppendUint8(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *uint16: + if val != nil { + dst = enc.AppendUint16(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *uint32: + if val != nil { + dst = enc.AppendUint32(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *uint64: + if val != nil { + dst = enc.AppendUint64(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *float32: + if val != nil { + dst = enc.AppendFloat32(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *float64: + if val != nil { + dst = enc.AppendFloat64(dst, *val) + } else { + dst = enc.AppendNil(dst) + } + case *time.Time: + if val != nil { + dst = enc.AppendTime(dst, *val, TimeFieldFormat) + } else { + dst = enc.AppendNil(dst) + } + case *time.Duration: + if val != nil { + dst = enc.AppendDuration(dst, *val, DurationFieldUnit, DurationFieldInteger) + } else { + dst = enc.AppendNil(dst) + } + case []string: + dst = enc.AppendStrings(dst, val) + case []bool: + dst = enc.AppendBools(dst, val) + case []int: + dst = enc.AppendInts(dst, val) + case []int8: + dst = enc.AppendInts8(dst, val) + case []int16: + dst = enc.AppendInts16(dst, val) + case []int32: + dst = enc.AppendInts32(dst, val) + case []int64: + dst = enc.AppendInts64(dst, val) + case []uint: + dst = enc.AppendUints(dst, val) + // case []uint8: + // dst = enc.AppendUints8(dst, val) + case []uint16: + dst = enc.AppendUints16(dst, val) + case []uint32: + dst = enc.AppendUints32(dst, val) + case []uint64: + dst = enc.AppendUints64(dst, val) + case []float32: + dst = enc.AppendFloats32(dst, val) + case []float64: + dst = enc.AppendFloats64(dst, val) + case []time.Time: + dst = enc.AppendTimes(dst, val, TimeFieldFormat) + case []time.Duration: + dst = enc.AppendDurations(dst, val, DurationFieldUnit, DurationFieldInteger) + case nil: + dst = enc.AppendNil(dst) + case net.IP: + dst = enc.AppendIPAddr(dst, val) + case net.IPNet: + dst = enc.AppendIPPrefix(dst, val) + case net.HardwareAddr: + dst = enc.AppendMACAddr(dst, val) + default: + dst = enc.AppendInterface(dst, val) + } + } + return dst +} diff --git a/vendor/github.com/rs/zerolog/globals.go b/vendor/github.com/rs/zerolog/globals.go new file mode 100644 index 0000000..1c66904 --- /dev/null +++ b/vendor/github.com/rs/zerolog/globals.go @@ -0,0 +1,76 @@ +package zerolog + +import "time" +import "sync/atomic" + +var ( + // TimestampFieldName is the field name used for the timestamp field. + TimestampFieldName = "time" + + // LevelFieldName is the field name used for the level field. + LevelFieldName = "level" + + // MessageFieldName is the field name used for the message field. + MessageFieldName = "message" + + // ErrorFieldName is the field name used for error fields. + ErrorFieldName = "error" + + // CallerFieldName is the field name used for caller field. + CallerFieldName = "caller" + + // CallerSkipFrameCount is the number of stack frames to skip to find the caller. + CallerSkipFrameCount = 2 + + // TimeFieldFormat defines the time format of the Time field type. + // If set to an empty string, the time is formatted as an UNIX timestamp + // as integer. + TimeFieldFormat = time.RFC3339 + + // TimestampFunc defines the function called to generate a timestamp. + TimestampFunc = time.Now + + // DurationFieldUnit defines the unit for time.Duration type fields added + // using the Dur method. + DurationFieldUnit = time.Millisecond + + // DurationFieldInteger renders Dur fields as integer instead of float if + // set to true. + DurationFieldInteger = false + + // ErrorHandler is called whenever zerolog fails to write an event on its + // output. If not set, an error is printed on the stderr. This handler must + // be thread safe and non-blocking. + ErrorHandler func(err error) +) + +var ( + gLevel = new(uint32) + disableSampling = new(uint32) +) + +// SetGlobalLevel sets the global override for log level. If this +// values is raised, all Loggers will use at least this value. +// +// To globally disable logs, set GlobalLevel to Disabled. +func SetGlobalLevel(l Level) { + atomic.StoreUint32(gLevel, uint32(l)) +} + +// GlobalLevel returns the current global log level +func GlobalLevel() Level { + return Level(atomic.LoadUint32(gLevel)) +} + +// DisableSampling will disable sampling in all Loggers if true. +func DisableSampling(v bool) { + var i uint32 + if v { + i = 1 + } + atomic.StoreUint32(disableSampling, i) +} + +func samplingDisabled() bool { + return atomic.LoadUint32(disableSampling) == 1 +} diff --git a/vendor/github.com/rs/zerolog/go.mod b/vendor/github.com/rs/zerolog/go.mod new file mode 100644 index 0000000..ed79427 --- /dev/null +++ b/vendor/github.com/rs/zerolog/go.mod @@ -0,0 +1 @@ +module github.com/rs/zerolog diff --git a/vendor/github.com/rs/zerolog/hook.go b/vendor/github.com/rs/zerolog/hook.go new file mode 100644 index 0000000..08133ac --- /dev/null +++ b/vendor/github.com/rs/zerolog/hook.go @@ -0,0 +1,60 @@ +package zerolog + +// Hook defines an interface to a log hook. +type Hook interface { + // Run runs the hook with the event. + Run(e *Event, level Level, message string) +} + +// HookFunc is an adaptor to allow the use of an ordinary function +// as a Hook. +type HookFunc func(e *Event, level Level, message string) + +// Run implements the Hook interface. +func (h HookFunc) Run(e *Event, level Level, message string) { + h(e, level, message) +} + +// LevelHook applies a different hook for each level. +type LevelHook struct { + NoLevelHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook +} + +// Run implements the Hook interface. +func (h LevelHook) Run(e *Event, level Level, message string) { + switch level { + case DebugLevel: + if h.DebugHook != nil { + h.DebugHook.Run(e, level, message) + } + case InfoLevel: + if h.InfoHook != nil { + h.InfoHook.Run(e, level, message) + } + case WarnLevel: + if h.WarnHook != nil { + h.WarnHook.Run(e, level, message) + } + case ErrorLevel: + if h.ErrorHook != nil { + h.ErrorHook.Run(e, level, message) + } + case FatalLevel: + if h.FatalHook != nil { + h.FatalHook.Run(e, level, message) + } + case PanicLevel: + if h.PanicHook != nil { + h.PanicHook.Run(e, level, message) + } + case NoLevel: + if h.NoLevelHook != nil { + h.NoLevelHook.Run(e, level, message) + } + } +} + +// NewLevelHook returns a new LevelHook. +func NewLevelHook() LevelHook { + return LevelHook{} +} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/README.md b/vendor/github.com/rs/zerolog/internal/cbor/README.md new file mode 100644 index 0000000..92c2e8c --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/cbor/README.md @@ -0,0 +1,56 @@ +## Reference: + CBOR Encoding is described in [RFC7049](https://tools.ietf.org/html/rfc7049) + +## Comparison of JSON vs CBOR + +Two main areas of reduction are: + +1. CPU usage to write a log msg +2. Size (in bytes) of log messages. + + +CPU Usage savings are below: +``` +name JSON time/op CBOR time/op delta +Info-32 15.3ns ± 1% 11.7ns ± 3% -23.78% (p=0.000 n=9+10) +ContextFields-32 16.2ns ± 2% 12.3ns ± 3% -23.97% (p=0.000 n=9+9) +ContextAppend-32 6.70ns ± 0% 6.20ns ± 0% -7.44% (p=0.000 n=9+9) +LogFields-32 66.4ns ± 0% 24.6ns ± 2% -62.89% (p=0.000 n=10+9) +LogArrayObject-32 911ns ±11% 768ns ± 6% -15.64% (p=0.000 n=10+10) +LogFieldType/Floats-32 70.3ns ± 2% 29.5ns ± 1% -57.98% (p=0.000 n=10+10) +LogFieldType/Err-32 14.0ns ± 3% 12.1ns ± 8% -13.20% (p=0.000 n=8+10) +LogFieldType/Dur-32 17.2ns ± 2% 13.1ns ± 1% -24.27% (p=0.000 n=10+9) +LogFieldType/Object-32 54.3ns ±11% 52.3ns ± 7% ~ (p=0.239 n=10+10) +LogFieldType/Ints-32 20.3ns ± 2% 15.1ns ± 2% -25.50% (p=0.000 n=9+10) +LogFieldType/Interfaces-32 642ns ±11% 621ns ± 9% ~ (p=0.118 n=10+10) +LogFieldType/Interface(Objects)-32 635ns ±13% 632ns ± 9% ~ (p=0.592 n=10+10) +LogFieldType/Times-32 294ns ± 0% 27ns ± 1% -90.71% (p=0.000 n=10+9) +LogFieldType/Durs-32 121ns ± 0% 33ns ± 2% -72.44% (p=0.000 n=9+9) +LogFieldType/Interface(Object)-32 56.6ns ± 8% 52.3ns ± 8% -7.54% (p=0.007 n=10+10) +LogFieldType/Errs-32 17.8ns ± 3% 16.1ns ± 2% -9.71% (p=0.000 n=10+9) +LogFieldType/Time-32 40.5ns ± 1% 12.7ns ± 6% -68.66% (p=0.000 n=8+9) +LogFieldType/Bool-32 12.0ns ± 5% 10.2ns ± 2% -15.18% (p=0.000 n=10+8) +LogFieldType/Bools-32 17.2ns ± 2% 12.6ns ± 4% -26.63% (p=0.000 n=10+10) +LogFieldType/Int-32 12.3ns ± 2% 11.2ns ± 4% -9.27% (p=0.000 n=9+10) +LogFieldType/Float-32 16.7ns ± 1% 12.6ns ± 2% -24.42% (p=0.000 n=7+9) +LogFieldType/Str-32 12.7ns ± 7% 11.3ns ± 7% -10.88% (p=0.000 n=10+9) +LogFieldType/Strs-32 20.3ns ± 3% 18.2ns ± 3% -10.25% (p=0.000 n=9+10) +LogFieldType/Interface-32 183ns ±12% 175ns ± 9% ~ (p=0.078 n=10+10) +``` + +Log message size savings is greatly dependent on the number and type of fields in the log message. +Assuming this log message (with an Integer, timestamp and string, in addition to level). + +`{"level":"error","Fault":41650,"time":"2018-04-01T15:18:19-07:00","message":"Some Message"}` + +Two measurements were done for the log file sizes - one without any compression, second +using [compress/zlib](https://golang.org/pkg/compress/zlib/). + +Results for 10,000 log messages: + +| Log Format | Plain File Size (in KB) | Compressed File Size (in KB) | +| :--- | :---: | :---: | +| JSON | 920 | 28 | +| CBOR | 550 | 28 | + +The example used to calculate the above data is available in [Examples](examples). diff --git a/vendor/github.com/rs/zerolog/internal/cbor/base.go b/vendor/github.com/rs/zerolog/internal/cbor/base.go new file mode 100644 index 0000000..58cd082 --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/cbor/base.go @@ -0,0 +1,11 @@ +package cbor + +type Encoder struct{} + +// AppendKey adds a key (string) to the binary encoded log message +func (e Encoder) AppendKey(dst []byte, key string) []byte { + if len(dst) < 1 { + dst = e.AppendBeginMarker(dst) + } + return e.AppendString(dst, key) +} \ No newline at end of file diff --git a/vendor/github.com/rs/zerolog/internal/cbor/cbor.go b/vendor/github.com/rs/zerolog/internal/cbor/cbor.go new file mode 100644 index 0000000..969f591 --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/cbor/cbor.go @@ -0,0 +1,100 @@ +// Package cbor provides primitives for storing different data +// in the CBOR (binary) format. CBOR is defined in RFC7049. +package cbor + +import "time" + +const ( + majorOffset = 5 + additionalMax = 23 + + // Non Values. + additionalTypeBoolFalse byte = 20 + additionalTypeBoolTrue byte = 21 + additionalTypeNull byte = 22 + + // Integer (+ve and -ve) Sub-types. + additionalTypeIntUint8 byte = 24 + additionalTypeIntUint16 byte = 25 + additionalTypeIntUint32 byte = 26 + additionalTypeIntUint64 byte = 27 + + // Float Sub-types. + additionalTypeFloat16 byte = 25 + additionalTypeFloat32 byte = 26 + additionalTypeFloat64 byte = 27 + additionalTypeBreak byte = 31 + + // Tag Sub-types. + additionalTypeTimestamp byte = 01 + + // Extended Tags - from https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml + additionalTypeTagNetworkAddr uint16 = 260 + additionalTypeTagNetworkPrefix uint16 = 261 + additionalTypeEmbeddedJSON uint16 = 262 + additionalTypeTagHexString uint16 = 263 + + // Unspecified number of elements. + additionalTypeInfiniteCount byte = 31 +) +const ( + majorTypeUnsignedInt byte = iota << majorOffset // Major type 0 + majorTypeNegativeInt // Major type 1 + majorTypeByteString // Major type 2 + majorTypeUtf8String // Major type 3 + majorTypeArray // Major type 4 + majorTypeMap // Major type 5 + majorTypeTags // Major type 6 + majorTypeSimpleAndFloat // Major type 7 +) + +const ( + maskOutAdditionalType byte = (7 << majorOffset) + maskOutMajorType byte = 31 +) + +const ( + float32Nan = "\xfa\x7f\xc0\x00\x00" + float32PosInfinity = "\xfa\x7f\x80\x00\x00" + float32NegInfinity = "\xfa\xff\x80\x00\x00" + float64Nan = "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00" + float64PosInfinity = "\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00" + float64NegInfinity = "\xfb\xff\xf0\x00\x00\x00\x00\x00\x00" +) + +// IntegerTimeFieldFormat indicates the format of timestamp decoded +// from an integer (time in seconds). +var IntegerTimeFieldFormat = time.RFC3339 + +// NanoTimeFieldFormat indicates the format of timestamp decoded +// from a float value (time in seconds and nano seconds). +var NanoTimeFieldFormat = time.RFC3339Nano + +func appendCborTypePrefix(dst []byte, major byte, number uint64) []byte { + byteCount := 8 + var minor byte + switch { + case number < 256: + byteCount = 1 + minor = additionalTypeIntUint8 + + case number < 65536: + byteCount = 2 + minor = additionalTypeIntUint16 + + case number < 4294967296: + byteCount = 4 + minor = additionalTypeIntUint32 + + default: + byteCount = 8 + minor = additionalTypeIntUint64 + + } + dst = append(dst, byte(major|minor)) + byteCount-- + for ; byteCount >= 0; byteCount-- { + dst = append(dst, byte(number>>(uint(byteCount)*8))) + } + return dst +} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/decode_stream.go b/vendor/github.com/rs/zerolog/internal/cbor/decode_stream.go new file mode 100644 index 0000000..e3cf3b7 --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/cbor/decode_stream.go @@ -0,0 +1,614 @@ +package cbor + +// This file contains code to decode a stream of CBOR Data into JSON. + +import ( + "bufio" + "bytes" + "fmt" + "io" + "math" + "net" + "runtime" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +var decodeTimeZone *time.Location + +const hexTable = "0123456789abcdef" + +const isFloat32 = 4 +const isFloat64 = 8 + +func readNBytes(src *bufio.Reader, n int) []byte { + ret := make([]byte, n) + for i := 0; i < n; i++ { + ch, e := src.ReadByte() + if e != nil { + panic(fmt.Errorf("Tried to Read %d Bytes.. But hit end of file", n)) + } + ret[i] = ch + } + return ret +} + +func readByte(src *bufio.Reader) byte { + b, e := src.ReadByte() + if e != nil { + panic(fmt.Errorf("Tried to Read 1 Byte.. But hit end of file")) + } + return b +} + +func decodeIntAdditonalType(src *bufio.Reader, minor byte) int64 { + val := int64(0) + if minor <= 23 { + val = int64(minor) + } else { + bytesToRead := 0 + switch minor { + case additionalTypeIntUint8: + bytesToRead = 1 + case additionalTypeIntUint16: + bytesToRead = 2 + case additionalTypeIntUint32: + bytesToRead = 4 + case additionalTypeIntUint64: + bytesToRead = 8 + default: + panic(fmt.Errorf("Invalid Additional Type: %d in decodeInteger (expected <28)", minor)) + } + pb := readNBytes(src, bytesToRead) + for i := 0; i < bytesToRead; i++ { + val = val * 256 + val += int64(pb[i]) + } + } + return val +} + +func decodeInteger(src *bufio.Reader) int64 { + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeUnsignedInt && major != majorTypeNegativeInt { + panic(fmt.Errorf("Major type is: %d in decodeInteger!! (expected 0 or 1)", major)) + } + val := decodeIntAdditonalType(src, minor) + if major == 0 { + return val + } + return (-1 - val) +} + +func decodeFloat(src *bufio.Reader) (float64, int) { + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeSimpleAndFloat { + panic(fmt.Errorf("Incorrect Major type is: %d in decodeFloat", major)) + } + + switch minor { + case additionalTypeFloat16: + panic(fmt.Errorf("float16 is not suppported in decodeFloat")) + + case additionalTypeFloat32: + pb := readNBytes(src, 4) + switch string(pb) { + case float32Nan: + return math.NaN(), isFloat32 + case float32PosInfinity: + return math.Inf(0), isFloat32 + case float32NegInfinity: + return math.Inf(-1), isFloat32 + } + n := uint32(0) + for i := 0; i < 4; i++ { + n = n * 256 + n += uint32(pb[i]) + } + val := math.Float32frombits(n) + return float64(val), isFloat32 + case additionalTypeFloat64: + pb := readNBytes(src, 8) + switch string(pb) { + case float64Nan: + return math.NaN(), isFloat64 + case float64PosInfinity: + return math.Inf(0), isFloat64 + case float64NegInfinity: + return math.Inf(-1), isFloat64 + } + n := uint64(0) + for i := 0; i < 8; i++ { + n = n * 256 + n += uint64(pb[i]) + } + val := math.Float64frombits(n) + return val, isFloat64 + } + panic(fmt.Errorf("Invalid Additional Type: %d in decodeFloat", minor)) +} + +func decodeStringComplex(dst []byte, s string, pos uint) []byte { + i := int(pos) + start := 0 + + for i < len(s) { + b := s[i] + if b >= utf8.RuneSelf { + r, size := utf8.DecodeRuneInString(s[i:]) + if r == utf8.RuneError && size == 1 { + // In case of error, first append previous simple characters to + // the byte slice if any and append a replacement character code + // in place of the invalid sequence. + if start < i { + dst = append(dst, s[start:i]...) + } + dst = append(dst, `\ufffd`...) + i += size + start = i + continue + } + i += size + continue + } + if b >= 0x20 && b <= 0x7e && b != '\\' && b != '"' { + i++ + continue + } + // We encountered a character that needs to be encoded. + // Let's append the previous simple characters to the byte slice + // and switch our operation to read and encode the remainder + // characters byte-by-byte. + if start < i { + dst = append(dst, s[start:i]...) + } + switch b { + case '"', '\\': + dst = append(dst, '\\', b) + case '\b': + dst = append(dst, '\\', 'b') + case '\f': + dst = append(dst, '\\', 'f') + case '\n': + dst = append(dst, '\\', 'n') + case '\r': + dst = append(dst, '\\', 'r') + case '\t': + dst = append(dst, '\\', 't') + default: + dst = append(dst, '\\', 'u', '0', '0', hexTable[b>>4], hexTable[b&0xF]) + } + i++ + start = i + } + if start < len(s) { + dst = append(dst, s[start:]...) + } + return dst +} + +func decodeString(src *bufio.Reader, noQuotes bool) []byte { + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeByteString { + panic(fmt.Errorf("Major type is: %d in decodeString", major)) + } + result := []byte{} + if !noQuotes { + result = append(result, '"') + } + length := decodeIntAdditonalType(src, minor) + len := int(length) + pbs := readNBytes(src, len) + result = append(result, pbs...) + if noQuotes { + return result + } + return append(result, '"') +} + +func decodeUTF8String(src *bufio.Reader) []byte { + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeUtf8String { + panic(fmt.Errorf("Major type is: %d in decodeUTF8String", major)) + } + result := []byte{'"'} + length := decodeIntAdditonalType(src, minor) + len := int(length) + pbs := readNBytes(src, len) + + for i := 0; i < len; i++ { + // Check if the character needs encoding. Control characters, slashes, + // and the double quote need json encoding. Bytes above the ascii + // boundary needs utf8 encoding. + if pbs[i] < 0x20 || pbs[i] > 0x7e || pbs[i] == '\\' || pbs[i] == '"' { + // We encountered a character that needs to be encoded. Switch + // to complex version of the algorithm. + dst := []byte{'"'} + dst = decodeStringComplex(dst, string(pbs), uint(i)) + return append(dst, '"') + } + } + // The string has no need for encoding an therefore is directly + // appended to the byte slice. + result = append(result, pbs...) + return append(result, '"') +} + +func array2Json(src *bufio.Reader, dst io.Writer) { + dst.Write([]byte{'['}) + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeArray { + panic(fmt.Errorf("Major type is: %d in array2Json", major)) + } + len := 0 + unSpecifiedCount := false + if minor == additionalTypeInfiniteCount { + unSpecifiedCount = true + } else { + length := decodeIntAdditonalType(src, minor) + len = int(length) + } + for i := 0; unSpecifiedCount || i < len; i++ { + if unSpecifiedCount { + pb, e := src.Peek(1) + if e != nil { + panic(e) + } + if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { + readByte(src) + break + } + } + cbor2JsonOneObject(src, dst) + if unSpecifiedCount { + pb, e := src.Peek(1) + if e != nil { + panic(e) + } + if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { + readByte(src) + break + } + dst.Write([]byte{','}) + } else if i+1 < len { + dst.Write([]byte{','}) + } + } + dst.Write([]byte{']'}) +} + +func map2Json(src *bufio.Reader, dst io.Writer) { + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeMap { + panic(fmt.Errorf("Major type is: %d in map2Json", major)) + } + len := 0 + unSpecifiedCount := false + if minor == additionalTypeInfiniteCount { + unSpecifiedCount = true + } else { + length := decodeIntAdditonalType(src, minor) + len = int(length) + } + dst.Write([]byte{'{'}) + for i := 0; unSpecifiedCount || i < len; i++ { + if unSpecifiedCount { + pb, e := src.Peek(1) + if e != nil { + panic(e) + } + if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { + readByte(src) + break + } + } + cbor2JsonOneObject(src, dst) + if i%2 == 0 { + // Even position values are keys. + dst.Write([]byte{':'}) + } else { + if unSpecifiedCount { + pb, e := src.Peek(1) + if e != nil { + panic(e) + } + if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { + readByte(src) + break + } + dst.Write([]byte{','}) + } else if i+1 < len { + dst.Write([]byte{','}) + } + } + } + dst.Write([]byte{'}'}) +} + +func decodeTagData(src *bufio.Reader) []byte { + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeTags { + panic(fmt.Errorf("Major type is: %d in decodeTagData", major)) + } + switch minor { + case additionalTypeTimestamp: + return decodeTimeStamp(src) + + // Tag value is larger than 256 (so uint16). + case additionalTypeIntUint16: + val := decodeIntAdditonalType(src, minor) + + switch uint16(val) { + case additionalTypeEmbeddedJSON: + pb := readByte(src) + dataMajor := pb & maskOutAdditionalType + if dataMajor != majorTypeByteString { + panic(fmt.Errorf("Unsupported embedded Type: %d in decodeEmbeddedJSON", dataMajor)) + } + src.UnreadByte() + return decodeString(src, true) + + case additionalTypeTagNetworkAddr: + octets := decodeString(src, true) + ss := []byte{'"'} + switch len(octets) { + case 6: // MAC address. + ha := net.HardwareAddr(octets) + ss = append(append(ss, ha.String()...), '"') + case 4: // IPv4 address. + fallthrough + case 16: // IPv6 address. + ip := net.IP(octets) + ss = append(append(ss, ip.String()...), '"') + default: + panic(fmt.Errorf("Unexpected Network Address length: %d (expected 4,6,16)", len(octets))) + } + return ss + + case additionalTypeTagNetworkPrefix: + pb := readByte(src) + if pb != byte(majorTypeMap|0x1) { + panic(fmt.Errorf("IP Prefix is NOT of MAP of 1 elements as expected")) + } + octets := decodeString(src, true) + val := decodeInteger(src) + ip := net.IP(octets) + var mask net.IPMask + pfxLen := int(val) + if len(octets) == 4 { + mask = net.CIDRMask(pfxLen, 32) + } else { + mask = net.CIDRMask(pfxLen, 128) + } + ipPfx := net.IPNet{IP: ip, Mask: mask} + ss := []byte{'"'} + ss = append(append(ss, ipPfx.String()...), '"') + return ss + + case additionalTypeTagHexString: + octets := decodeString(src, true) + ss := []byte{'"'} + for _, v := range octets { + ss = append(ss, hexTable[v>>4], hexTable[v&0x0f]) + } + return append(ss, '"') + + default: + panic(fmt.Errorf("Unsupported Additional Tag Type: %d in decodeTagData", val)) + } + } + panic(fmt.Errorf("Unsupported Additional Type: %d in decodeTagData", minor)) +} + +func decodeTimeStamp(src *bufio.Reader) []byte { + pb := readByte(src) + src.UnreadByte() + tsMajor := pb & maskOutAdditionalType + if tsMajor == majorTypeUnsignedInt || tsMajor == majorTypeNegativeInt { + n := decodeInteger(src) + t := time.Unix(n, 0) + if decodeTimeZone != nil { + t = t.In(decodeTimeZone) + } else { + t = t.In(time.UTC) + } + tsb := []byte{} + tsb = append(tsb, '"') + tsb = t.AppendFormat(tsb, IntegerTimeFieldFormat) + tsb = append(tsb, '"') + return tsb + } else if tsMajor == majorTypeSimpleAndFloat { + n, _ := decodeFloat(src) + secs := int64(n) + n -= float64(secs) + n *= float64(1e9) + t := time.Unix(secs, int64(n)) + if decodeTimeZone != nil { + t = t.In(decodeTimeZone) + } else { + t = t.In(time.UTC) + } + tsb := []byte{} + tsb = append(tsb, '"') + tsb = t.AppendFormat(tsb, NanoTimeFieldFormat) + tsb = append(tsb, '"') + return tsb + } + panic(fmt.Errorf("TS format is neigther int nor float: %d", tsMajor)) +} + +func decodeSimpleFloat(src *bufio.Reader) []byte { + pb := readByte(src) + major := pb & maskOutAdditionalType + minor := pb & maskOutMajorType + if major != majorTypeSimpleAndFloat { + panic(fmt.Errorf("Major type is: %d in decodeSimpleFloat", major)) + } + switch minor { + case additionalTypeBoolTrue: + return []byte("true") + case additionalTypeBoolFalse: + return []byte("false") + case additionalTypeNull: + return []byte("null") + case additionalTypeFloat16: + fallthrough + case additionalTypeFloat32: + fallthrough + case additionalTypeFloat64: + src.UnreadByte() + v, bc := decodeFloat(src) + ba := []byte{} + switch { + case math.IsNaN(v): + return []byte("\"NaN\"") + case math.IsInf(v, 1): + return []byte("\"+Inf\"") + case math.IsInf(v, -1): + return []byte("\"-Inf\"") + } + if bc == isFloat32 { + ba = strconv.AppendFloat(ba, v, 'f', -1, 32) + } else if bc == isFloat64 { + ba = strconv.AppendFloat(ba, v, 'f', -1, 64) + } else { + panic(fmt.Errorf("Invalid Float precision from decodeFloat: %d", bc)) + } + return ba + default: + panic(fmt.Errorf("Invalid Additional Type: %d in decodeSimpleFloat", minor)) + } +} + +func cbor2JsonOneObject(src *bufio.Reader, dst io.Writer) { + pb, e := src.Peek(1) + if e != nil { + panic(e) + } + major := (pb[0] & maskOutAdditionalType) + + switch major { + case majorTypeUnsignedInt: + fallthrough + case majorTypeNegativeInt: + n := decodeInteger(src) + dst.Write([]byte(strconv.Itoa(int(n)))) + + case majorTypeByteString: + s := decodeString(src, false) + dst.Write(s) + + case majorTypeUtf8String: + s := decodeUTF8String(src) + dst.Write(s) + + case majorTypeArray: + array2Json(src, dst) + + case majorTypeMap: + map2Json(src, dst) + + case majorTypeTags: + s := decodeTagData(src) + dst.Write(s) + + case majorTypeSimpleAndFloat: + s := decodeSimpleFloat(src) + dst.Write(s) + } +} + +func moreBytesToRead(src *bufio.Reader) bool { + _, e := src.ReadByte() + if e == nil { + src.UnreadByte() + return true + } + return false +} + +// Cbor2JsonManyObjects decodes all the CBOR Objects read from src +// reader. It keeps on decoding until reader returns EOF (error when reading). +// Decoded string is written to the dst. At the end of every CBOR Object +// newline is written to the output stream. +// +// Returns error (if any) that was encountered during decode. +// The child functions will generate a panic when error is encountered and +// this function will recover non-runtime Errors and return the reason as error. +func Cbor2JsonManyObjects(src io.Reader, dst io.Writer) (err error) { + defer func() { + if r := recover(); r != nil { + if _, ok := r.(runtime.Error); ok { + panic(r) + } + err = r.(error) + } + }() + bufRdr := bufio.NewReader(src) + for moreBytesToRead(bufRdr) { + cbor2JsonOneObject(bufRdr, dst) + dst.Write([]byte("\n")) + } + return nil +} + +// Detect if the bytes to be printed is Binary or not. +func binaryFmt(p []byte) bool { + if len(p) > 0 && p[0] > 0x7F { + return true + } + return false +} + +func getReader(str string) *bufio.Reader { + return bufio.NewReader(strings.NewReader(str)) +} + +// DecodeIfBinaryToString converts a binary formatted log msg to a +// JSON formatted String Log message - suitable for printing to Console/Syslog. +func DecodeIfBinaryToString(in []byte) string { + if binaryFmt(in) { + var b bytes.Buffer + Cbor2JsonManyObjects(strings.NewReader(string(in)), &b) + return b.String() + } + return string(in) +} + +// DecodeObjectToStr checks if the input is a binary format, if so, +// it will decode a single Object and return the decoded string. +func DecodeObjectToStr(in []byte) string { + if binaryFmt(in) { + var b bytes.Buffer + cbor2JsonOneObject(getReader(string(in)), &b) + return b.String() + } + return string(in) +} + +// DecodeIfBinaryToBytes checks if the input is a binary format, if so, +// it will decode all Objects and return the decoded string as byte array. +func DecodeIfBinaryToBytes(in []byte) []byte { + if binaryFmt(in) { + var b bytes.Buffer + Cbor2JsonManyObjects(bytes.NewReader(in), &b) + return b.Bytes() + } + return in +} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/string.go b/vendor/github.com/rs/zerolog/internal/cbor/string.go new file mode 100644 index 0000000..ff42afa --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/cbor/string.go @@ -0,0 +1,68 @@ +package cbor + +// AppendStrings encodes and adds an array of strings to the dst byte array. +func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { + major := majorTypeArray + l := len(vals) + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendString(dst, v) + } + return dst +} + +// AppendString encodes and adds a string to the dst byte array. +func (Encoder) AppendString(dst []byte, s string) []byte { + major := majorTypeUtf8String + + l := len(s) + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, majorTypeUtf8String, uint64(l)) + } + return append(dst, s...) +} + +// AppendBytes encodes and adds an array of bytes to the dst byte array. +func (Encoder) AppendBytes(dst, s []byte) []byte { + major := majorTypeByteString + + l := len(s) + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + return append(dst, s...) +} + +// AppendEmbeddedJSON adds a tag and embeds input JSON as such. +func AppendEmbeddedJSON(dst, s []byte) []byte { + major := majorTypeTags + minor := additionalTypeEmbeddedJSON + + // Append the TAG to indicate this is Embedded JSON. + dst = append(dst, byte(major|additionalTypeIntUint16)) + dst = append(dst, byte(minor>>8)) + dst = append(dst, byte(minor&0xff)) + + // Append the JSON Object as Byte String. + major = majorTypeByteString + + l := len(s) + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + return append(dst, s...) +} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/time.go b/vendor/github.com/rs/zerolog/internal/cbor/time.go new file mode 100644 index 0000000..12f6a1d --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/cbor/time.go @@ -0,0 +1,93 @@ +package cbor + +import ( + "time" +) + +func appendIntegerTimestamp(dst []byte, t time.Time) []byte { + major := majorTypeTags + minor := additionalTypeTimestamp + dst = append(dst, byte(major|minor)) + secs := t.Unix() + var val uint64 + if secs < 0 { + major = majorTypeNegativeInt + val = uint64(-secs - 1) + } else { + major = majorTypeUnsignedInt + val = uint64(secs) + } + dst = appendCborTypePrefix(dst, major, uint64(val)) + return dst +} + +func (e Encoder) appendFloatTimestamp(dst []byte, t time.Time) []byte { + major := majorTypeTags + minor := additionalTypeTimestamp + dst = append(dst, byte(major|minor)) + secs := t.Unix() + nanos := t.Nanosecond() + var val float64 + val = float64(secs)*1.0 + float64(nanos)*1E-9 + return e.AppendFloat64(dst, val) +} + +// AppendTime encodes and adds a timestamp to the dst byte array. +func (e Encoder) AppendTime(dst []byte, t time.Time, unused string) []byte { + utc := t.UTC() + if utc.Nanosecond() == 0 { + return appendIntegerTimestamp(dst, utc) + } + return e.appendFloatTimestamp(dst, utc) +} + +// AppendTimes encodes and adds an array of timestamps to the dst byte array. +func (e Encoder) AppendTimes(dst []byte, vals []time.Time, unused string) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + + for _, t := range vals { + dst = e.AppendTime(dst, t, unused) + } + return dst +} + +// AppendDuration encodes and adds a duration to the dst byte array. +// useInt field indicates whether to store the duration as seconds (integer) or +// as seconds+nanoseconds (float). +func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte { + if useInt { + return e.AppendInt64(dst, int64(d/unit)) + } + return e.AppendFloat64(dst, float64(d)/float64(unit)) +} + +// AppendDurations encodes and adds an array of durations to the dst byte array. +// useInt field indicates whether to store the duration as seconds (integer) or +// as seconds+nanoseconds (float). +func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, d := range vals { + dst = e.AppendDuration(dst, d, unit, useInt) + } + return dst +} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/types.go b/vendor/github.com/rs/zerolog/internal/cbor/types.go new file mode 100644 index 0000000..eb4f697 --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/cbor/types.go @@ -0,0 +1,478 @@ +package cbor + +import ( + "encoding/json" + "fmt" + "math" + "net" +) + +// AppendNil inserts a 'Nil' object into the dst byte array. +func (Encoder) AppendNil(dst []byte) []byte { + return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeNull)) +} + +// AppendBeginMarker inserts a map start into the dst byte array. +func (Encoder) AppendBeginMarker(dst []byte) []byte { + return append(dst, byte(majorTypeMap|additionalTypeInfiniteCount)) +} + +// AppendEndMarker inserts a map end into the dst byte array. +func (Encoder) AppendEndMarker(dst []byte) []byte { + return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak)) +} + +// AppendObjectData takes an object in form of a byte array and appends to dst. +func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { + // BeginMarker is present in the dst, which + // should not be copied when appending to existing data. + return append(dst, o[1:]...) +} + +// AppendArrayStart adds markers to indicate the start of an array. +func (Encoder) AppendArrayStart(dst []byte) []byte { + return append(dst, byte(majorTypeArray|additionalTypeInfiniteCount)) +} + +// AppendArrayEnd adds markers to indicate the end of an array. +func (Encoder) AppendArrayEnd(dst []byte) []byte { + return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak)) +} + +// AppendArrayDelim adds markers to indicate end of a particular array element. +func (Encoder) AppendArrayDelim(dst []byte) []byte { + //No delimiters needed in cbor + return dst +} + +// AppendLineBreak is a noop that keep API compat with json encoder. +func (Encoder) AppendLineBreak(dst []byte) []byte { + // No line breaks needed in binary format. + return dst +} + +// AppendBool encodes and inserts a boolean value into the dst byte array. +func (Encoder) AppendBool(dst []byte, val bool) []byte { + b := additionalTypeBoolFalse + if val { + b = additionalTypeBoolTrue + } + return append(dst, byte(majorTypeSimpleAndFloat|b)) +} + +// AppendBools encodes and inserts an array of boolean values into the dst byte array. +func (e Encoder) AppendBools(dst []byte, vals []bool) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendBool(dst, v) + } + return dst +} + +// AppendInt encodes and inserts an integer value into the dst byte array. +func (Encoder) AppendInt(dst []byte, val int) []byte { + major := majorTypeUnsignedInt + contentVal := val + if val < 0 { + major = majorTypeNegativeInt + contentVal = -val - 1 + } + if contentVal <= additionalMax { + lb := byte(contentVal) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(contentVal)) + } + return dst +} + +// AppendInts encodes and inserts an array of integer values into the dst byte array. +func (e Encoder) AppendInts(dst []byte, vals []int) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendInt(dst, v) + } + return dst +} + +// AppendInt8 encodes and inserts an int8 value into the dst byte array. +func (e Encoder) AppendInt8(dst []byte, val int8) []byte { + return e.AppendInt(dst, int(val)) +} + +// AppendInts8 encodes and inserts an array of integer values into the dst byte array. +func (e Encoder) AppendInts8(dst []byte, vals []int8) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendInt(dst, int(v)) + } + return dst +} + +// AppendInt16 encodes and inserts a int16 value into the dst byte array. +func (e Encoder) AppendInt16(dst []byte, val int16) []byte { + return e.AppendInt(dst, int(val)) +} + +// AppendInts16 encodes and inserts an array of int16 values into the dst byte array. +func (e Encoder) AppendInts16(dst []byte, vals []int16) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendInt(dst, int(v)) + } + return dst +} + +// AppendInt32 encodes and inserts a int32 value into the dst byte array. +func (e Encoder) AppendInt32(dst []byte, val int32) []byte { + return e.AppendInt(dst, int(val)) +} + +// AppendInts32 encodes and inserts an array of int32 values into the dst byte array. +func (e Encoder) AppendInts32(dst []byte, vals []int32) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendInt(dst, int(v)) + } + return dst +} + +// AppendInt64 encodes and inserts a int64 value into the dst byte array. +func (Encoder) AppendInt64(dst []byte, val int64) []byte { + major := majorTypeUnsignedInt + contentVal := val + if val < 0 { + major = majorTypeNegativeInt + contentVal = -val - 1 + } + if contentVal <= additionalMax { + lb := byte(contentVal) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(contentVal)) + } + return dst +} + +// AppendInts64 encodes and inserts an array of int64 values into the dst byte array. +func (e Encoder) AppendInts64(dst []byte, vals []int64) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendInt64(dst, v) + } + return dst +} + +// AppendUint encodes and inserts an unsigned integer value into the dst byte array. +func (e Encoder) AppendUint(dst []byte, val uint) []byte { + return e.AppendInt64(dst, int64(val)) +} + +// AppendUints encodes and inserts an array of unsigned integer values into the dst byte array. +func (e Encoder) AppendUints(dst []byte, vals []uint) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendUint(dst, v) + } + return dst +} + +// AppendUint8 encodes and inserts a unsigned int8 value into the dst byte array. +func (e Encoder) AppendUint8(dst []byte, val uint8) []byte { + return e.AppendUint(dst, uint(val)) +} + +// AppendUints8 encodes and inserts an array of uint8 values into the dst byte array. +func (e Encoder) AppendUints8(dst []byte, vals []uint8) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendUint8(dst, v) + } + return dst +} + +// AppendUint16 encodes and inserts a uint16 value into the dst byte array. +func (e Encoder) AppendUint16(dst []byte, val uint16) []byte { + return e.AppendUint(dst, uint(val)) +} + +// AppendUints16 encodes and inserts an array of uint16 values into the dst byte array. +func (e Encoder) AppendUints16(dst []byte, vals []uint16) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendUint16(dst, v) + } + return dst +} + +// AppendUint32 encodes and inserts a uint32 value into the dst byte array. +func (e Encoder) AppendUint32(dst []byte, val uint32) []byte { + return e.AppendUint(dst, uint(val)) +} + +// AppendUints32 encodes and inserts an array of uint32 values into the dst byte array. +func (e Encoder) AppendUints32(dst []byte, vals []uint32) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendUint32(dst, v) + } + return dst +} + +// AppendUint64 encodes and inserts a uint64 value into the dst byte array. +func (Encoder) AppendUint64(dst []byte, val uint64) []byte { + major := majorTypeUnsignedInt + contentVal := val + if contentVal <= additionalMax { + lb := byte(contentVal) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(contentVal)) + } + return dst +} + +// AppendUints64 encodes and inserts an array of uint64 values into the dst byte array. +func (e Encoder) AppendUints64(dst []byte, vals []uint64) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendUint64(dst, v) + } + return dst +} + +// AppendFloat32 encodes and inserts a single precision float value into the dst byte array. +func (Encoder) AppendFloat32(dst []byte, val float32) []byte { + switch { + case math.IsNaN(float64(val)): + return append(dst, "\xfa\x7f\xc0\x00\x00"...) + case math.IsInf(float64(val), 1): + return append(dst, "\xfa\x7f\x80\x00\x00"...) + case math.IsInf(float64(val), -1): + return append(dst, "\xfa\xff\x80\x00\x00"...) + } + major := majorTypeSimpleAndFloat + subType := additionalTypeFloat32 + n := math.Float32bits(val) + var buf [4]byte + for i := uint(0); i < 4; i++ { + buf[i] = byte(n >> ((3 - i) * 8)) + } + return append(append(dst, byte(major|subType)), buf[0], buf[1], buf[2], buf[3]) +} + +// AppendFloats32 encodes and inserts an array of single precision float value into the dst byte array. +func (e Encoder) AppendFloats32(dst []byte, vals []float32) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendFloat32(dst, v) + } + return dst +} + +// AppendFloat64 encodes and inserts a double precision float value into the dst byte array. +func (Encoder) AppendFloat64(dst []byte, val float64) []byte { + switch { + case math.IsNaN(val): + return append(dst, "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00"...) + case math.IsInf(val, 1): + return append(dst, "\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00"...) + case math.IsInf(val, -1): + return append(dst, "\xfb\xff\xf0\x00\x00\x00\x00\x00\x00"...) + } + major := majorTypeSimpleAndFloat + subType := additionalTypeFloat64 + n := math.Float64bits(val) + dst = append(dst, byte(major|subType)) + for i := uint(1); i <= 8; i++ { + b := byte(n >> ((8 - i) * 8)) + dst = append(dst, b) + } + return dst +} + +// AppendFloats64 encodes and inserts an array of double precision float values into the dst byte array. +func (e Encoder) AppendFloats64(dst []byte, vals []float64) []byte { + major := majorTypeArray + l := len(vals) + if l == 0 { + return e.AppendArrayEnd(e.AppendArrayStart(dst)) + } + if l <= additionalMax { + lb := byte(l) + dst = append(dst, byte(major|lb)) + } else { + dst = appendCborTypePrefix(dst, major, uint64(l)) + } + for _, v := range vals { + dst = e.AppendFloat64(dst, v) + } + return dst +} + +// AppendInterface takes an arbitrary object and converts it to JSON and embeds it dst. +func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte { + marshaled, err := json.Marshal(i) + if err != nil { + return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err)) + } + return AppendEmbeddedJSON(dst, marshaled) +} + +// AppendIPAddr encodes and inserts an IP Address (IPv4 or IPv6). +func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte { + dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) + dst = append(dst, byte(additionalTypeTagNetworkAddr>>8)) + dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff)) + return e.AppendBytes(dst, ip) +} + +// AppendIPPrefix encodes and inserts an IP Address Prefix (Address + Mask Length). +func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte { + dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) + dst = append(dst, byte(additionalTypeTagNetworkPrefix>>8)) + dst = append(dst, byte(additionalTypeTagNetworkPrefix&0xff)) + + // Prefix is a tuple (aka MAP of 1 pair of elements) - + // first element is prefix, second is mask length. + dst = append(dst, byte(majorTypeMap|0x1)) + dst = e.AppendBytes(dst, pfx.IP) + maskLen, _ := pfx.Mask.Size() + return e.AppendUint8(dst, uint8(maskLen)) +} + +// AppendMACAddr encodes and inserts an Hardware (MAC) address. +func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte { + dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) + dst = append(dst, byte(additionalTypeTagNetworkAddr>>8)) + dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff)) + return e.AppendBytes(dst, ha) +} + +// AppendHex adds a TAG and inserts a hex bytes as a string. +func (e Encoder) AppendHex(dst []byte, val []byte) []byte { + dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) + dst = append(dst, byte(additionalTypeTagHexString>>8)) + dst = append(dst, byte(additionalTypeTagHexString&0xff)) + return e.AppendBytes(dst, val) +} diff --git a/vendor/github.com/rs/zerolog/internal/json/base.go b/vendor/github.com/rs/zerolog/internal/json/base.go new file mode 100644 index 0000000..d6f8839 --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/json/base.go @@ -0,0 +1,12 @@ +package json + +type Encoder struct{} + +// AppendKey appends a new key to the output JSON. +func (e Encoder) AppendKey(dst []byte, key string) []byte { + if len(dst) > 1 && dst[len(dst)-1] != '{' { + dst = append(dst, ',') + } + dst = e.AppendString(dst, key) + return append(dst, ':') +} \ No newline at end of file diff --git a/vendor/github.com/rs/zerolog/internal/json/bytes.go b/vendor/github.com/rs/zerolog/internal/json/bytes.go new file mode 100644 index 0000000..de64120 --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/json/bytes.go @@ -0,0 +1,85 @@ +package json + +import "unicode/utf8" + +// AppendBytes is a mirror of appendString with []byte arg +func (Encoder) AppendBytes(dst, s []byte) []byte { + dst = append(dst, '"') + for i := 0; i < len(s); i++ { + if !noEscapeTable[s[i]] { + dst = appendBytesComplex(dst, s, i) + return append(dst, '"') + } + } + dst = append(dst, s...) + return append(dst, '"') +} + +// AppendHex encodes the input bytes to a hex string and appends +// the encoded string to the input byte slice. +// +// The operation loops though each byte and encodes it as hex using +// the hex lookup table. +func (Encoder) AppendHex(dst, s []byte) []byte { + dst = append(dst, '"') + for _, v := range s { + dst = append(dst, hex[v>>4], hex[v&0x0f]) + } + return append(dst, '"') +} + +// appendBytesComplex is a mirror of the appendStringComplex +// with []byte arg +func appendBytesComplex(dst, s []byte, i int) []byte { + start := 0 + for i < len(s) { + b := s[i] + if b >= utf8.RuneSelf { + r, size := utf8.DecodeRune(s[i:]) + if r == utf8.RuneError && size == 1 { + if start < i { + dst = append(dst, s[start:i]...) + } + dst = append(dst, `\ufffd`...) + i += size + start = i + continue + } + i += size + continue + } + if noEscapeTable[b] { + i++ + continue + } + // We encountered a character that needs to be encoded. + // Let's append the previous simple characters to the byte slice + // and switch our operation to read and encode the remainder + // characters byte-by-byte. + if start < i { + dst = append(dst, s[start:i]...) + } + switch b { + case '"', '\\': + dst = append(dst, '\\', b) + case '\b': + dst = append(dst, '\\', 'b') + case '\f': + dst = append(dst, '\\', 'f') + case '\n': + dst = append(dst, '\\', 'n') + case '\r': + dst = append(dst, '\\', 'r') + case '\t': + dst = append(dst, '\\', 't') + default: + dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) + } + i++ + start = i + } + if start < len(s) { + dst = append(dst, s[start:]...) + } + return dst +} diff --git a/vendor/github.com/rs/zerolog/internal/json/string.go b/vendor/github.com/rs/zerolog/internal/json/string.go new file mode 100644 index 0000000..815906f --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/json/string.go @@ -0,0 +1,121 @@ +package json + +import "unicode/utf8" + +const hex = "0123456789abcdef" + +var noEscapeTable = [256]bool{} + +func init() { + for i := 0; i <= 0x7e; i++ { + noEscapeTable[i] = i >= 0x20 && i != '\\' && i != '"' + } +} + +// AppendStrings encodes the input strings to json and +// appends the encoded string list to the input byte slice. +func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = e.AppendString(dst, vals[0]) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = e.AppendString(append(dst, ','), val) + } + } + dst = append(dst, ']') + return dst +} + +// AppendString encodes the input string to json and appends +// the encoded string to the input byte slice. +// +// The operation loops though each byte in the string looking +// for characters that need json or utf8 encoding. If the string +// does not need encoding, then the string is appended in it's +// entirety to the byte slice. +// If we encounter a byte that does need encoding, switch up +// the operation and perform a byte-by-byte read-encode-append. +func (Encoder) AppendString(dst []byte, s string) []byte { + // Start with a double quote. + dst = append(dst, '"') + // Loop through each character in the string. + for i := 0; i < len(s); i++ { + // Check if the character needs encoding. Control characters, slashes, + // and the double quote need json encoding. Bytes above the ascii + // boundary needs utf8 encoding. + if !noEscapeTable[s[i]] { + // We encountered a character that needs to be encoded. Switch + // to complex version of the algorithm. + dst = appendStringComplex(dst, s, i) + return append(dst, '"') + } + } + // The string has no need for encoding an therefore is directly + // appended to the byte slice. + dst = append(dst, s...) + // End with a double quote + return append(dst, '"') +} + +// appendStringComplex is used by appendString to take over an in +// progress JSON string encoding that encountered a character that needs +// to be encoded. +func appendStringComplex(dst []byte, s string, i int) []byte { + start := 0 + for i < len(s) { + b := s[i] + if b >= utf8.RuneSelf { + r, size := utf8.DecodeRuneInString(s[i:]) + if r == utf8.RuneError && size == 1 { + // In case of error, first append previous simple characters to + // the byte slice if any and append a remplacement character code + // in place of the invalid sequence. + if start < i { + dst = append(dst, s[start:i]...) + } + dst = append(dst, `\ufffd`...) + i += size + start = i + continue + } + i += size + continue + } + if noEscapeTable[b] { + i++ + continue + } + // We encountered a character that needs to be encoded. + // Let's append the previous simple characters to the byte slice + // and switch our operation to read and encode the remainder + // characters byte-by-byte. + if start < i { + dst = append(dst, s[start:i]...) + } + switch b { + case '"', '\\': + dst = append(dst, '\\', b) + case '\b': + dst = append(dst, '\\', 'b') + case '\f': + dst = append(dst, '\\', 'f') + case '\n': + dst = append(dst, '\\', 'n') + case '\r': + dst = append(dst, '\\', 'r') + case '\t': + dst = append(dst, '\\', 't') + default: + dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) + } + i++ + start = i + } + if start < len(s) { + dst = append(dst, s[start:]...) + } + return dst +} diff --git a/vendor/github.com/rs/zerolog/internal/json/time.go b/vendor/github.com/rs/zerolog/internal/json/time.go new file mode 100644 index 0000000..739afff --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/json/time.go @@ -0,0 +1,76 @@ +package json + +import ( + "strconv" + "time" +) + +// AppendTime formats the input time with the given format +// and appends the encoded string to the input byte slice. +func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte { + if format == "" { + return e.AppendInt64(dst, t.Unix()) + } + return append(t.AppendFormat(append(dst, '"'), format), '"') +} + +// AppendTimes converts the input times with the given format +// and appends the encoded string list to the input byte slice. +func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte { + if format == "" { + return appendUnixTimes(dst, vals) + } + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = append(vals[0].AppendFormat(append(dst, '"'), format), '"') + if len(vals) > 1 { + for _, t := range vals[1:] { + dst = append(t.AppendFormat(append(dst, ',', '"'), format), '"') + } + } + dst = append(dst, ']') + return dst +} + +func appendUnixTimes(dst []byte, vals []time.Time) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendInt(dst, vals[0].Unix(), 10) + if len(vals) > 1 { + for _, t := range vals[1:] { + dst = strconv.AppendInt(append(dst, ','), t.Unix(), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendDuration formats the input duration with the given unit & format +// and appends the encoded string to the input byte slice. +func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte { + if useInt { + return strconv.AppendInt(dst, int64(d/unit), 10) + } + return e.AppendFloat64(dst, float64(d)/float64(unit)) +} + +// AppendDurations formats the input durations with the given unit & format +// and appends the encoded string list to the input byte slice. +func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = e.AppendDuration(dst, vals[0], unit, useInt) + if len(vals) > 1 { + for _, d := range vals[1:] { + dst = e.AppendDuration(append(dst, ','), d, unit, useInt) + } + } + dst = append(dst, ']') + return dst +} diff --git a/vendor/github.com/rs/zerolog/internal/json/types.go b/vendor/github.com/rs/zerolog/internal/json/types.go new file mode 100644 index 0000000..f343c86 --- /dev/null +++ b/vendor/github.com/rs/zerolog/internal/json/types.go @@ -0,0 +1,402 @@ +package json + +import ( + "encoding/json" + "fmt" + "math" + "net" + "strconv" +) + +// AppendNil inserts a 'Nil' object into the dst byte array. +func (Encoder) AppendNil(dst []byte) []byte { + return append(dst, "null"...) +} + +// AppendBeginMarker inserts a map start into the dst byte array. +func (Encoder) AppendBeginMarker(dst []byte) []byte { + return append(dst, '{') +} + +// AppendEndMarker inserts a map end into the dst byte array. +func (Encoder) AppendEndMarker(dst []byte) []byte { + return append(dst, '}') +} + +// AppendLineBreak appends a line break. +func (Encoder) AppendLineBreak(dst []byte) []byte { + return append(dst, '\n') +} + +// AppendArrayStart adds markers to indicate the start of an array. +func (Encoder) AppendArrayStart(dst []byte) []byte { + return append(dst, '[') +} + +// AppendArrayEnd adds markers to indicate the end of an array. +func (Encoder) AppendArrayEnd(dst []byte) []byte { + return append(dst, ']') +} + +// AppendArrayDelim adds markers to indicate end of a particular array element. +func (Encoder) AppendArrayDelim(dst []byte) []byte { + if len(dst) > 0 { + return append(dst, ',') + } + return dst +} + +// AppendBool converts the input bool to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendBool(dst []byte, val bool) []byte { + return strconv.AppendBool(dst, val) +} + +// AppendBools encodes the input bools to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendBools(dst []byte, vals []bool) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendBool(dst, vals[0]) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendBool(append(dst, ','), val) + } + } + dst = append(dst, ']') + return dst +} + +// AppendInt converts the input int to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendInt(dst []byte, val int) []byte { + return strconv.AppendInt(dst, int64(val), 10) +} + +// AppendInts encodes the input ints to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendInts(dst []byte, vals []int) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendInt(dst, int64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendInt(append(dst, ','), int64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendInt8 converts the input []int8 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendInt8(dst []byte, val int8) []byte { + return strconv.AppendInt(dst, int64(val), 10) +} + +// AppendInts8 encodes the input int8s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendInts8(dst []byte, vals []int8) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendInt(dst, int64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendInt(append(dst, ','), int64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendInt16 converts the input int16 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendInt16(dst []byte, val int16) []byte { + return strconv.AppendInt(dst, int64(val), 10) +} + +// AppendInts16 encodes the input int16s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendInts16(dst []byte, vals []int16) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendInt(dst, int64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendInt(append(dst, ','), int64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendInt32 converts the input int32 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendInt32(dst []byte, val int32) []byte { + return strconv.AppendInt(dst, int64(val), 10) +} + +// AppendInts32 encodes the input int32s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendInts32(dst []byte, vals []int32) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendInt(dst, int64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendInt(append(dst, ','), int64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendInt64 converts the input int64 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendInt64(dst []byte, val int64) []byte { + return strconv.AppendInt(dst, val, 10) +} + +// AppendInts64 encodes the input int64s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendInts64(dst []byte, vals []int64) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendInt(dst, vals[0], 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendInt(append(dst, ','), val, 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendUint converts the input uint to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendUint(dst []byte, val uint) []byte { + return strconv.AppendUint(dst, uint64(val), 10) +} + +// AppendUints encodes the input uints to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendUints(dst []byte, vals []uint) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendUint(dst, uint64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendUint8 converts the input uint8 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendUint8(dst []byte, val uint8) []byte { + return strconv.AppendUint(dst, uint64(val), 10) +} + +// AppendUints8 encodes the input uint8s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendUints8(dst []byte, vals []uint8) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendUint(dst, uint64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendUint16 converts the input uint16 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendUint16(dst []byte, val uint16) []byte { + return strconv.AppendUint(dst, uint64(val), 10) +} + +// AppendUints16 encodes the input uint16s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendUints16(dst []byte, vals []uint16) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendUint(dst, uint64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendUint32 converts the input uint32 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendUint32(dst []byte, val uint32) []byte { + return strconv.AppendUint(dst, uint64(val), 10) +} + +// AppendUints32 encodes the input uint32s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendUints32(dst []byte, vals []uint32) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendUint(dst, uint64(vals[0]), 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) + } + } + dst = append(dst, ']') + return dst +} + +// AppendUint64 converts the input uint64 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendUint64(dst []byte, val uint64) []byte { + return strconv.AppendUint(dst, uint64(val), 10) +} + +// AppendUints64 encodes the input uint64s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendUints64(dst []byte, vals []uint64) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = strconv.AppendUint(dst, vals[0], 10) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = strconv.AppendUint(append(dst, ','), val, 10) + } + } + dst = append(dst, ']') + return dst +} + +func appendFloat(dst []byte, val float64, bitSize int) []byte { + // JSON does not permit NaN or Infinity. A typical JSON encoder would fail + // with an error, but a logging library wants the data to get thru so we + // make a tradeoff and store those types as string. + switch { + case math.IsNaN(val): + return append(dst, `"NaN"`...) + case math.IsInf(val, 1): + return append(dst, `"+Inf"`...) + case math.IsInf(val, -1): + return append(dst, `"-Inf"`...) + } + return strconv.AppendFloat(dst, val, 'f', -1, bitSize) +} + +// AppendFloat32 converts the input float32 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendFloat32(dst []byte, val float32) []byte { + return appendFloat(dst, float64(val), 32) +} + +// AppendFloats32 encodes the input float32s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendFloats32(dst []byte, vals []float32) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = appendFloat(dst, float64(vals[0]), 32) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = appendFloat(append(dst, ','), float64(val), 32) + } + } + dst = append(dst, ']') + return dst +} + +// AppendFloat64 converts the input float64 to a string and +// appends the encoded string to the input byte slice. +func (Encoder) AppendFloat64(dst []byte, val float64) []byte { + return appendFloat(dst, val, 64) +} + +// AppendFloats64 encodes the input float64s to json and +// appends the encoded string list to the input byte slice. +func (Encoder) AppendFloats64(dst []byte, vals []float64) []byte { + if len(vals) == 0 { + return append(dst, '[', ']') + } + dst = append(dst, '[') + dst = appendFloat(dst, vals[0], 32) + if len(vals) > 1 { + for _, val := range vals[1:] { + dst = appendFloat(append(dst, ','), val, 64) + } + } + dst = append(dst, ']') + return dst +} + +// AppendInterface marshals the input interface to a string and +// appends the encoded string to the input byte slice. +func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte { + marshaled, err := json.Marshal(i) + if err != nil { + return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err)) + } + return append(dst, marshaled...) +} + +// AppendObjectData takes in an object that is already in a byte array +// and adds it to the dst. +func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { + // Two conditions we want to put a ',' between existing content and + // new content: + // 1. new content starts with '{' - which shd be dropped OR + // 2. existing content has already other fields + if o[0] == '{' { + o[0] = ',' + } else if len(dst) > 1 { + dst = append(dst, ',') + } + return append(dst, o...) +} + +// AppendIPAddr adds IPv4 or IPv6 address to dst. +func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte { + return e.AppendString(dst, ip.String()) +} + +// AppendIPPrefix adds IPv4 or IPv6 Prefix (address & mask) to dst. +func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte { + return e.AppendString(dst, pfx.String()) + +} + +// AppendMACAddr adds MAC address to dst. +func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte { + return e.AppendString(dst, ha.String()) +} diff --git a/vendor/github.com/rs/zerolog/log.go b/vendor/github.com/rs/zerolog/log.go new file mode 100644 index 0000000..8eb45a8 --- /dev/null +++ b/vendor/github.com/rs/zerolog/log.go @@ -0,0 +1,400 @@ +// Package zerolog provides a lightweight logging library dedicated to JSON logging. +// +// A global Logger can be use for simple logging: +// +// import "github.com/rs/zerolog/log" +// +// log.Info().Msg("hello world") +// // Output: {"time":1494567715,"level":"info","message":"hello world"} +// +// NOTE: To import the global logger, import the "log" subpackage "github.com/rs/zerolog/log". +// +// Fields can be added to log messages: +// +// log.Info().Str("foo", "bar").Msg("hello world") +// // Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"} +// +// Create logger instance to manage different outputs: +// +// logger := zerolog.New(os.Stderr).With().Timestamp().Logger() +// logger.Info(). +// Str("foo", "bar"). +// Msg("hello world") +// // Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"} +// +// Sub-loggers let you chain loggers with additional context: +// +// sublogger := log.With().Str("component": "foo").Logger() +// sublogger.Info().Msg("hello world") +// // Output: {"time":1494567715,"level":"info","message":"hello world","component":"foo"} +// +// Level logging +// +// zerolog.SetGlobalLevel(zerolog.InfoLevel) +// +// log.Debug().Msg("filtered out message") +// log.Info().Msg("routed message") +// +// if e := log.Debug(); e.Enabled() { +// // Compute log output only if enabled. +// value := compute() +// e.Str("foo": value).Msg("some debug message") +// } +// // Output: {"level":"info","time":1494567715,"routed message"} +// +// Customize automatic field names: +// +// log.TimestampFieldName = "t" +// log.LevelFieldName = "p" +// log.MessageFieldName = "m" +// +// log.Info().Msg("hello world") +// // Output: {"t":1494567715,"p":"info","m":"hello world"} +// +// Log with no level and message: +// +// log.Log().Str("foo","bar").Msg("") +// // Output: {"time":1494567715,"foo":"bar"} +// +// Add contextual fields to global Logger: +// +// log.Logger = log.With().Str("foo", "bar").Logger() +// +// Sample logs: +// +// sampled := log.Sample(&zerolog.BasicSampler{N: 10}) +// sampled.Info().Msg("will be logged every 10 messages") +// +// Log with contextual hooks: +// +// // Create the hook: +// type SeverityHook struct{} +// +// func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { +// if level != zerolog.NoLevel { +// e.Str("severity", level.String()) +// } +// } +// +// // And use it: +// var h SeverityHook +// log := zerolog.New(os.Stdout).Hook(h) +// log.Warn().Msg("") +// // Output: {"level":"warn","severity":"warn"} +// +// +// Caveats +// +// There is no fields deduplication out-of-the-box. +// Using the same key multiple times creates new key in final JSON each time. +// +// logger := zerolog.New(os.Stderr).With().Timestamp().Logger() +// logger.Info(). +// Timestamp(). +// Msg("dup") +// // Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"} +// +// However, it’s not a big deal though as JSON accepts dup keys, +// the last one prevails. +package zerolog + +import ( + "fmt" + "io" + "io/ioutil" + "os" + "strconv" +) + +// Level defines log levels. +type Level uint8 + +const ( + // DebugLevel defines debug log level. + DebugLevel Level = iota + // InfoLevel defines info log level. + InfoLevel + // WarnLevel defines warn log level. + WarnLevel + // ErrorLevel defines error log level. + ErrorLevel + // FatalLevel defines fatal log level. + FatalLevel + // PanicLevel defines panic log level. + PanicLevel + // NoLevel defines an absent log level. + NoLevel + // Disabled disables the logger. + Disabled +) + +func (l Level) String() string { + switch l { + case DebugLevel: + return "debug" + case InfoLevel: + return "info" + case WarnLevel: + return "warn" + case ErrorLevel: + return "error" + case FatalLevel: + return "fatal" + case PanicLevel: + return "panic" + case NoLevel: + return "" + } + return "" +} + +// ParseLevel converts a level string into a zerolog Level value. +// returns an error if the input string does not match known values. +func ParseLevel(levelStr string) (Level, error) { + switch levelStr { + case DebugLevel.String(): + return DebugLevel, nil + case InfoLevel.String(): + return InfoLevel, nil + case WarnLevel.String(): + return WarnLevel, nil + case ErrorLevel.String(): + return ErrorLevel, nil + case FatalLevel.String(): + return FatalLevel, nil + case PanicLevel.String(): + return PanicLevel, nil + case NoLevel.String(): + return NoLevel, nil + } + return NoLevel, fmt.Errorf("Unknown Level String: '%s', defaulting to NoLevel", levelStr) +} + +// A Logger represents an active logging object that generates lines +// of JSON output to an io.Writer. Each logging operation makes a single +// call to the Writer's Write method. There is no guaranty on access +// serialization to the Writer. If your Writer is not thread safe, +// you may consider a sync wrapper. +type Logger struct { + w LevelWriter + level Level + sampler Sampler + context []byte + hooks []Hook +} + +// New creates a root logger with given output writer. If the output writer implements +// the LevelWriter interface, the WriteLevel method will be called instead of the Write +// one. +// +// Each logging operation makes a single call to the Writer's Write method. There is no +// guaranty on access serialization to the Writer. If your Writer is not thread safe, +// you may consider using sync wrapper. +func New(w io.Writer) Logger { + if w == nil { + w = ioutil.Discard + } + lw, ok := w.(LevelWriter) + if !ok { + lw = levelWriterAdapter{w} + } + return Logger{w: lw} +} + +// Nop returns a disabled logger for which all operation are no-op. +func Nop() Logger { + return New(nil).Level(Disabled) +} + +// Output duplicates the current logger and sets w as its output. +func (l Logger) Output(w io.Writer) Logger { + l2 := New(w) + l2.level = l.level + l2.sampler = l.sampler + if len(l.hooks) > 0 { + l2.hooks = append(l2.hooks, l.hooks...) + } + if l.context != nil { + l2.context = make([]byte, len(l.context), cap(l.context)) + copy(l2.context, l.context) + } + return l2 +} + +// With creates a child logger with the field added to its context. +func (l Logger) With() Context { + context := l.context + l.context = make([]byte, 0, 500) + if context != nil { + l.context = append(l.context, context...) + } + return Context{l} +} + +// UpdateContext updates the internal logger's context. +// +// Use this method with caution. If unsure, prefer the With method. +func (l *Logger) UpdateContext(update func(c Context) Context) { + if l == disabledLogger { + return + } + if cap(l.context) == 0 { + l.context = make([]byte, 0, 500) + } + c := update(Context{*l}) + l.context = c.l.context +} + +// Level creates a child logger with the minimum accepted level set to level. +func (l Logger) Level(lvl Level) Logger { + l.level = lvl + return l +} + +// Sample returns a logger with the s sampler. +func (l Logger) Sample(s Sampler) Logger { + l.sampler = s + return l +} + +// Hook returns a logger with the h Hook. +func (l Logger) Hook(h Hook) Logger { + l.hooks = append(l.hooks, h) + return l +} + +// Debug starts a new message with debug level. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) Debug() *Event { + return l.newEvent(DebugLevel, nil) +} + +// Info starts a new message with info level. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) Info() *Event { + return l.newEvent(InfoLevel, nil) +} + +// Warn starts a new message with warn level. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) Warn() *Event { + return l.newEvent(WarnLevel, nil) +} + +// Error starts a new message with error level. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) Error() *Event { + return l.newEvent(ErrorLevel, nil) +} + +// Fatal starts a new message with fatal level. The os.Exit(1) function +// is called by the Msg method, which terminates the program immediately. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) Fatal() *Event { + return l.newEvent(FatalLevel, func(msg string) { os.Exit(1) }) +} + +// Panic starts a new message with panic level. The panic() function +// is called by the Msg method, which stops the ordinary flow of a goroutine. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) Panic() *Event { + return l.newEvent(PanicLevel, func(msg string) { panic(msg) }) +} + +// WithLevel starts a new message with level. Unlike Fatal and Panic +// methods, WithLevel does not terminate the program or stop the ordinary +// flow of a gourotine when used with their respective levels. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) WithLevel(level Level) *Event { + switch level { + case DebugLevel: + return l.Debug() + case InfoLevel: + return l.Info() + case WarnLevel: + return l.Warn() + case ErrorLevel: + return l.Error() + case FatalLevel: + return l.newEvent(FatalLevel, nil) + case PanicLevel: + return l.newEvent(PanicLevel, nil) + case NoLevel: + return l.Log() + case Disabled: + return nil + default: + panic("zerolog: WithLevel(): invalid level: " + strconv.Itoa(int(level))) + } +} + +// Log starts a new message with no level. Setting GlobalLevel to Disabled +// will still disable events produced by this method. +// +// You must call Msg on the returned event in order to send the event. +func (l *Logger) Log() *Event { + return l.newEvent(NoLevel, nil) +} + +// Print sends a log event using debug level and no extra field. +// Arguments are handled in the manner of fmt.Print. +func (l *Logger) Print(v ...interface{}) { + if e := l.Debug(); e.Enabled() { + e.Msg(fmt.Sprint(v...)) + } +} + +// Printf sends a log event using debug level and no extra field. +// Arguments are handled in the manner of fmt.Printf. +func (l *Logger) Printf(format string, v ...interface{}) { + if e := l.Debug(); e.Enabled() { + e.Msg(fmt.Sprintf(format, v...)) + } +} + +// Write implements the io.Writer interface. This is useful to set as a writer +// for the standard library log. +func (l Logger) Write(p []byte) (n int, err error) { + n = len(p) + if n > 0 && p[n-1] == '\n' { + // Trim CR added by stdlog. + p = p[0 : n-1] + } + l.Log().Msg(string(p)) + return +} + +func (l *Logger) newEvent(level Level, done func(string)) *Event { + enabled := l.should(level) + if !enabled { + return nil + } + e := newEvent(l.w, level) + e.done = done + e.ch = l.hooks + if level != NoLevel { + e.Str(LevelFieldName, level.String()) + } + if l.context != nil && len(l.context) > 0 { + e.buf = enc.AppendObjectData(e.buf, l.context) + } + return e +} + +// should returns true if the log event should be logged. +func (l *Logger) should(lvl Level) bool { + if lvl < l.level || lvl < GlobalLevel() { + return false + } + if l.sampler != nil && !samplingDisabled() { + return l.sampler.Sample(lvl) + } + return true +} diff --git a/vendor/github.com/rs/zerolog/pretty.png b/vendor/github.com/rs/zerolog/pretty.png new file mode 100644 index 0000000..34e4308 Binary files /dev/null and b/vendor/github.com/rs/zerolog/pretty.png differ diff --git a/vendor/github.com/rs/zerolog/sampler.go b/vendor/github.com/rs/zerolog/sampler.go new file mode 100644 index 0000000..2360f0d --- /dev/null +++ b/vendor/github.com/rs/zerolog/sampler.go @@ -0,0 +1,126 @@ +package zerolog + +import ( + "math/rand" + "sync/atomic" + "time" +) + +var ( + // Often samples log every ~ 10 events. + Often = RandomSampler(10) + // Sometimes samples log every ~ 100 events. + Sometimes = RandomSampler(100) + // Rarely samples log every ~ 1000 events. + Rarely = RandomSampler(1000) +) + +// Sampler defines an interface to a log sampler. +type Sampler interface { + // Sample returns true if the event should be part of the sample, false if + // the event should be dropped. + Sample(lvl Level) bool +} + +// RandomSampler use a PRNG to randomly sample an event out of N events, +// regardless of their level. +type RandomSampler uint32 + +// Sample implements the Sampler interface. +func (s RandomSampler) Sample(lvl Level) bool { + if s <= 0 { + return false + } + if rand.Intn(int(s)) != 0 { + return false + } + return true +} + +// BasicSampler is a sampler that will send every Nth events, regardless of +// there level. +type BasicSampler struct { + N uint32 + counter uint32 +} + +// Sample implements the Sampler interface. +func (s *BasicSampler) Sample(lvl Level) bool { + c := atomic.AddUint32(&s.counter, 1) + return c%s.N == s.N-1 +} + +// BurstSampler lets Burst events pass per Period then pass the decision to +// NextSampler. If Sampler is not set, all subsequent events are rejected. +type BurstSampler struct { + // Burst is the maximum number of event per period allowed before calling + // NextSampler. + Burst uint32 + // Period defines the burst period. If 0, NextSampler is always called. + Period time.Duration + // NextSampler is the sampler used after the burst is reached. If nil, + // events are always rejected after the burst. + NextSampler Sampler + + counter uint32 + resetAt int64 +} + +// Sample implements the Sampler interface. +func (s *BurstSampler) Sample(lvl Level) bool { + if s.Burst > 0 && s.Period > 0 { + if s.inc() <= s.Burst { + return true + } + } + if s.NextSampler == nil { + return false + } + return s.NextSampler.Sample(lvl) +} + +func (s *BurstSampler) inc() uint32 { + now := time.Now().UnixNano() + resetAt := atomic.LoadInt64(&s.resetAt) + var c uint32 + if now > resetAt { + c = 1 + atomic.StoreUint32(&s.counter, c) + newResetAt := now + s.Period.Nanoseconds() + reset := atomic.CompareAndSwapInt64(&s.resetAt, resetAt, newResetAt) + if !reset { + // Lost the race with another goroutine trying to reset. + c = atomic.AddUint32(&s.counter, 1) + } + } else { + c = atomic.AddUint32(&s.counter, 1) + } + return c +} + +// LevelSampler applies a different sampler for each level. +type LevelSampler struct { + DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler +} + +func (s LevelSampler) Sample(lvl Level) bool { + switch lvl { + case DebugLevel: + if s.DebugSampler != nil { + return s.DebugSampler.Sample(lvl) + } + case InfoLevel: + if s.InfoSampler != nil { + return s.InfoSampler.Sample(lvl) + } + case WarnLevel: + if s.WarnSampler != nil { + return s.WarnSampler.Sample(lvl) + } + case ErrorLevel: + if s.ErrorSampler != nil { + return s.ErrorSampler.Sample(lvl) + } + } + return true +} diff --git a/vendor/github.com/rs/zerolog/syslog.go b/vendor/github.com/rs/zerolog/syslog.go new file mode 100644 index 0000000..82b470e --- /dev/null +++ b/vendor/github.com/rs/zerolog/syslog.go @@ -0,0 +1,57 @@ +// +build !windows +// +build !binary_log + +package zerolog + +import ( + "io" +) + +// SyslogWriter is an interface matching a syslog.Writer struct. +type SyslogWriter interface { + io.Writer + Debug(m string) error + Info(m string) error + Warning(m string) error + Err(m string) error + Emerg(m string) error + Crit(m string) error +} + +type syslogWriter struct { + w SyslogWriter +} + +// SyslogLevelWriter wraps a SyslogWriter and call the right syslog level +// method matching the zerolog level. +func SyslogLevelWriter(w SyslogWriter) LevelWriter { + return syslogWriter{w} +} + +func (sw syslogWriter) Write(p []byte) (n int, err error) { + return sw.w.Write(p) +} + +// WriteLevel implements LevelWriter interface. +func (sw syslogWriter) WriteLevel(level Level, p []byte) (n int, err error) { + switch level { + case DebugLevel: + err = sw.w.Debug(string(p)) + case InfoLevel: + err = sw.w.Info(string(p)) + case WarnLevel: + err = sw.w.Warning(string(p)) + case ErrorLevel: + err = sw.w.Err(string(p)) + case FatalLevel: + err = sw.w.Emerg(string(p)) + case PanicLevel: + err = sw.w.Crit(string(p)) + case NoLevel: + err = sw.w.Info(string(p)) + default: + panic("invalid level") + } + n = len(p) + return +} diff --git a/vendor/github.com/rs/zerolog/writer.go b/vendor/github.com/rs/zerolog/writer.go new file mode 100644 index 0000000..a58d717 --- /dev/null +++ b/vendor/github.com/rs/zerolog/writer.go @@ -0,0 +1,100 @@ +package zerolog + +import ( + "io" + "sync" +) + +// LevelWriter defines as interface a writer may implement in order +// to receive level information with payload. +type LevelWriter interface { + io.Writer + WriteLevel(level Level, p []byte) (n int, err error) +} + +type levelWriterAdapter struct { + io.Writer +} + +func (lw levelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error) { + return lw.Write(p) +} + +type syncWriter struct { + mu sync.Mutex + lw LevelWriter +} + +// SyncWriter wraps w so that each call to Write is synchronized with a mutex. +// This syncer can be the call to writer's Write method is not thread safe. +// Note that os.File Write operation is using write() syscall which is supposed +// to be thread-safe on POSIX systems. So there is no need to use this with +// os.File on such systems as zerolog guaranties to issue a single Write call +// per log event. +func SyncWriter(w io.Writer) io.Writer { + if lw, ok := w.(LevelWriter); ok { + return &syncWriter{lw: lw} + } + return &syncWriter{lw: levelWriterAdapter{w}} +} + +// Write implements the io.Writer interface. +func (s *syncWriter) Write(p []byte) (n int, err error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.lw.Write(p) +} + +// WriteLevel implements the LevelWriter interface. +func (s *syncWriter) WriteLevel(l Level, p []byte) (n int, err error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.lw.WriteLevel(l, p) +} + +type multiLevelWriter struct { + writers []LevelWriter +} + +func (t multiLevelWriter) Write(p []byte) (n int, err error) { + for _, w := range t.writers { + n, err = w.Write(p) + if err != nil { + return + } + if n != len(p) { + err = io.ErrShortWrite + return + } + } + return len(p), nil +} + +func (t multiLevelWriter) WriteLevel(l Level, p []byte) (n int, err error) { + for _, w := range t.writers { + n, err = w.WriteLevel(l, p) + if err != nil { + return + } + if n != len(p) { + err = io.ErrShortWrite + return + } + } + return len(p), nil +} + +// MultiLevelWriter creates a writer that duplicates its writes to all the +// provided writers, similar to the Unix tee(1) command. If some writers +// implement LevelWriter, their WriteLevel method will be used instead of Write. +func MultiLevelWriter(writers ...io.Writer) LevelWriter { + lwriters := make([]LevelWriter, 0, len(writers)) + for _, w := range writers { + if lw, ok := w.(LevelWriter); ok { + lwriters = append(lwriters, lw) + } else { + lwriters = append(lwriters, levelWriterAdapter{w}) + } + } + return multiLevelWriter{lwriters} +} diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml new file mode 100644 index 0000000..9f55693 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/.travis.yml @@ -0,0 +1,12 @@ +language: go + +go: + - 1.4 + - 1.5 + - 1.6 + - 1.7 + - 1.8 + - 1.9 + - tip + +go_import_path: gopkg.in/yaml.v2 diff --git a/vendor/gopkg.in/yaml.v2/LICENSE b/vendor/gopkg.in/yaml.v2/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/gopkg.in/yaml.v2/LICENSE.libyaml b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml new file mode 100644 index 0000000..8da58fb --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml @@ -0,0 +1,31 @@ +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original copyright and license: + + apic.go + emitterc.go + parserc.go + readerc.go + scannerc.go + writerc.go + yamlh.go + yamlprivateh.go + +Copyright (c) 2006 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/gopkg.in/yaml.v2/NOTICE b/vendor/gopkg.in/yaml.v2/NOTICE new file mode 100644 index 0000000..866d74a --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/NOTICE @@ -0,0 +1,13 @@ +Copyright 2011-2016 Canonical Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/gopkg.in/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md new file mode 100644 index 0000000..b50c6e8 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/README.md @@ -0,0 +1,133 @@ +# YAML support for the Go language + +Introduction +------------ + +The yaml package enables Go programs to comfortably encode and decode YAML +values. It was developed within [Canonical](https://www.canonical.com) as +part of the [juju](https://juju.ubuntu.com) project, and is based on a +pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) +C library to parse and generate YAML data quickly and reliably. + +Compatibility +------------- + +The yaml package supports most of YAML 1.1 and 1.2, including support for +anchors, tags, map merging, etc. Multi-document unmarshalling is not yet +implemented, and base-60 floats from YAML 1.1 are purposefully not +supported since they're a poor design and are gone in YAML 1.2. + +Installation and usage +---------------------- + +The import path for the package is *gopkg.in/yaml.v2*. + +To install it, run: + + go get gopkg.in/yaml.v2 + +API documentation +----------------- + +If opened in a browser, the import path itself leads to the API documentation: + + * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) + +API stability +------------- + +The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). + + +License +------- + +The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. + + +Example +------- + +```Go +package main + +import ( + "fmt" + "log" + + "gopkg.in/yaml.v2" +) + +var data = ` +a: Easy! +b: + c: 2 + d: [3, 4] +` + +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. +type T struct { + A string + B struct { + RenamedC int `yaml:"c"` + D []int `yaml:",flow"` + } +} + +func main() { + t := T{} + + err := yaml.Unmarshal([]byte(data), &t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t:\n%v\n\n", t) + + d, err := yaml.Marshal(&t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t dump:\n%s\n\n", string(d)) + + m := make(map[interface{}]interface{}) + + err = yaml.Unmarshal([]byte(data), &m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m:\n%v\n\n", m) + + d, err = yaml.Marshal(&m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m dump:\n%s\n\n", string(d)) +} +``` + +This example will generate the following output: + +``` +--- t: +{Easy! {2 [3 4]}} + +--- t dump: +a: Easy! +b: + c: 2 + d: [3, 4] + + +--- m: +map[a:Easy! b:map[c:2 d:[3 4]]] + +--- m dump: +a: Easy! +b: + c: 2 + d: + - 3 + - 4 +``` + diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go new file mode 100644 index 0000000..1f7e87e --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/apic.go @@ -0,0 +1,739 @@ +package yaml + +import ( + "io" +) + +func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { + //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + + // Check if we can move the queue at the beginning of the buffer. + if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { + if parser.tokens_head != len(parser.tokens) { + copy(parser.tokens, parser.tokens[parser.tokens_head:]) + } + parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] + parser.tokens_head = 0 + } + parser.tokens = append(parser.tokens, *token) + if pos < 0 { + return + } + copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) + parser.tokens[parser.tokens_head+pos] = *token +} + +// Create a new parser object. +func yaml_parser_initialize(parser *yaml_parser_t) bool { + *parser = yaml_parser_t{ + raw_buffer: make([]byte, 0, input_raw_buffer_size), + buffer: make([]byte, 0, input_buffer_size), + } + return true +} + +// Destroy a parser object. +func yaml_parser_delete(parser *yaml_parser_t) { + *parser = yaml_parser_t{} +} + +// String read handler. +func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + if parser.input_pos == len(parser.input) { + return 0, io.EOF + } + n = copy(buffer, parser.input[parser.input_pos:]) + parser.input_pos += n + return n, nil +} + +// Reader read handler. +func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + return parser.input_reader.Read(buffer) +} + +// Set a string input. +func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_string_read_handler + parser.input = input + parser.input_pos = 0 +} + +// Set a file input. +func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_reader_read_handler + parser.input_reader = r +} + +// Set the source encoding. +func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { + if parser.encoding != yaml_ANY_ENCODING { + panic("must set the encoding only once") + } + parser.encoding = encoding +} + +// Create a new emitter object. +func yaml_emitter_initialize(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{ + buffer: make([]byte, output_buffer_size), + raw_buffer: make([]byte, 0, output_raw_buffer_size), + states: make([]yaml_emitter_state_t, 0, initial_stack_size), + events: make([]yaml_event_t, 0, initial_queue_size), + } +} + +// Destroy an emitter object. +func yaml_emitter_delete(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{} +} + +// String write handler. +func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + *emitter.output_buffer = append(*emitter.output_buffer, buffer...) + return nil +} + +// yaml_writer_write_handler uses emitter.output_writer to write the +// emitted text. +func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + _, err := emitter.output_writer.Write(buffer) + return err +} + +// Set a string output. +func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_string_write_handler + emitter.output_buffer = output_buffer +} + +// Set a file output. +func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_writer_write_handler + emitter.output_writer = w +} + +// Set the output encoding. +func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { + if emitter.encoding != yaml_ANY_ENCODING { + panic("must set the output encoding only once") + } + emitter.encoding = encoding +} + +// Set the canonical output style. +func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { + emitter.canonical = canonical +} + +//// Set the indentation increment. +func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { + if indent < 2 || indent > 9 { + indent = 2 + } + emitter.best_indent = indent +} + +// Set the preferred line width. +func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { + if width < 0 { + width = -1 + } + emitter.best_width = width +} + +// Set if unescaped non-ASCII characters are allowed. +func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { + emitter.unicode = unicode +} + +// Set the preferred line break character. +func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { + emitter.line_break = line_break +} + +///* +// * Destroy a token object. +// */ +// +//YAML_DECLARE(void) +//yaml_token_delete(yaml_token_t *token) +//{ +// assert(token); // Non-NULL token object expected. +// +// switch (token.type) +// { +// case YAML_TAG_DIRECTIVE_TOKEN: +// yaml_free(token.data.tag_directive.handle); +// yaml_free(token.data.tag_directive.prefix); +// break; +// +// case YAML_ALIAS_TOKEN: +// yaml_free(token.data.alias.value); +// break; +// +// case YAML_ANCHOR_TOKEN: +// yaml_free(token.data.anchor.value); +// break; +// +// case YAML_TAG_TOKEN: +// yaml_free(token.data.tag.handle); +// yaml_free(token.data.tag.suffix); +// break; +// +// case YAML_SCALAR_TOKEN: +// yaml_free(token.data.scalar.value); +// break; +// +// default: +// break; +// } +// +// memset(token, 0, sizeof(yaml_token_t)); +//} +// +///* +// * Check if a string is a valid UTF-8 sequence. +// * +// * Check 'reader.c' for more details on UTF-8 encoding. +// */ +// +//static int +//yaml_check_utf8(yaml_char_t *start, size_t length) +//{ +// yaml_char_t *end = start+length; +// yaml_char_t *pointer = start; +// +// while (pointer < end) { +// unsigned char octet; +// unsigned int width; +// unsigned int value; +// size_t k; +// +// octet = pointer[0]; +// width = (octet & 0x80) == 0x00 ? 1 : +// (octet & 0xE0) == 0xC0 ? 2 : +// (octet & 0xF0) == 0xE0 ? 3 : +// (octet & 0xF8) == 0xF0 ? 4 : 0; +// value = (octet & 0x80) == 0x00 ? octet & 0x7F : +// (octet & 0xE0) == 0xC0 ? octet & 0x1F : +// (octet & 0xF0) == 0xE0 ? octet & 0x0F : +// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; +// if (!width) return 0; +// if (pointer+width > end) return 0; +// for (k = 1; k < width; k ++) { +// octet = pointer[k]; +// if ((octet & 0xC0) != 0x80) return 0; +// value = (value << 6) + (octet & 0x3F); +// } +// if (!((width == 1) || +// (width == 2 && value >= 0x80) || +// (width == 3 && value >= 0x800) || +// (width == 4 && value >= 0x10000))) return 0; +// +// pointer += width; +// } +// +// return 1; +//} +// + +// Create STREAM-START. +func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + encoding: encoding, + } +} + +// Create STREAM-END. +func yaml_stream_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + } +} + +// Create DOCUMENT-START. +func yaml_document_start_event_initialize( + event *yaml_event_t, + version_directive *yaml_version_directive_t, + tag_directives []yaml_tag_directive_t, + implicit bool, +) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: implicit, + } +} + +// Create DOCUMENT-END. +func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + implicit: implicit, + } +} + +///* +// * Create ALIAS. +// */ +// +//YAML_DECLARE(int) +//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) +//{ +// mark yaml_mark_t = { 0, 0, 0 } +// anchor_copy *yaml_char_t = NULL +// +// assert(event) // Non-NULL event object is expected. +// assert(anchor) // Non-NULL anchor is expected. +// +// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 +// +// anchor_copy = yaml_strdup(anchor) +// if (!anchor_copy) +// return 0 +// +// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) +// +// return 1 +//} + +// Create SCALAR. +func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + anchor: anchor, + tag: tag, + value: value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-START. +func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-END. +func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + } + return true +} + +// Create MAPPING-START. +func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } +} + +// Create MAPPING-END. +func yaml_mapping_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + } +} + +// Destroy an event object. +func yaml_event_delete(event *yaml_event_t) { + *event = yaml_event_t{} +} + +///* +// * Create a document object. +// */ +// +//YAML_DECLARE(int) +//yaml_document_initialize(document *yaml_document_t, +// version_directive *yaml_version_directive_t, +// tag_directives_start *yaml_tag_directive_t, +// tag_directives_end *yaml_tag_directive_t, +// start_implicit int, end_implicit int) +//{ +// struct { +// error yaml_error_type_t +// } context +// struct { +// start *yaml_node_t +// end *yaml_node_t +// top *yaml_node_t +// } nodes = { NULL, NULL, NULL } +// version_directive_copy *yaml_version_directive_t = NULL +// struct { +// start *yaml_tag_directive_t +// end *yaml_tag_directive_t +// top *yaml_tag_directive_t +// } tag_directives_copy = { NULL, NULL, NULL } +// value yaml_tag_directive_t = { NULL, NULL } +// mark yaml_mark_t = { 0, 0, 0 } +// +// assert(document) // Non-NULL document object is expected. +// assert((tag_directives_start && tag_directives_end) || +// (tag_directives_start == tag_directives_end)) +// // Valid tag directives are expected. +// +// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error +// +// if (version_directive) { +// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) +// if (!version_directive_copy) goto error +// version_directive_copy.major = version_directive.major +// version_directive_copy.minor = version_directive.minor +// } +// +// if (tag_directives_start != tag_directives_end) { +// tag_directive *yaml_tag_directive_t +// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) +// goto error +// for (tag_directive = tag_directives_start +// tag_directive != tag_directives_end; tag_directive ++) { +// assert(tag_directive.handle) +// assert(tag_directive.prefix) +// if (!yaml_check_utf8(tag_directive.handle, +// strlen((char *)tag_directive.handle))) +// goto error +// if (!yaml_check_utf8(tag_directive.prefix, +// strlen((char *)tag_directive.prefix))) +// goto error +// value.handle = yaml_strdup(tag_directive.handle) +// value.prefix = yaml_strdup(tag_directive.prefix) +// if (!value.handle || !value.prefix) goto error +// if (!PUSH(&context, tag_directives_copy, value)) +// goto error +// value.handle = NULL +// value.prefix = NULL +// } +// } +// +// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, +// tag_directives_copy.start, tag_directives_copy.top, +// start_implicit, end_implicit, mark, mark) +// +// return 1 +// +//error: +// STACK_DEL(&context, nodes) +// yaml_free(version_directive_copy) +// while (!STACK_EMPTY(&context, tag_directives_copy)) { +// value yaml_tag_directive_t = POP(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// } +// STACK_DEL(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// +// return 0 +//} +// +///* +// * Destroy a document object. +// */ +// +//YAML_DECLARE(void) +//yaml_document_delete(document *yaml_document_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// tag_directive *yaml_tag_directive_t +// +// context.error = YAML_NO_ERROR // Eliminate a compiler warning. +// +// assert(document) // Non-NULL document object is expected. +// +// while (!STACK_EMPTY(&context, document.nodes)) { +// node yaml_node_t = POP(&context, document.nodes) +// yaml_free(node.tag) +// switch (node.type) { +// case YAML_SCALAR_NODE: +// yaml_free(node.data.scalar.value) +// break +// case YAML_SEQUENCE_NODE: +// STACK_DEL(&context, node.data.sequence.items) +// break +// case YAML_MAPPING_NODE: +// STACK_DEL(&context, node.data.mapping.pairs) +// break +// default: +// assert(0) // Should not happen. +// } +// } +// STACK_DEL(&context, document.nodes) +// +// yaml_free(document.version_directive) +// for (tag_directive = document.tag_directives.start +// tag_directive != document.tag_directives.end +// tag_directive++) { +// yaml_free(tag_directive.handle) +// yaml_free(tag_directive.prefix) +// } +// yaml_free(document.tag_directives.start) +// +// memset(document, 0, sizeof(yaml_document_t)) +//} +// +///** +// * Get a document node. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_node(document *yaml_document_t, index int) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (index > 0 && document.nodes.start + index <= document.nodes.top) { +// return document.nodes.start + index - 1 +// } +// return NULL +//} +// +///** +// * Get the root object. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_root_node(document *yaml_document_t) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (document.nodes.top != document.nodes.start) { +// return document.nodes.start +// } +// return NULL +//} +// +///* +// * Add a scalar node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_scalar(document *yaml_document_t, +// tag *yaml_char_t, value *yaml_char_t, length int, +// style yaml_scalar_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// value_copy *yaml_char_t = NULL +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// assert(value) // Non-NULL value is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (length < 0) { +// length = strlen((char *)value) +// } +// +// if (!yaml_check_utf8(value, length)) goto error +// value_copy = yaml_malloc(length+1) +// if (!value_copy) goto error +// memcpy(value_copy, value, length) +// value_copy[length] = '\0' +// +// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// yaml_free(tag_copy) +// yaml_free(value_copy) +// +// return 0 +//} +// +///* +// * Add a sequence node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_sequence(document *yaml_document_t, +// tag *yaml_char_t, style yaml_sequence_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_item_t +// end *yaml_node_item_t +// top *yaml_node_item_t +// } items = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error +// +// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, items) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Add a mapping node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_mapping(document *yaml_document_t, +// tag *yaml_char_t, style yaml_mapping_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_pair_t +// end *yaml_node_pair_t +// top *yaml_node_pair_t +// } pairs = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error +// +// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, pairs) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Append an item to a sequence node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_sequence_item(document *yaml_document_t, +// sequence int, item int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// assert(document) // Non-NULL document is required. +// assert(sequence > 0 +// && document.nodes.start + sequence <= document.nodes.top) +// // Valid sequence id is required. +// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) +// // A sequence node is required. +// assert(item > 0 && document.nodes.start + item <= document.nodes.top) +// // Valid item id is required. +// +// if (!PUSH(&context, +// document.nodes.start[sequence-1].data.sequence.items, item)) +// return 0 +// +// return 1 +//} +// +///* +// * Append a pair of a key and a value to a mapping node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_mapping_pair(document *yaml_document_t, +// mapping int, key int, value int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// pair yaml_node_pair_t +// +// assert(document) // Non-NULL document is required. +// assert(mapping > 0 +// && document.nodes.start + mapping <= document.nodes.top) +// // Valid mapping id is required. +// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) +// // A mapping node is required. +// assert(key > 0 && document.nodes.start + key <= document.nodes.top) +// // Valid key id is required. +// assert(value > 0 && document.nodes.start + value <= document.nodes.top) +// // Valid value id is required. +// +// pair.key = key +// pair.value = value +// +// if (!PUSH(&context, +// document.nodes.start[mapping-1].data.mapping.pairs, pair)) +// return 0 +// +// return 1 +//} +// +// diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go new file mode 100644 index 0000000..e4e56e2 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/decode.go @@ -0,0 +1,775 @@ +package yaml + +import ( + "encoding" + "encoding/base64" + "fmt" + "io" + "math" + "reflect" + "strconv" + "time" +) + +const ( + documentNode = 1 << iota + mappingNode + sequenceNode + scalarNode + aliasNode +) + +type node struct { + kind int + line, column int + tag string + // For an alias node, alias holds the resolved alias. + alias *node + value string + implicit bool + children []*node + anchors map[string]*node +} + +// ---------------------------------------------------------------------------- +// Parser, produces a node tree out of a libyaml event stream. + +type parser struct { + parser yaml_parser_t + event yaml_event_t + doc *node + doneInit bool +} + +func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p +} + +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p +} + +func (p *parser) init() { + if p.doneInit { + return + } + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + +func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) +} + +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + return p.event.typ +} + +func (p *parser) fail() { + var where string + var line int + if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) +} + +func (p *parser) anchor(n *node, anchor []byte) { + if anchor != nil { + p.doc.anchors[string(anchor)] = n + } +} + +func (p *parser) parse() *node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + default: + panic("attempted to parse unknown event: " + p.event.typ.String()) + } +} + +func (p *parser) node(kind int) *node { + return &node{ + kind: kind, + line: p.event.start_mark.line, + column: p.event.start_mark.column, + } +} + +func (p *parser) document() *node { + n := p.node(documentNode) + n.anchors = make(map[string]*node) + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + n.children = append(n.children, p.parse()) + p.expect(yaml_DOCUMENT_END_EVENT) + return n +} + +func (p *parser) alias() *node { + n := p.node(aliasNode) + n.value = string(p.event.anchor) + n.alias = p.doc.anchors[n.value] + if n.alias == nil { + failf("unknown anchor '%s' referenced", n.value) + } + p.expect(yaml_ALIAS_EVENT) + return n +} + +func (p *parser) scalar() *node { + n := p.node(scalarNode) + n.value = string(p.event.value) + n.tag = string(p.event.tag) + n.implicit = p.event.implicit + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n +} + +func (p *parser) sequence() *node { + n := p.node(sequenceNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + n.children = append(n.children, p.parse()) + } + p.expect(yaml_SEQUENCE_END_EVENT) + return n +} + +func (p *parser) mapping() *node { + n := p.node(mappingNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + n.children = append(n.children, p.parse(), p.parse()) + } + p.expect(yaml_MAPPING_END_EVENT) + return n +} + +// ---------------------------------------------------------------------------- +// Decoder, unmarshals a node into a provided value. + +type decoder struct { + doc *node + aliases map[*node]bool + mapType reflect.Type + terrors []string + strict bool +} + +var ( + mapItemType = reflect.TypeOf(MapItem{}) + durationType = reflect.TypeOf(time.Duration(0)) + defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) + ifaceType = defaultMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) +) + +func newDecoder(strict bool) *decoder { + d := &decoder{mapType: defaultMapType, strict: strict} + d.aliases = make(map[*node]bool) + return d +} + +func (d *decoder) terror(n *node, tag string, out reflect.Value) { + if n.tag != "" { + tag = n.tag + } + value := n.value + if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) +} + +func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +// d.prepare initializes and dereferences pointers and calls UnmarshalYAML +// if a value is found to implement it. +// It returns the initialized and dereferenced out value, whether +// unmarshalling was already done by UnmarshalYAML, and if so whether +// its types unmarshalled appropriately. +// +// If n holds a null value, prepare returns before doing anything. +func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + if u, ok := out.Addr().Interface().(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false +} + +func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { + switch n.kind { + case documentNode: + return d.document(n, out) + case aliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.kind { + case scalarNode: + good = d.scalar(n, out) + case mappingNode: + good = d.mapping(n, out) + case sequenceNode: + good = d.sequence(n, out) + default: + panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) + } + return good +} + +func (d *decoder) document(n *node, out reflect.Value) (good bool) { + if len(n.children) == 1 { + d.doc = n + d.unmarshal(n.children[0], out) + return true + } + return false +} + +func (d *decoder) alias(n *node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.value) + } + d.aliases[n] = true + good = d.unmarshal(n.alias, out) + delete(d.aliases, n) + return good +} + +var zeroValue reflect.Value + +func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } +} + +func (d *decoder) scalar(n *node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.tag == "" && !n.implicit { + tag = yaml_STR_TAG + resolved = n.value + } else { + tag, resolved = resolve(n.tag, n.value) + if tag == yaml_BINARY_TAG { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + if out.Kind() == reflect.Map && !out.CanAddr() { + resetMap(out) + } else { + out.Set(reflect.Zero(out.Type())) + } + return true + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == yaml_BINARY_TAG { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == yaml_BINARY_TAG { + out.SetString(resolved.(string)) + return true + } + if resolved != nil { + out.SetString(n.value) + return true + } + case reflect.Interface: + if resolved == nil { + out.Set(reflect.Zero(out.Type())) + } else if tag == yaml_TIMESTAMP_TAG { + // It looks like a timestamp but for backward compatibility + // reasons we set it as a string, so that code that unmarshals + // timestamp-like values into interface{} will continue to + // see a string and not a time.Time. + // TODO(v3) Drop this. + out.Set(reflect.ValueOf(n.value)) + } else { + out.Set(reflect.ValueOf(resolved)) + } + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + switch resolved := resolved.(type) { + case int: + if !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + if out.Type().Elem() == reflect.TypeOf(resolved) { + // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? + elem := reflect.New(out.Type().Elem()) + elem.Elem().Set(reflect.ValueOf(resolved)) + out.Set(elem) + return true + } + } + d.terror(n, tag, out) + return false +} + +func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv +} + +func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { + l := len(n.children) + + var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, yaml_SEQ_TAG, out) + return false + } + et := out.Type().Elem() + + j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.children[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true +} + +func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Slice: + return d.mappingSlice(n, out) + case reflect.Map: + // okay + case reflect.Interface: + if d.mapType.Kind() == reflect.Map { + iface := out + out = reflect.MakeMap(d.mapType) + iface.Set(out) + } else { + slicev := reflect.New(d.mapType).Elem() + if !d.mappingSlice(n, slicev) { + return false + } + out.Set(slicev) + return true + } + default: + d.terror(n, yaml_MAP_TAG, out) + return false + } + outt := out.Type() + kt := outt.Key() + et := outt.Elem() + + mapType := d.mapType + if outt.Key() == ifaceType && outt.Elem() == ifaceType { + d.mapType = outt + } + + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + } + l := len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.children[i], k) { + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.children[i+1], e) { + d.setMapIndex(n.children[i+1], out, k, e) + } + } + } + d.mapType = mapType + return true +} + +func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) { + if d.strict && out.MapIndex(k) != zeroValue { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface())) + return + } + out.SetMapIndex(k, v) +} + +func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { + outt := out.Type() + if outt.Elem() != mapItemType { + d.terror(n, yaml_MAP_TAG, out) + return false + } + + mapType := d.mapType + d.mapType = outt + + var slice []MapItem + var l = len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + item := MapItem{} + k := reflect.ValueOf(&item.Key).Elem() + if d.unmarshal(n.children[i], k) { + v := reflect.ValueOf(&item.Value).Elem() + if d.unmarshal(n.children[i+1], v) { + slice = append(slice, item) + } + } + } + out.Set(reflect.ValueOf(slice)) + d.mapType = mapType + return true +} + +func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + name := settableValueOf("") + l := len(n.children) + + var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) + elemType = inlineMap.Type().Elem() + } + + var doneFields []bool + if d.strict { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + for i := 0; i < l; i += 2 { + ni := n.children[i] + if isMerge(ni) { + d.merge(n.children[i+1], out) + continue + } + if !d.unmarshal(ni, name) { + continue + } + if info, ok := sinfo.FieldsMap[name.String()]; ok { + if d.strict { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = out.FieldByIndex(info.Inline) + } + d.unmarshal(n.children[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.children[i+1], value) + d.setMapIndex(n.children[i+1], inlineMap, name, value) + } else if d.strict { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type())) + } + } + return true +} + +func failWantMap() { + failf("map merge requires map or sequence of maps as the value") +} + +func (d *decoder) merge(n *node, out reflect.Value) { + switch n.kind { + case mappingNode: + d.unmarshal(n, out) + case aliasNode: + an, ok := d.doc.anchors[n.value] + if ok && an.kind != mappingNode { + failWantMap() + } + d.unmarshal(n, out) + case sequenceNode: + // Step backwards as earlier nodes take precedence. + for i := len(n.children) - 1; i >= 0; i-- { + ni := n.children[i] + if ni.kind == aliasNode { + an, ok := d.doc.anchors[ni.value] + if ok && an.kind != mappingNode { + failWantMap() + } + } else if ni.kind != mappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } +} + +func isMerge(n *node) bool { + return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) +} diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go new file mode 100644 index 0000000..a1c2cc5 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/emitterc.go @@ -0,0 +1,1685 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Flush the buffer if needed. +func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true +} + +// Put a character to the output buffer. +func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true +} + +// Put a line break to the output buffer. +func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + emitter.column = 0 + emitter.line++ + return true +} + +// Copy a character from a string into buffer. +func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true +} + +// Write a whole string into buffer. +func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true +} + +// Copy a line break character from a string into buffer. +func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + emitter.column = 0 + emitter.line++ + } + return true +} + +// Set an emitter error and return false. +func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false +} + +// Emit an event. +func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true +} + +// Check if we need to accumulate more events before emitting. +// +// We accumulate extra +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +// +func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true +} + +// Append a directive to the directives stack. +func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } + + // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true +} + +// Increase the indentation level. +func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + emitter.indent += emitter.best_indent + } + return true +} + +// State dispatcher. +func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) + + case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) + + case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) + + case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) + + case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) + + case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true) + + case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) + + case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) + + case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) + + case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") +} + +// Expect STREAM-START. +func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } + + emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true + + if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true +} + +// Expect DOCUMENT-START or STREAM-END. +func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + + if event.typ == yaml_DOCUMENT_START_EVENT { + + if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } + + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } + + for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } + + implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } + + if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } + + if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } + + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") +} + +// Expect the root node. +func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) + return yaml_emitter_emit_node(emitter, event, true, false, false, false) +} + +// Expect DOCUMENT-END. +func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true +} + +// Expect a flow item node. +func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a flow key node. +func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_MAPPING_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a flow value node. +func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block item node. +func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a block key node. +func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block value node. +func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a node. +func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { + + emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key + + switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } +} + +// Expect ALIAS. +func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SCALAR. +func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SEQUENCE-START. +func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true +} + +// Expect MAPPING-START. +func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true +} + +// Check if the document content is an empty scalar. +func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? +} + +// Check if the next events represent an empty sequence. +func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT +} + +// Check if the next events represent an empty mapping. +func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT +} + +// Check if the next node can be expressed as a simple key. +func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 +} + +// Determine an acceptable scalar style. +func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } + + style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + + if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true +} + +// Write an anchor. +func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) +} + +// Write a tag. +func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true +} + +// Write a scalar. +func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) + + case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") +} + +// Check if a %YAML directive is valid. +func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true +} + +// Check if a %TAG directive is valid. +func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true +} + +// Check if an anchor is valid. +func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true +} + +// Check if a tag is valid. +func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true +} + +// Check if a scalar is valid. +func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + var ( + block_indicators = false + flow_indicators = false + line_breaks = false + special_characters = false + + leading_space = false + leading_break = false + trailing_space = false + trailing_break = false + break_space = false + space_break = false + + preceded_by_whitespace = false + followed_by_whitespace = false + previous_space = false + previous_break = false + ) + + emitter.scalar_data.value = value + + if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } + + if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } + + preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) + + if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } + + if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } + + // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } + + emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true + + if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true +} + +// Check if the event data is valid. +func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil + + switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } + + case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } + + case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + + case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true +} + +// Write the BOM character. +func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true +} + +func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + emitter.indention = true + return true +} + +func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true +} + +func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } + + c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + + c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + + emitter.whitespace = false + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } + + return true +} + +func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } + + for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { + + octet := value[i] + + var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w + + if !put(emitter, '\\') { + return false + } + + var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } + + emitter.open_ended = false + + var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true +} + +func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + + return true +} + +func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + + breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true +} diff --git a/vendor/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go new file mode 100644 index 0000000..0ee738e --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/encode.go @@ -0,0 +1,390 @@ +package yaml + +import ( + "encoding" + "fmt" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// jsonNumber is the interface of the encoding/json.Number datatype. +// Repeating the interface here avoids a dependency on encoding/json, and also +// supports other libraries like jsoniter, which use a similar datatype with +// the same interface. Detecting this interface is useful when dealing with +// structures containing json.Number, which is a string under the hood. The +// encoder should prefer the use of Int64(), Float64() and string(), in that +// order, when encoding this type. +type jsonNumber interface { + Float64() (float64, error) + Int64() (int64, error) + String() string +} + +type encoder struct { + emitter yaml_emitter_t + event yaml_event_t + out []byte + flow bool + // doneInit holds whether the initial stream_start_event has been + // emitted. + doneInit bool +} + +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) +} + +func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) +} + +func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } +} + +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() +} + +func (e *encoder) marshal(tag string, in reflect.Value) { + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch m := iface.(type) { + case jsonNumber: + integer, err := m.Int64() + if err == nil { + // In this case the json.Number is a valid int64 + in = reflect.ValueOf(integer) + break + } + float, err := m.Float64() + if err == nil { + // In this case the json.Number is a valid float64 + in = reflect.ValueOf(float) + break + } + // fallback case - no number could be obtained + in = reflect.ValueOf(m.String()) + case time.Time, *time.Time: + // Although time.Time implements TextMarshaler, + // we don't want to treat it as a string for YAML + // purposes because YAML has special support for + // timestamps. + case Marshaler: + v, err := m.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + in = reflect.ValueOf(v) + case encoding.TextMarshaler: + text, err := m.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + if in.Type() == ptrTimeType { + e.timev(tag, in.Elem()) + } else { + e.marshal(tag, in.Elem()) + } + case reflect.Struct: + if in.Type() == timeType { + e.timev(tag, in) + } else { + e.structv(tag, in) + } + case reflect.Slice, reflect.Array: + if in.Type().Elem() == mapItemType { + e.itemsv(tag, in) + } else { + e.slicev(tag, in) + } + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if in.Type() == durationType { + e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) + } else { + e.intv(tag, in) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } +} + +func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) +} + +func (e *encoder) itemsv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) + for _, item := range slice { + e.marshal("", reflect.ValueOf(item.Key)) + e.marshal("", reflect.ValueOf(item.Value)) + } + }) +} + +func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = in.FieldByIndex(info.Inline) + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) +} + +func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() +} + +// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. +// +// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported +// in YAML 1.2 and by this package, but these should be marshalled quoted for +// the time being for compatibility with other parsers. +func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) +} + +// From http://yaml.org/type/float.html, except the regular expression there +// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. +var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) + +func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == yaml_BINARY_TAG { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = yaml_BINARY_TAG + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style) +} + +func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { + implicit := tag == "" + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.emit() +} diff --git a/vendor/gopkg.in/yaml.v2/go.mod b/vendor/gopkg.in/yaml.v2/go.mod new file mode 100644 index 0000000..1934e87 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/go.mod @@ -0,0 +1,5 @@ +module "gopkg.in/yaml.v2" + +require ( + "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405 +) diff --git a/vendor/gopkg.in/yaml.v2/parserc.go b/vendor/gopkg.in/yaml.v2/parserc.go new file mode 100644 index 0000000..81d05df --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/parserc.go @@ -0,0 +1,1095 @@ +package yaml + +import ( + "bytes" +) + +// The parser implements the following grammar: +// +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// implicit_document ::= block_node DOCUMENT-END* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// block_node_or_indentless_sequence ::= +// ALIAS +// | properties (block_content | indentless_block_sequence)? +// | block_content +// | indentless_block_sequence +// block_node ::= ALIAS +// | properties block_content? +// | block_content +// flow_node ::= ALIAS +// | properties flow_content? +// | flow_content +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// block_content ::= block_collection | flow_collection | SCALAR +// flow_content ::= flow_collection | SCALAR +// block_collection ::= block_sequence | block_mapping +// flow_collection ::= flow_sequence | flow_mapping +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// block_mapping ::= BLOCK-MAPPING_START +// ((KEY block_node_or_indentless_sequence?)? +// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// flow_sequence ::= FLOW-SEQUENCE-START +// (flow_sequence_entry FLOW-ENTRY)* +// flow_sequence_entry? +// FLOW-SEQUENCE-END +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// flow_mapping ::= FLOW-MAPPING-START +// (flow_mapping_entry FLOW-ENTRY)* +// flow_mapping_entry? +// FLOW-MAPPING-END +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + +// Peek the next token in the token queue. +func peek_token(parser *yaml_parser_t) *yaml_token_t { + if parser.token_available || yaml_parser_fetch_more_tokens(parser) { + return &parser.tokens[parser.tokens_head] + } + return nil +} + +// Remove the next token from the queue (must be called after peek_token). +func skip_token(parser *yaml_parser_t) { + parser.token_available = false + parser.tokens_parsed++ + parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN + parser.tokens_head++ +} + +// Get the next event. +func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { + // Erase the event object. + *event = yaml_event_t{} + + // No events after the end of the stream or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { + return true + } + + // Generate the next event. + return yaml_parser_state_machine(parser, event) +} + +// Set parser error. +func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +// State dispatcher. +func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { + //trace("yaml_parser_state_machine", "state:", parser.state.String()) + + switch parser.state { + case yaml_PARSE_STREAM_START_STATE: + return yaml_parser_parse_stream_start(parser, event) + + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, true) + + case yaml_PARSE_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, false) + + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return yaml_parser_parse_document_content(parser, event) + + case yaml_PARSE_DOCUMENT_END_STATE: + return yaml_parser_parse_document_end(parser, event) + + case yaml_PARSE_BLOCK_NODE_STATE: + return yaml_parser_parse_node(parser, event, true, false) + + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return yaml_parser_parse_node(parser, event, true, true) + + case yaml_PARSE_FLOW_NODE_STATE: + return yaml_parser_parse_node(parser, event, false, false) + + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, true) + + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, false) + + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_indentless_sequence_entry(parser, event) + + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, true) + + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, false) + + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return yaml_parser_parse_block_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, true) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, false) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) + + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, true) + + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, true) + + default: + panic("invalid parser state") + } +} + +// Parse the production: +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// ************ +func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_STREAM_START_TOKEN { + return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) + } + parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + encoding: token.encoding, + } + skip_token(parser) + return true +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// * +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// ************************* +func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { + + token := peek_token(parser) + if token == nil { + return false + } + + // Parse extra document end indicators. + if !implicit { + for token.typ == yaml_DOCUMENT_END_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && + token.typ != yaml_TAG_DIRECTIVE_TOKEN && + token.typ != yaml_DOCUMENT_START_TOKEN && + token.typ != yaml_STREAM_END_TOKEN { + // Parse an implicit document. + if !yaml_parser_process_directives(parser, nil, nil) { + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_BLOCK_NODE_STATE + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + } else if token.typ != yaml_STREAM_END_TOKEN { + // Parse an explicit document. + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + start_mark := token.start_mark + if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { + return false + } + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_DOCUMENT_START_TOKEN { + yaml_parser_set_parser_error(parser, + "did not find expected ", token.start_mark) + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE + end_mark := token.end_mark + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: false, + } + skip_token(parser) + + } else { + // Parse the stream end. + parser.state = yaml_PARSE_END_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + } + + return true +} + +// Parse the productions: +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** +// +func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || + token.typ == yaml_TAG_DIRECTIVE_TOKEN || + token.typ == yaml_DOCUMENT_START_TOKEN || + token.typ == yaml_DOCUMENT_END_TOKEN || + token.typ == yaml_STREAM_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + return yaml_parser_process_empty_scalar(parser, event, + token.start_mark) + } + return yaml_parser_parse_node(parser, event, true, false) +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// ************* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// +func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + start_mark := token.start_mark + end_mark := token.start_mark + + implicit := true + if token.typ == yaml_DOCUMENT_END_TOKEN { + end_mark = token.end_mark + skip_token(parser) + implicit = false + } + + parser.tag_directives = parser.tag_directives[:0] + + parser.state = yaml_PARSE_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + start_mark: start_mark, + end_mark: end_mark, + implicit: implicit, + } + return true +} + +// Parse the productions: +// block_node_or_indentless_sequence ::= +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * +// block_node ::= ALIAS +// ***** +// | properties block_content? +// ********** * +// | block_content +// * +// flow_node ::= ALIAS +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// ************************* +// block_content ::= block_collection | flow_collection | SCALAR +// ****** +// flow_content ::= flow_collection | SCALAR +// ****** +func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { + //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_ALIAS_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + anchor: token.value, + } + skip_token(parser) + return true + } + + start_mark := token.start_mark + end_mark := token.start_mark + + var tag_token bool + var tag_handle, tag_suffix, anchor []byte + var tag_mark yaml_mark_t + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + start_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } else if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + start_mark = token.start_mark + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + var tag []byte + if tag_token { + if len(tag_handle) == 0 { + tag = tag_suffix + tag_suffix = nil + } else { + for i := range parser.tag_directives { + if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { + tag = append([]byte(nil), parser.tag_directives[i].prefix...) + tag = append(tag, tag_suffix...) + break + } + } + if len(tag) == 0 { + yaml_parser_set_parser_error_context(parser, + "while parsing a node", start_mark, + "found undefined tag handle", tag_mark) + return false + } + } + } + + implicit := len(tag) == 0 + if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_SCALAR_TOKEN { + var plain_implicit, quoted_implicit bool + end_mark = token.end_mark + if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { + plain_implicit = true + } else if len(tag) == 0 { + quoted_implicit = true + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + value: token.value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(token.style), + } + skip_token(parser) + return true + } + if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { + // [Go] Some of the events below can be merged as they differ only on style. + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_FLOW_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), + } + return true + } + if len(anchor) > 0 || len(tag) > 0 { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + quoted_implicit: false, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true + } + + context := "while parsing a flow node" + if block { + context = "while parsing a block node" + } + yaml_parser_set_parser_error_context(parser, context, start_mark, + "did not find expected node content", token.start_mark) + return false +} + +// Parse the productions: +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* +// +func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } else { + parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } + if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block collection", context_mark, + "did not find expected '-' indicator", token.start_mark) +} + +// Parse the productions: +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// *********** * +func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && + token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? + } + return true +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* +// +// BLOCK-END +// ********* +// +func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_KEY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } else { + parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } else if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block mapping", context_mark, + "did not find expected key", token.start_mark) +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +// +// +func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence ::= FLOW-SEQUENCE-START +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow sequence", context_mark, + "did not find expected ',' or ']'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + implicit: true, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + skip_token(parser) + return true + } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true +} + +// +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + mark := token.end_mark + skip_token(parser) + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? + } + return true +} + +// Parse the productions: +// flow_mapping ::= FLOW-MAPPING-START +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * *** * +// +func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow mapping", context_mark, + "did not find expected ',' or '}'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } else { + parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true +} + +// Parse the productions: +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * ***** * +// +func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { + token := peek_token(parser) + if token == nil { + return false + } + if empty { + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Generate an empty scalar event. +func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: mark, + end_mark: mark, + value: nil, // Empty + implicit: true, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true +} + +var default_tag_directives = []yaml_tag_directive_t{ + {[]byte("!"), []byte("!")}, + {[]byte("!!"), []byte("tag:yaml.org,2002:")}, +} + +// Parse directives. +func yaml_parser_process_directives(parser *yaml_parser_t, + version_directive_ref **yaml_version_directive_t, + tag_directives_ref *[]yaml_tag_directive_t) bool { + + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + + token := peek_token(parser) + if token == nil { + return false + } + + for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { + if version_directive != nil { + yaml_parser_set_parser_error(parser, + "found duplicate %YAML directive", token.start_mark) + return false + } + if token.major != 1 || token.minor != 1 { + yaml_parser_set_parser_error(parser, + "found incompatible YAML document", token.start_mark) + return false + } + version_directive = &yaml_version_directive_t{ + major: token.major, + minor: token.minor, + } + } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { + value := yaml_tag_directive_t{ + handle: token.value, + prefix: token.prefix, + } + if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { + return false + } + tag_directives = append(tag_directives, value) + } + + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + + for i := range default_tag_directives { + if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { + return false + } + } + + if version_directive_ref != nil { + *version_directive_ref = version_directive + } + if tag_directives_ref != nil { + *tag_directives_ref = tag_directives + } + return true +} + +// Append a tag directive to the directives stack. +func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { + for i := range parser.tag_directives { + if bytes.Equal(value.handle, parser.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) + } + } + + // [Go] I suspect the copy is unnecessary. This was likely done + // because there was no way to track ownership of the data. + value_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(value_copy.handle, value.handle) + copy(value_copy.prefix, value.prefix) + parser.tag_directives = append(parser.tag_directives, value_copy) + return true +} diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go new file mode 100644 index 0000000..7c1f5fa --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/readerc.go @@ -0,0 +1,412 @@ +package yaml + +import ( + "io" +) + +// Set the reader error and return 0. +func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { + parser.error = yaml_READER_ERROR + parser.problem = problem + parser.problem_offset = offset + parser.problem_value = value + return false +} + +// Byte order marks. +const ( + bom_UTF8 = "\xef\xbb\xbf" + bom_UTF16LE = "\xff\xfe" + bom_UTF16BE = "\xfe\xff" +) + +// Determine the input stream encoding by checking the BOM symbol. If no BOM is +// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. +func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { + // Ensure that we had enough bytes in the raw buffer. + for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { + if !yaml_parser_update_raw_buffer(parser) { + return false + } + } + + // Determine the encoding. + buf := parser.raw_buffer + pos := parser.raw_buffer_pos + avail := len(buf) - pos + if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { + parser.encoding = yaml_UTF16LE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { + parser.encoding = yaml_UTF16BE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { + parser.encoding = yaml_UTF8_ENCODING + parser.raw_buffer_pos += 3 + parser.offset += 3 + } else { + parser.encoding = yaml_UTF8_ENCODING + } + return true +} + +// Update the raw buffer. +func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { + size_read := 0 + + // Return if the raw buffer is full. + if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { + return true + } + + // Return on EOF. + if parser.eof { + return true + } + + // Move the remaining bytes in the raw buffer to the beginning. + if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { + copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) + } + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] + parser.raw_buffer_pos = 0 + + // Call the read handler to fill the buffer. + size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] + if err == io.EOF { + parser.eof = true + } else if err != nil { + return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) + } + return true +} + +// Ensure that the buffer contains at least `length` characters. +// Return true on success, false on failure. +// +// The length is supposed to be significantly less that the buffer size. +func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { + if parser.read_handler == nil { + panic("read handler must be set") + } + + // [Go] This function was changed to guarantee the requested length size at EOF. + // The fact we need to do this is pretty awful, but the description above implies + // for that to be the case, and there are tests + + // If the EOF flag is set and the raw buffer is empty, do nothing. + if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { + // [Go] ACTUALLY! Read the documentation of this function above. + // This is just broken. To return true, we need to have the + // given length in the buffer. Not doing that means every single + // check that calls this function to make sure the buffer has a + // given length is Go) panicking; or C) accessing invalid memory. + //return true + } + + // Return if the buffer contains enough characters. + if parser.unread >= length { + return true + } + + // Determine the input encoding if it is not known yet. + if parser.encoding == yaml_ANY_ENCODING { + if !yaml_parser_determine_encoding(parser) { + return false + } + } + + // Move the unread characters to the beginning of the buffer. + buffer_len := len(parser.buffer) + if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { + copy(parser.buffer, parser.buffer[parser.buffer_pos:]) + buffer_len -= parser.buffer_pos + parser.buffer_pos = 0 + } else if parser.buffer_pos == buffer_len { + buffer_len = 0 + parser.buffer_pos = 0 + } + + // Open the whole buffer for writing, and cut it before returning. + parser.buffer = parser.buffer[:cap(parser.buffer)] + + // Fill the buffer until it has enough characters. + first := true + for parser.unread < length { + + // Fill the raw buffer if necessary. + if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { + if !yaml_parser_update_raw_buffer(parser) { + parser.buffer = parser.buffer[:buffer_len] + return false + } + } + first = false + + // Decode the raw buffer. + inner: + for parser.raw_buffer_pos != len(parser.raw_buffer) { + var value rune + var width int + + raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos + + // Decode the next character. + switch parser.encoding { + case yaml_UTF8_ENCODING: + // Decode a UTF-8 character. Check RFC 3629 + // (http://www.ietf.org/rfc/rfc3629.txt) for more details. + // + // The following table (taken from the RFC) is used for + // decoding. + // + // Char. number range | UTF-8 octet sequence + // (hexadecimal) | (binary) + // --------------------+------------------------------------ + // 0000 0000-0000 007F | 0xxxxxxx + // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + // + // Additionally, the characters in the range 0xD800-0xDFFF + // are prohibited as they are reserved for use with UTF-16 + // surrogate pairs. + + // Determine the length of the UTF-8 sequence. + octet := parser.raw_buffer[parser.raw_buffer_pos] + switch { + case octet&0x80 == 0x00: + width = 1 + case octet&0xE0 == 0xC0: + width = 2 + case octet&0xF0 == 0xE0: + width = 3 + case octet&0xF8 == 0xF0: + width = 4 + default: + // The leading octet is invalid. + return yaml_parser_set_reader_error(parser, + "invalid leading UTF-8 octet", + parser.offset, int(octet)) + } + + // Check if the raw buffer contains an incomplete character. + if width > raw_unread { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-8 octet sequence", + parser.offset, -1) + } + break inner + } + + // Decode the leading octet. + switch { + case octet&0x80 == 0x00: + value = rune(octet & 0x7F) + case octet&0xE0 == 0xC0: + value = rune(octet & 0x1F) + case octet&0xF0 == 0xE0: + value = rune(octet & 0x0F) + case octet&0xF8 == 0xF0: + value = rune(octet & 0x07) + default: + value = 0 + } + + // Check and decode the trailing octets. + for k := 1; k < width; k++ { + octet = parser.raw_buffer[parser.raw_buffer_pos+k] + + // Check if the octet is valid. + if (octet & 0xC0) != 0x80 { + return yaml_parser_set_reader_error(parser, + "invalid trailing UTF-8 octet", + parser.offset+k, int(octet)) + } + + // Decode the octet. + value = (value << 6) + rune(octet&0x3F) + } + + // Check the length of the sequence against the value. + switch { + case width == 1: + case width == 2 && value >= 0x80: + case width == 3 && value >= 0x800: + case width == 4 && value >= 0x10000: + default: + return yaml_parser_set_reader_error(parser, + "invalid length of a UTF-8 sequence", + parser.offset, -1) + } + + // Check the range of the value. + if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { + return yaml_parser_set_reader_error(parser, + "invalid Unicode character", + parser.offset, int(value)) + } + + case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: + var low, high int + if parser.encoding == yaml_UTF16LE_ENCODING { + low, high = 0, 1 + } else { + low, high = 1, 0 + } + + // The UTF-16 encoding is not as simple as one might + // naively think. Check RFC 2781 + // (http://www.ietf.org/rfc/rfc2781.txt). + // + // Normally, two subsequent bytes describe a Unicode + // character. However a special technique (called a + // surrogate pair) is used for specifying character + // values larger than 0xFFFF. + // + // A surrogate pair consists of two pseudo-characters: + // high surrogate area (0xD800-0xDBFF) + // low surrogate area (0xDC00-0xDFFF) + // + // The following formulas are used for decoding + // and encoding characters using surrogate pairs: + // + // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) + // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) + // W1 = 110110yyyyyyyyyy + // W2 = 110111xxxxxxxxxx + // + // where U is the character value, W1 is the high surrogate + // area, W2 is the low surrogate area. + + // Check for incomplete UTF-16 character. + if raw_unread < 2 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 character", + parser.offset, -1) + } + break inner + } + + // Get the character. + value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) + + // Check for unexpected low surrogate area. + if value&0xFC00 == 0xDC00 { + return yaml_parser_set_reader_error(parser, + "unexpected low surrogate area", + parser.offset, int(value)) + } + + // Check for a high surrogate area. + if value&0xFC00 == 0xD800 { + width = 4 + + // Check for incomplete surrogate pair. + if raw_unread < 4 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 surrogate pair", + parser.offset, -1) + } + break inner + } + + // Get the next character. + value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) + + // Check for a low surrogate area. + if value2&0xFC00 != 0xDC00 { + return yaml_parser_set_reader_error(parser, + "expected low surrogate area", + parser.offset+2, int(value2)) + } + + // Generate the value of the surrogate pair. + value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) + } else { + width = 2 + } + + default: + panic("impossible") + } + + // Check if the character is in the allowed range: + // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) + // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) + // | [#x10000-#x10FFFF] (32 bit) + switch { + case value == 0x09: + case value == 0x0A: + case value == 0x0D: + case value >= 0x20 && value <= 0x7E: + case value == 0x85: + case value >= 0xA0 && value <= 0xD7FF: + case value >= 0xE000 && value <= 0xFFFD: + case value >= 0x10000 && value <= 0x10FFFF: + default: + return yaml_parser_set_reader_error(parser, + "control characters are not allowed", + parser.offset, int(value)) + } + + // Move the raw pointers. + parser.raw_buffer_pos += width + parser.offset += width + + // Finally put the character into the buffer. + if value <= 0x7F { + // 0000 0000-0000 007F . 0xxxxxxx + parser.buffer[buffer_len+0] = byte(value) + buffer_len += 1 + } else if value <= 0x7FF { + // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) + parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) + buffer_len += 2 + } else if value <= 0xFFFF { + // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) + buffer_len += 3 + } else { + // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) + buffer_len += 4 + } + + parser.unread++ + } + + // On EOF, put NUL into the buffer and return. + if parser.eof { + parser.buffer[buffer_len] = 0 + buffer_len++ + parser.unread++ + break + } + } + // [Go] Read the documentation of this function above. To return true, + // we need to have the given length in the buffer. Not doing that means + // every single check that calls this function to make sure the buffer + // has a given length is Go) panicking; or C) accessing invalid memory. + // This happens here due to the EOF above breaking early. + for buffer_len < length { + parser.buffer[buffer_len] = 0 + buffer_len++ + } + parser.buffer = parser.buffer[:buffer_len] + return true +} diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go new file mode 100644 index 0000000..6c151db --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/resolve.go @@ -0,0 +1,258 @@ +package yaml + +import ( + "encoding/base64" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +type resolveMapItem struct { + value interface{} + tag string +} + +var resolveTable = make([]byte, 256) +var resolveMap = make(map[string]resolveMapItem) + +func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) + + var resolveMapList = []struct { + v interface{} + tag string + l []string + }{ + {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, + {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, + {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, + {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, + {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, + {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, + {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", yaml_MERGE_TAG, []string{"<<"}}, + } + + m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } +} + +const longTagPrefix = "tag:yaml.org,2002:" + +func shortTag(tag string) string { + // TODO This can easily be made faster and produce less garbage. + if strings.HasPrefix(tag, longTagPrefix) { + return "!!" + tag[len(longTagPrefix):] + } + return tag +} + +func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + return longTagPrefix + tag[2:] + } + return tag +} + +func resolvableTag(tag string) bool { + switch tag { + case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: + return true + } + return false +} + +var yamlStyleFloat = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+][0-9]+)?$`) + +func resolve(tag string, in string) (rtag string, out interface{}) { + if !resolvableTag(tag) { + return tag, in + } + + defer func() { + switch tag { + case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: + return + case yaml_FLOAT_TAG: + if rtag == yaml_INT_TAG { + switch v := out.(type) { + case int64: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + case int: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() + + // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } + + // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. + + switch hint { + case 'M': + // We've already checked the map above. + + case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + + case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == yaml_TIMESTAMP_TAG { + t, ok := parseTimestamp(in) + if ok { + return yaml_TIMESTAMP_TAG, t + } + } + + plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + } + default: + panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") + } + } + return yaml_STR_TAG, in +} + +// encodeBase64 encodes s as base64 that is broken up into multiple lines +// as appropriate for the resulting length. +func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) +} + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go new file mode 100644 index 0000000..077fd1d --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/scannerc.go @@ -0,0 +1,2696 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Introduction +// ************ +// +// The following notes assume that you are familiar with the YAML specification +// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in +// some cases we are less restrictive that it requires. +// +// The process of transforming a YAML stream into a sequence of events is +// divided on two steps: Scanning and Parsing. +// +// The Scanner transforms the input stream into a sequence of tokens, while the +// parser transform the sequence of tokens produced by the Scanner into a +// sequence of parsing events. +// +// The Scanner is rather clever and complicated. The Parser, on the contrary, +// is a straightforward implementation of a recursive-descendant parser (or, +// LL(1) parser, as it is usually called). +// +// Actually there are two issues of Scanning that might be called "clever", the +// rest is quite straightforward. The issues are "block collection start" and +// "simple keys". Both issues are explained below in details. +// +// Here the Scanning step is explained and implemented. We start with the list +// of all the tokens produced by the Scanner together with short descriptions. +// +// Now, tokens: +// +// STREAM-START(encoding) # The stream start. +// STREAM-END # The stream end. +// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. +// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. +// DOCUMENT-START # '---' +// DOCUMENT-END # '...' +// BLOCK-SEQUENCE-START # Indentation increase denoting a block +// BLOCK-MAPPING-START # sequence or a block mapping. +// BLOCK-END # Indentation decrease. +// FLOW-SEQUENCE-START # '[' +// FLOW-SEQUENCE-END # ']' +// BLOCK-SEQUENCE-START # '{' +// BLOCK-SEQUENCE-END # '}' +// BLOCK-ENTRY # '-' +// FLOW-ENTRY # ',' +// KEY # '?' or nothing (simple keys). +// VALUE # ':' +// ALIAS(anchor) # '*anchor' +// ANCHOR(anchor) # '&anchor' +// TAG(handle,suffix) # '!handle!suffix' +// SCALAR(value,style) # A scalar. +// +// The following two tokens are "virtual" tokens denoting the beginning and the +// end of the stream: +// +// STREAM-START(encoding) +// STREAM-END +// +// We pass the information about the input stream encoding with the +// STREAM-START token. +// +// The next two tokens are responsible for tags: +// +// VERSION-DIRECTIVE(major,minor) +// TAG-DIRECTIVE(handle,prefix) +// +// Example: +// +// %YAML 1.1 +// %TAG ! !foo +// %TAG !yaml! tag:yaml.org,2002: +// --- +// +// The correspoding sequence of tokens: +// +// STREAM-START(utf-8) +// VERSION-DIRECTIVE(1,1) +// TAG-DIRECTIVE("!","!foo") +// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") +// DOCUMENT-START +// STREAM-END +// +// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole +// line. +// +// The document start and end indicators are represented by: +// +// DOCUMENT-START +// DOCUMENT-END +// +// Note that if a YAML stream contains an implicit document (without '---' +// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be +// produced. +// +// In the following examples, we present whole documents together with the +// produced tokens. +// +// 1. An implicit document: +// +// 'a scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// STREAM-END +// +// 2. An explicit document: +// +// --- +// 'a scalar' +// ... +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// SCALAR("a scalar",single-quoted) +// DOCUMENT-END +// STREAM-END +// +// 3. Several documents in a stream: +// +// 'a scalar' +// --- +// 'another scalar' +// --- +// 'yet another scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// DOCUMENT-START +// SCALAR("another scalar",single-quoted) +// DOCUMENT-START +// SCALAR("yet another scalar",single-quoted) +// STREAM-END +// +// We have already introduced the SCALAR token above. The following tokens are +// used to describe aliases, anchors, tag, and scalars: +// +// ALIAS(anchor) +// ANCHOR(anchor) +// TAG(handle,suffix) +// SCALAR(value,style) +// +// The following series of examples illustrate the usage of these tokens: +// +// 1. A recursive sequence: +// +// &A [ *A ] +// +// Tokens: +// +// STREAM-START(utf-8) +// ANCHOR("A") +// FLOW-SEQUENCE-START +// ALIAS("A") +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A tagged scalar: +// +// !!float "3.14" # A good approximation. +// +// Tokens: +// +// STREAM-START(utf-8) +// TAG("!!","float") +// SCALAR("3.14",double-quoted) +// STREAM-END +// +// 3. Various scalar styles: +// +// --- # Implicit empty plain scalars do not produce tokens. +// --- a plain scalar +// --- 'a single-quoted scalar' +// --- "a double-quoted scalar" +// --- |- +// a literal scalar +// --- >- +// a folded +// scalar +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// DOCUMENT-START +// SCALAR("a plain scalar",plain) +// DOCUMENT-START +// SCALAR("a single-quoted scalar",single-quoted) +// DOCUMENT-START +// SCALAR("a double-quoted scalar",double-quoted) +// DOCUMENT-START +// SCALAR("a literal scalar",literal) +// DOCUMENT-START +// SCALAR("a folded scalar",folded) +// STREAM-END +// +// Now it's time to review collection-related tokens. We will start with +// flow collections: +// +// FLOW-SEQUENCE-START +// FLOW-SEQUENCE-END +// FLOW-MAPPING-START +// FLOW-MAPPING-END +// FLOW-ENTRY +// KEY +// VALUE +// +// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and +// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' +// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the +// indicators '?' and ':', which are used for denoting mapping keys and values, +// are represented by the KEY and VALUE tokens. +// +// The following examples show flow collections: +// +// 1. A flow sequence: +// +// [item 1, item 2, item 3] +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-SEQUENCE-START +// SCALAR("item 1",plain) +// FLOW-ENTRY +// SCALAR("item 2",plain) +// FLOW-ENTRY +// SCALAR("item 3",plain) +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A flow mapping: +// +// { +// a simple key: a value, # Note that the KEY token is produced. +// ? a complex key: another value, +// } +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// FLOW-ENTRY +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// FLOW-ENTRY +// FLOW-MAPPING-END +// STREAM-END +// +// A simple key is a key which is not denoted by the '?' indicator. Note that +// the Scanner still produce the KEY token whenever it encounters a simple key. +// +// For scanning block collections, the following tokens are used (note that we +// repeat KEY and VALUE here): +// +// BLOCK-SEQUENCE-START +// BLOCK-MAPPING-START +// BLOCK-END +// BLOCK-ENTRY +// KEY +// VALUE +// +// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation +// increase that precedes a block collection (cf. the INDENT token in Python). +// The token BLOCK-END denote indentation decrease that ends a block collection +// (cf. the DEDENT token in Python). However YAML has some syntax pecularities +// that makes detections of these tokens more complex. +// +// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators +// '-', '?', and ':' correspondingly. +// +// The following examples show how the tokens BLOCK-SEQUENCE-START, +// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: +// +// 1. Block sequences: +// +// - item 1 +// - item 2 +// - +// - item 3.1 +// - item 3.2 +// - +// key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 3.1",plain) +// BLOCK-ENTRY +// SCALAR("item 3.2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Block mappings: +// +// a simple key: a value # The KEY token is produced here. +// ? a complex key +// : another value +// a mapping: +// key 1: value 1 +// key 2: value 2 +// a sequence: +// - item 1 +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// KEY +// SCALAR("a mapping",plain) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML does not always require to start a new block collection from a new +// line. If the current line contains only '-', '?', and ':' indicators, a new +// block collection may start at the current line. The following examples +// illustrate this case: +// +// 1. Collections in a sequence: +// +// - - item 1 +// - item 2 +// - key 1: value 1 +// key 2: value 2 +// - ? complex key +// : complex value +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("complex key") +// VALUE +// SCALAR("complex value") +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Collections in a mapping: +// +// ? a sequence +// : - item 1 +// - item 2 +// ? a mapping +// : key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// KEY +// SCALAR("a mapping",plain) +// VALUE +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML also permits non-indented sequences if they are included into a block +// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: +// +// key: +// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key",plain) +// VALUE +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// + +// Ensure that the buffer contains the required number of characters. +// Return true on success, false on failure (reader error or memory error). +func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) +} + +// Advance the buffer pointer. +func skip(parser *yaml_parser_t) { + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) +} + +func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + } +} + +// Copy a character to a string buffer and advance pointers. +func read(parser *yaml_parser_t, s []byte) []byte { + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s +} + +// Copy a line break character to a string buffer and advance pointers. +func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + return s +} + +// Get the next token. +func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? + + // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } + + // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } + + // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false + + if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true +} + +// Set the scanner error and return false. +func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false +} + +func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) +} + +func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } +} + +// Ensure that the tokens queue contains at least one token which can be +// returned to the Parser. +func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + // Check if we really need to fetch more tokens. + need_more_tokens := false + + if parser.tokens_head == len(parser.tokens) { + // Queue is empty. + need_more_tokens = true + } else { + // Check if any potential simple key may occupy the head position. + if !yaml_parser_stale_simple_keys(parser) { + return false + } + + for i := range parser.simple_keys { + simple_key := &parser.simple_keys[i] + if simple_key.possible && simple_key.token_number == parser.tokens_parsed { + need_more_tokens = true + break + } + } + } + + // We are finished. + if !need_more_tokens { + break + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } + + parser.token_available = true + return true +} + +// The dispatcher for token fetchers. +func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } + + // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } + + // Remove obsolete potential simple keys. + if !yaml_parser_stale_simple_keys(parser) { + return false + } + + // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column) { + return false + } + + // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } + + // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } + + buf := parser.buffer + pos := parser.buffer_pos + + // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } + + // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } + + // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } + + // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } + + // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } + + // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } + + // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } + + // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } + + // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } + + // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } + + // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } + + // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } + + // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } + + // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } + + // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } + + // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } + + // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } + + // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } + + // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") +} + +// Check the list of potential simple keys and remove the positions that +// cannot contain simple keys anymore. +func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool { + // Check for a potential simple key for each flow level. + for i := range parser.simple_keys { + simple_key := &parser.simple_keys[i] + + // The specification requires that a simple key + // + // - is limited to a single line, + // - is shorter than 1024 characters. + if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) { + + // Check if the potential simple key to be removed is required. + if simple_key.required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + } + } + return true +} + +// Check if a simple key may start at the current position and add it if +// needed. +func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. + + required := parser.flow_level == 0 && parser.indent == parser.mark.column + + // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ + possible: true, + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + } + simple_key.mark = parser.mark + + if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + } + return true +} + +// Remove a potential simple key at the current flow level. +func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + return true +} + +// Increase the flow level and resize the simple key list if needed. +func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + + // Increase the flow level. + parser.flow_level++ + return true +} + +// Decrease the flow level. +func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1] + } + return true +} + +// Push the current indentation level to the stack and set the new level +// the current column is greater than the indentation level. In this case, +// append or insert the specified token into the token queue. +func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + + // Create a token and insert it into the queue. + token := yaml_token_t{ + typ: typ, + start_mark: mark, + end_mark: mark, + } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true +} + +// Pop indentation levels from the indents stack until the current level +// becomes less or equal to the column. For each indentation level, append +// the BLOCK-END token. +func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + // Loop through the indentation levels in the stack. + for parser.indent > column { + // Create a token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + + // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true +} + +// Initialize the scanner and produce the STREAM-START token. +func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { + + // Set the initial indentation. + parser.indent = -1 + + // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + + // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true + + // We have started. + parser.stream_start_produced = true + + // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + encoding: parser.encoding, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the STREAM-END token and shut down the scanner. +func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { + + // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } + + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. +func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the DOCUMENT-START or DOCUMENT-END token. +func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Consume the token. + start_mark := parser.mark + + skip(parser) + skip(parser) + skip(parser) + + end_mark := parser.mark + + // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. +func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } + + // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. +func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } + + // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false + + // Consume the token. + + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-ENTRY token. +func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after ','. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the BLOCK-ENTRY token. +func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '-'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the KEY token. +func yaml_parser_fetch_key(parser *yaml_parser_t) bool { + + // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the KEY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the VALUE token. +func yaml_parser_fetch_value(parser *yaml_parser_t) bool { + + simple_key := &parser.simple_keys[len(parser.simple_keys)-1] + + // Have we found a simple key? + if simple_key.possible { + // Create the KEY token and insert it into the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, + end_mark: simple_key.mark, + } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) + + // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } + + // Remove the simple key. + simple_key.possible = false + + // A simple key cannot follow another simple key. + parser.simple_key_allowed = false + + } else { + // The ':' indicator follows a complex key. + + // In the block context, extra checks are required. + if parser.flow_level == 0 { + + // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } + + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the VALUE token and append it to the queue. + token := yaml_token_t{ + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the ALIAS or ANCHOR token. +func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false + + // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the TAG token. +func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a tag. + parser.simple_key_allowed = false + + // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. +func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // A simple key may follow a block scalar. + parser.simple_key_allowed = true + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. +func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,plain) token. +func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Eat whitespaces and comments until the next token is found. +func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { + + // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } + + // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + + // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } + + return true +} + +// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) + + // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } + + // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark + + // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + major: major, + minor: minor, + } + + // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark + + // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + prefix: prefix, + } + + // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } + + // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + return true +} + +// Scan the directive name. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ +// +func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } + + // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true +} + +// Scan the value of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^ +func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } + + // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } + + skip(parser) + + // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true +} + +const max_number_length = 2 + +// Scan the version number of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ +func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { + + // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true +} + +// Scan the value of a TAG-DIRECTIVE token. +// +// Scope: +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte + + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } + + // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } + + // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } + + // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } + + *handle = handle_value + *prefix = prefix_value + return true +} + +func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte + + // Eat the indicator character. + start_mark := parser.mark + skip(parser) + + // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + end_mark := parser.mark + + /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ + + if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } + + // Create a token. + *token = yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + value: s, + } + + return true +} + +/* + * Scan a TAG token. + */ + +func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte + + start_mark := parser.mark + + // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' + + // Eat '!<' + skip(parser) + skip(parser) + + // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + + // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } + + skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. + + // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } + + // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } + + // Set the handle to '!'. + handle = []byte{'!'} + + // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } + + // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } + + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_TAG_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + suffix: suffix, + } + return true +} + +// Scan a tag handle. +func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + + var s []byte + + // Copy the '!' character. + s = read(parser, s) + + // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } + + *handle = s + return true +} + +// Scan a tag. +func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 + + // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } + + // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } + + if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true +} + +// Decode an URI-escape sequence corresponding to a single UTF-8 character. +func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { + + // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + + if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } + + // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) + + // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } + + // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true +} + +// Scan a block scalar. +func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) + + // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + + // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + + // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } + + } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. + + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } + + // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + end_mark := parser.mark + + // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } + + // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + + // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. + + // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] + + // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] + + // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + leading_break = read_line(parser, leading_break) + + // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } + + // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_LITERAL_SCALAR_STYLE, + } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true +} + +// Scan indentation spaces and line breaks for a block scalar. Determine the +// indentation level if needed. +func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark + + // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } + + // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } + + // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } + + // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true +} + +// Scan a quoted scalar. +func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) + + // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } + + // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } + + // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) + + } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 + + // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } + + skip(parser) + skip(parser) + + // Consume an arbitrary escape code. + if code_length > 0 { + var value int + + // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } + + // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } + + // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } + + // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Eat the right quote. + skip(parser) + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true +} + +// Scan a plain scalar. +func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { + + var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 + + start_mark := parser.mark + end_mark := parser.mark + + // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } + + // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } + + // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { + + // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } + + // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Copy the character. + s = read(parser, s) + + end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } + + // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + + // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } + + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_PLAIN_SCALAR_STYLE, + } + + // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true +} diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go new file mode 100644 index 0000000..4c45e66 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/sorter.go @@ -0,0 +1,113 @@ +package yaml + +import ( + "reflect" + "unicode" +) + +type keyList []reflect.Value + +func (l keyList) Len() int { return len(l) } +func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + return bl + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) +} + +// keyFloat returns a float value for v if it is a number/bool +// and whether it is a number/bool or not. +func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false +} + +// numLess returns whether a < b. +// a and b must necessarily have the same kind. +func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") +} diff --git a/vendor/gopkg.in/yaml.v2/writerc.go b/vendor/gopkg.in/yaml.v2/writerc.go new file mode 100644 index 0000000..a2dde60 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/writerc.go @@ -0,0 +1,26 @@ +package yaml + +// Set the writer error and return false. +func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_WRITER_ERROR + emitter.problem = problem + return false +} + +// Flush the output buffer. +func yaml_emitter_flush(emitter *yaml_emitter_t) bool { + if emitter.write_handler == nil { + panic("write handler not set") + } + + // Check if the buffer is empty. + if emitter.buffer_pos == 0 { + return true + } + + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { + return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) + } + emitter.buffer_pos = 0 + return true +} diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go new file mode 100644 index 0000000..de85aa4 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/yaml.go @@ -0,0 +1,466 @@ +// Package yaml implements YAML support for the Go language. +// +// Source code and other details for the project are available at GitHub: +// +// https://github.com/go-yaml/yaml +// +package yaml + +import ( + "errors" + "fmt" + "io" + "reflect" + "strings" + "sync" +) + +// MapSlice encodes and decodes as a YAML map. +// The order of keys is preserved when encoding and decoding. +type MapSlice []MapItem + +// MapItem is an item in a MapSlice. +type MapItem struct { + Key, Value interface{} +} + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a YAML document. The UnmarshalYAML +// method receives a function that may be called to unmarshal the original +// YAML value into a field or variable. It is safe to call the unmarshal +// function parameter more than once if necessary. +type Unmarshaler interface { + UnmarshalYAML(unmarshal func(interface{}) error) error +} + +// The Marshaler interface may be implemented by types to customize their +// behavior when being marshaled into a YAML document. The returned value +// is marshaled in place of the original value implementing Marshaler. +// +// If an error is returned by MarshalYAML, the marshaling procedure stops +// and returns with the provided error. +type Marshaler interface { + MarshalYAML() (interface{}, error) +} + +// Unmarshal decodes the first document found within the in byte slice +// and assigns decoded values into the out value. +// +// Maps and pointers (to a struct, string, int, etc) are accepted as out +// values. If an internal pointer within a struct is not initialized, +// the yaml package will initialize it if necessary for unmarshalling +// the provided data. The out parameter must not be nil. +// +// The type of the decoded values should be compatible with the respective +// values in out. If one or more values cannot be decoded due to a type +// mismatches, decoding continues partially until the end of the YAML +// content, and a *yaml.TypeError is returned with details for all +// missed values. +// +// Struct fields are only unmarshalled if they are exported (have an +// upper case first letter), and are unmarshalled using the field name +// lowercased as the default key. Custom keys may be defined via the +// "yaml" name in the field tag: the content preceding the first comma +// is used as the key, and the following comma-separated options are +// used to tweak the marshalling process (see Marshal). +// Conflicting names result in a runtime error. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// +// See the documentation of Marshal for the format of tags and a list of +// supported tag options. +// +func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) +} + +// UnmarshalStrict is like Unmarshal except that any fields that are found +// in the data that do not have corresponding struct members, or mapping +// keys that are duplicates, will result in +// an error. +func UnmarshalStrict(in []byte, out interface{}) (err error) { + return unmarshal(in, out, true) +} + +// A Decorder reads and decodes YAML values from an input stream. +type Decoder struct { + strict bool + parser *parser +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// SetStrict sets whether strict decoding behaviour is enabled when +// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict. +func (dec *Decoder) SetStrict(strict bool) { + dec.strict = strict +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder(dec.strict) + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder(strict) + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Marshal serializes the value provided into a YAML document. The structure +// of the generated document will reflect the structure of the value itself. +// Maps and pointers (to struct, string, int, etc) are accepted as the in value. +// +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the +// default key. Custom keys may be defined via the "yaml" name in the field +// tag: the content preceding the first comma is used as the key, and the +// following comma-separated options are used to tweak the marshalling process. +// Conflicting names result in a runtime error. +// +// The field tag format accepted is: +// +// `(...) yaml:"[][,[,]]" (...)` +// +// The following flags are currently supported: +// +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be included if that method returns true. +// +// flow Marshal using a flow style (useful for structs, +// sequences and maps). +// +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. +// +// In addition, if the key is "-", the field is ignored. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// +func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return +} + +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + +func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } +} + +type yamlError struct { + err error +} + +func fail(err error) { + panic(yamlError{err}) +} + +func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) +} + +// A TypeError is returned by Unmarshal when one or more fields in +// the YAML document cannot be properly decoded into the requested +// types. When this error is returned, the value is still +// unmarshaled partially. +type TypeError struct { + Errors []string +} + +func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) +} + +// -------------------------------------------------------------------------- +// Maintain a mapping of keys to structure field indexes + +// The code in this section was copied from mgo/bson. + +// structInfo holds details for the serialization of fields of +// a given struct. +type structInfo struct { + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo + + // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int +} + +type fieldInfo struct { + Key string + Num int + OmitEmpty bool + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int + + // Inline holds the field index if the field is part of an inlined struct. + Inline []int +} + +var structMap = make(map[reflect.Type]*structInfo) +var fieldMapMutex sync.RWMutex + +func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } + + n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } + + info := fieldInfo{Num: i} + + tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } + + inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } + + if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("Multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct: + sinfo, err := getStructInfo(field.Type) + if err != nil { + return nil, err + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + default: + //return nil, errors.New("Option ,inline needs a struct value or map field") + return nil, errors.New("Option ,inline needs a struct value field") + } + continue + } + + if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } + + if _, found = fieldsMap[info.Key]; found { + msg := "Duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + + info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } + + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + } + + fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil +} + +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + +func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go new file mode 100644 index 0000000..e25cee5 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/yamlh.go @@ -0,0 +1,738 @@ +package yaml + +import ( + "fmt" + "io" +) + +// The version directive data. +type yaml_version_directive_t struct { + major int8 // The major version number. + minor int8 // The minor version number. +} + +// The tag directive data. +type yaml_tag_directive_t struct { + handle []byte // The tag handle. + prefix []byte // The tag prefix. +} + +type yaml_encoding_t int + +// The stream encoding. +const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota + + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. +) + +type yaml_break_t int + +// Line break types. +const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota + + yaml_CR_BREAK // Use CR for line breaks (Mac style). + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). +) + +type yaml_error_type_t int + +// Many bad things could happen with the parser and emitter. +const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota + + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + yaml_READER_ERROR // Cannot read or decode the input stream. + yaml_SCANNER_ERROR // Cannot scan the input stream. + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. + yaml_WRITER_ERROR // Cannot write to the output stream. + yaml_EMITTER_ERROR // Cannot emit a YAML stream. +) + +// The pointer position. +type yaml_mark_t struct { + index int // The position index. + line int // The position line. + column int // The position column. +} + +// Node Styles + +type yaml_style_t int8 + +type yaml_scalar_style_t yaml_style_t + +// Scalar styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota + + yaml_PLAIN_SCALAR_STYLE // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. +) + +type yaml_sequence_style_t yaml_style_t + +// Sequence styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota + + yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. +) + +type yaml_mapping_style_t yaml_style_t + +// Mapping styles. +const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota + + yaml_BLOCK_MAPPING_STYLE // The block mapping style. + yaml_FLOW_MAPPING_STYLE // The flow mapping style. +) + +// Tokens + +type yaml_token_type_t int + +// Token types. +const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota + + yaml_STREAM_START_TOKEN // A STREAM-START token. + yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + yaml_KEY_TOKEN // A KEY token. + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. +) + +func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" +} + +// The token structure. +type yaml_token_t struct { + // The token type. + typ yaml_token_type_t + + // The start/end of the token. + start_mark, end_mark yaml_mark_t + + // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t + + // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte + + // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte + + // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte + + // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t + + // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 +} + +// Events + +type yaml_event_type_t int8 + +// Event types. +const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota + + yaml_STREAM_START_EVENT // A STREAM-START event. + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + yaml_ALIAS_EVENT // An ALIAS event. + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + yaml_MAPPING_START_EVENT // A MAPPING-START event. + yaml_MAPPING_END_EVENT // A MAPPING-END event. +) + +var eventStrings = []string{ + yaml_NO_EVENT: "none", + yaml_STREAM_START_EVENT: "stream start", + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", + yaml_DOCUMENT_END_EVENT: "document end", + yaml_ALIAS_EVENT: "alias", + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", + yaml_SEQUENCE_END_EVENT: "sequence end", + yaml_MAPPING_START_EVENT: "mapping start", + yaml_MAPPING_END_EVENT: "mapping end", +} + +func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] +} + +// The event structure. +type yaml_event_t struct { + + // The event type. + typ yaml_event_type_t + + // The start and end of the event. + start_mark, end_mark yaml_mark_t + + // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t + + // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t + + // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t + + // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte + + // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte + + // The scalar value (for yaml_SCALAR_EVENT). + value []byte + + // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool + + // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool + + // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t +} + +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +// Nodes + +const ( + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. + + yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. + + // Not in original libyaml. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. +) + +type yaml_node_type_t int + +// Node types. +const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota + + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. + yaml_MAPPING_NODE // A mapping node. +) + +// An element of a sequence node. +type yaml_node_item_t int + +// An element of a mapping node. +type yaml_node_pair_t struct { + key int // The key of the element. + value int // The value of the element. +} + +// The node structure. +type yaml_node_t struct { + typ yaml_node_type_t // The node type. + tag []byte // The node tag. + + // The node data. + + // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { + value []byte // The scalar value. + length int // The length of the scalar value. + style yaml_scalar_style_t // The scalar style. + } + + // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { + items_data []yaml_node_item_t // The stack of sequence items. + style yaml_sequence_style_t // The sequence style. + } + + // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + pairs_start *yaml_node_pair_t // The beginning of the stack. + pairs_end *yaml_node_pair_t // The end of the stack. + pairs_top *yaml_node_pair_t // The top of the stack. + style yaml_mapping_style_t // The mapping style. + } + + start_mark yaml_mark_t // The beginning of the node. + end_mark yaml_mark_t // The end of the node. + +} + +// The document structure. +type yaml_document_t struct { + + // The document nodes. + nodes []yaml_node_t + + // The version directive. + version_directive *yaml_version_directive_t + + // The list of tag directives. + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. + tag_directives_end int // The end of the tag directives list. + + start_implicit int // Is the document start indicator implicit? + end_implicit int // Is the document end indicator implicit? + + // The start/end of the document. + start_mark, end_mark yaml_mark_t +} + +// The prototype of a read handler. +// +// The read handler is called when the parser needs to read more bytes from the +// source. The handler should write not more than size bytes to the buffer. +// The number of written bytes should be set to the size_read variable. +// +// [in,out] data A pointer to an application data specified by +// yaml_parser_set_input(). +// [out] buffer The buffer to write the data from the source. +// [in] size The size of the buffer. +// [out] size_read The actual number of bytes read from the source. +// +// On success, the handler should return 1. If the handler failed, +// the returned value should be 0. On EOF, the handler should set the +// size_read to 0 and return 1. +type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) + +// This structure holds information about a potential simple key. +type yaml_simple_key_t struct { + possible bool // Is a simple key possible? + required bool // Is a simple key required? + token_number int // The number of the token. + mark yaml_mark_t // The position mark. +} + +// The states of the parser. +type yaml_parser_state_t int + +const ( + yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota + + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + yaml_PARSE_END_STATE // Expect nothing. +) + +func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" +} + +// This structure holds aliases data. +type yaml_alias_data_t struct { + anchor []byte // The anchor. + index int // The node id. + mark yaml_mark_t // The anchor mark. +} + +// The parser structure. +// +// All members are internal. Manage the structure using the +// yaml_parser_ family of functions. +type yaml_parser_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + + problem string // Error description. + + // The byte about which the problem occurred. + problem_offset int + problem_value int + problem_mark yaml_mark_t + + // The error context. + context string + context_mark yaml_mark_t + + // Reader stuff + + read_handler yaml_read_handler_t // Read handler. + + input_reader io.Reader // File input data. + input []byte // String input data. + input_pos int + + eof bool // EOF flag + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + unread int // The number of unread characters in the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The input encoding. + + offset int // The offset of the current position (in bytes). + mark yaml_mark_t // The mark of the current position. + + // Scanner stuff + + stream_start_produced bool // Have we started to scan the input stream? + stream_end_produced bool // Have we reached the end of the input stream? + + flow_level int // The number of unclosed '[' and '{' indicators. + + tokens []yaml_token_t // The tokens queue. + tokens_head int // The head of the tokens queue. + tokens_parsed int // The number of tokens fetched from the queue. + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. + indents []int // The indentation levels stack. + + simple_key_allowed bool // May a simple key occur at the current position? + simple_keys []yaml_simple_key_t // The stack of simple keys. + + // Parser stuff + + state yaml_parser_state_t // The current parser state. + states []yaml_parser_state_t // The parser states stack. + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. + + // Dumper stuff + + aliases []yaml_alias_data_t // The alias data. + + document *yaml_document_t // The currently parsed document. +} + +// Emitter Definitions + +// The prototype of a write handler. +// +// The write handler is called when the emitter needs to flush the accumulated +// characters to the output. The handler should write @a size bytes of the +// @a buffer to the output. +// +// @param[in,out] data A pointer to an application data specified by +// yaml_emitter_set_output(). +// @param[in] buffer The buffer with bytes to be written. +// @param[in] size The size of the buffer. +// +// @returns On success, the handler should return @c 1. If the handler failed, +// the returned value should be @c 0. +// +type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error + +type yaml_emitter_state_t int + +// The emitter states. +const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota + + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + yaml_EMIT_END_STATE // Expect nothing. +) + +// The emitter structure. +// +// All members are internal. Manage the structure using the @c yaml_emitter_ +// family of functions. +type yaml_emitter_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + problem string // Error description. + + // Writer stuff + + write_handler yaml_write_handler_t // Write handler. + + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The stream encoding. + + // Emitter stuff + + canonical bool // If the output is in the canonical style? + best_indent int // The number of indentation spaces. + best_width int // The preferred width of the output lines. + unicode bool // Allow unescaped non-ASCII characters? + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. + states []yaml_emitter_state_t // The stack of states. + + events []yaml_event_t // The event queue. + events_head int // The head of the event queue. + + indents []int // The stack of indentation levels. + + tag_directives []yaml_tag_directive_t // The list of tag directives. + + indent int // The current indentation level. + + flow_level int // The current flow level. + + root_context bool // Is it the document root context? + sequence_context bool // Is it a sequence context? + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? + + line int // The current line. + column int // The current column. + whitespace bool // If the last character was a whitespace? + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? + + // Anchor analysis. + anchor_data struct { + anchor []byte // The anchor value. + alias bool // Is it an alias? + } + + // Tag analysis. + tag_data struct { + handle []byte // The tag handle. + suffix []byte // The tag suffix. + } + + // Scalar analysis. + scalar_data struct { + value []byte // The scalar value. + multiline bool // Does the scalar contain line breaks? + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + style yaml_scalar_style_t // The output style. + } + + // Dumper stuff + + opened bool // If the stream was already opened? + closed bool // If the stream was already closed? + + // The information associated with the document nodes. + anchors *struct { + references int // The number of references. + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } + + last_anchor_id int // The last assigned anchor id. + + document *yaml_document_t // The currently emitted document. +} diff --git a/vendor/gopkg.in/yaml.v2/yamlprivateh.go b/vendor/gopkg.in/yaml.v2/yamlprivateh.go new file mode 100644 index 0000000..8110ce3 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/yamlprivateh.go @@ -0,0 +1,173 @@ +package yaml + +const ( + // The size of the input raw buffer. + input_raw_buffer_size = 512 + + // The size of the input buffer. + // It should be possible to decode the whole raw buffer. + input_buffer_size = input_raw_buffer_size * 3 + + // The size of the output buffer. + output_buffer_size = 128 + + // The size of the output raw buffer. + // It should be possible to encode the whole output buffer. + output_raw_buffer_size = (output_buffer_size*2 + 2) + + // The size of other stacks and queues. + initial_stack_size = 16 + initial_queue_size = 16 + initial_string_size = 16 +) + +// Check if the character at the specified position is an alphabetical +// character, a digit, '_', or '-'. +func is_alpha(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' +} + +// Check if the character at the specified position is a digit. +func is_digit(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' +} + +// Get the value of a digit. +func as_digit(b []byte, i int) int { + return int(b[i]) - '0' +} + +// Check if the character at the specified position is a hex-digit. +func is_hex(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' +} + +// Get the value of a hex-digit. +func as_hex(b []byte, i int) int { + bi := b[i] + if bi >= 'A' && bi <= 'F' { + return int(bi) - 'A' + 10 + } + if bi >= 'a' && bi <= 'f' { + return int(bi) - 'a' + 10 + } + return int(bi) - '0' +} + +// Check if the character is ASCII. +func is_ascii(b []byte, i int) bool { + return b[i] <= 0x7F +} + +// Check if the character at the start of the buffer can be printed unescaped. +func is_printable(b []byte, i int) bool { + return ((b[i] == 0x0A) || // . == #x0A + (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E + (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF + (b[i] > 0xC2 && b[i] < 0xED) || + (b[i] == 0xED && b[i+1] < 0xA0) || + (b[i] == 0xEE) || + (b[i] == 0xEF && // #xE000 <= . <= #xFFFD + !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF + !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) +} + +// Check if the character at the specified position is NUL. +func is_z(b []byte, i int) bool { + return b[i] == 0x00 +} + +// Check if the beginning of the buffer is a BOM. +func is_bom(b []byte, i int) bool { + return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF +} + +// Check if the character at the specified position is space. +func is_space(b []byte, i int) bool { + return b[i] == ' ' +} + +// Check if the character at the specified position is tab. +func is_tab(b []byte, i int) bool { + return b[i] == '\t' +} + +// Check if the character at the specified position is blank (space or tab). +func is_blank(b []byte, i int) bool { + //return is_space(b, i) || is_tab(b, i) + return b[i] == ' ' || b[i] == '\t' +} + +// Check if the character at the specified position is a line break. +func is_break(b []byte, i int) bool { + return (b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) +} + +func is_crlf(b []byte, i int) bool { + return b[i] == '\r' && b[i+1] == '\n' +} + +// Check if the character is a line break or NUL. +func is_breakz(b []byte, i int) bool { + //return is_break(b, i) || is_z(b, i) + return ( // is_break: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + // is_z: + b[i] == 0) +} + +// Check if the character is a line break, space, or NUL. +func is_spacez(b []byte, i int) bool { + //return is_space(b, i) || is_breakz(b, i) + return ( // is_space: + b[i] == ' ' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Check if the character is a line break, space, tab, or NUL. +func is_blankz(b []byte, i int) bool { + //return is_blank(b, i) || is_breakz(b, i) + return ( // is_blank: + b[i] == ' ' || b[i] == '\t' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Determine the width of the character. +func width(b byte) int { + // Don't replace these by a switch without first + // confirming that it is being inlined. + if b&0x80 == 0x00 { + return 1 + } + if b&0xE0 == 0xC0 { + return 2 + } + if b&0xF0 == 0xE0 { + return 3 + } + if b&0xF8 == 0xF0 { + return 4 + } + return 0 + +}