diff --git a/client/accountTTL.go b/client/accountTTL.go new file mode 100644 index 0000000..39f3445 --- /dev/null +++ b/client/accountTTL.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetAccountTTL Returns the period of inactivity after which the account of the current user will automatically be deleted +func (client *Client) GetAccountTTL() (*tdlib.AccountTTL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getAccountTtl", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var accountTTL tdlib.AccountTTL + err = json.Unmarshal(result.Raw, &accountTTL) + return &accountTTL, err + +} diff --git a/client/animations.go b/client/animations.go new file mode 100644 index 0000000..36b4090 --- /dev/null +++ b/client/animations.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetSavedAnimations Returns saved animations +func (client *Client) GetSavedAnimations() (*tdlib.Animations, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSavedAnimations", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var animations tdlib.Animations + err = json.Unmarshal(result.Raw, &animations) + return &animations, err + +} diff --git a/client/authenticationCodeInfo.go b/client/authenticationCodeInfo.go new file mode 100644 index 0000000..6e22c81 --- /dev/null +++ b/client/authenticationCodeInfo.go @@ -0,0 +1,143 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 settings Settings for the authentication of the user's phone number +func (client *Client) ChangePhoneNumber(phoneNumber string, settings *tdlib.PhoneNumberAuthenticationSettings) (*tdlib.AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "changePhoneNumber", + "phone_number": phoneNumber, + "settings": settings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var authenticationCodeInfo tdlib.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 current user. Works only if the previously received authenticationCodeInfo next_code_type was not null and the server-specified timeout has passed +func (client *Client) ResendChangePhoneNumberCode() (*tdlib.AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resendChangePhoneNumberCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var authenticationCodeInfo tdlib.AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, 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 settings Settings for the authentication of the user's phone number +func (client *Client) SendPhoneNumberVerificationCode(phoneNumber string, settings *tdlib.PhoneNumberAuthenticationSettings) (*tdlib.AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendPhoneNumberVerificationCode", + "phone_number": phoneNumber, + "settings": settings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var authenticationCodeInfo tdlib.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() (*tdlib.AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resendPhoneNumberVerificationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var authenticationCodeInfo tdlib.AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// SendPhoneNumberConfirmationCode Sends phone number confirmation code to handle links of the type internalLinkTypePhoneNumberConfirmation +// @param hash Hash value from the link +// @param phoneNumber Phone number value from the link +// @param settings Settings for the authentication of the user's phone number +func (client *Client) SendPhoneNumberConfirmationCode(hash string, phoneNumber string, settings *tdlib.PhoneNumberAuthenticationSettings) (*tdlib.AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendPhoneNumberConfirmationCode", + "hash": hash, + "phone_number": phoneNumber, + "settings": settings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var authenticationCodeInfo tdlib.AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} + +// ResendPhoneNumberConfirmationCode Resends phone number confirmation code +func (client *Client) ResendPhoneNumberConfirmationCode() (*tdlib.AuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resendPhoneNumberConfirmationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var authenticationCodeInfo tdlib.AuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &authenticationCodeInfo) + return &authenticationCodeInfo, err + +} diff --git a/client/authorizationState.go b/client/authorizationState.go new file mode 100644 index 0000000..e1aed34 --- /dev/null +++ b/client/authorizationState.go @@ -0,0 +1,86 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetAuthorizationState Returns the current authorization state; this is an offline request. For informational purposes only. Use updateAuthorizationState instead to maintain the current authorization state. Can be called before initialization +func (client *Client) GetAuthorizationState() (tdlib.AuthorizationState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getAuthorizationState", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.AuthorizationStateEnum(result.Data["@type"].(string)) { + + case tdlib.AuthorizationStateWaitTdlibParametersType: + var authorizationState tdlib.AuthorizationStateWaitTdlibParameters + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateWaitEncryptionKeyType: + var authorizationState tdlib.AuthorizationStateWaitEncryptionKey + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateWaitPhoneNumberType: + var authorizationState tdlib.AuthorizationStateWaitPhoneNumber + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateWaitCodeType: + var authorizationState tdlib.AuthorizationStateWaitCode + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateWaitOtherDeviceConfirmationType: + var authorizationState tdlib.AuthorizationStateWaitOtherDeviceConfirmation + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateWaitRegistrationType: + var authorizationState tdlib.AuthorizationStateWaitRegistration + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateWaitPasswordType: + var authorizationState tdlib.AuthorizationStateWaitPassword + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateReadyType: + var authorizationState tdlib.AuthorizationStateReady + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateLoggingOutType: + var authorizationState tdlib.AuthorizationStateLoggingOut + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateClosingType: + var authorizationState tdlib.AuthorizationStateClosing + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + case tdlib.AuthorizationStateClosedType: + var authorizationState tdlib.AuthorizationStateClosed + err = json.Unmarshal(result.Raw, &authorizationState) + return &authorizationState, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/autoDownloadSettingsPresets.go b/client/autoDownloadSettingsPresets.go new file mode 100644 index 0000000..6a30c62 --- /dev/null +++ b/client/autoDownloadSettingsPresets.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetAutoDownloadSettingsPresets Returns auto-download settings presets for the current user +func (client *Client) GetAutoDownloadSettingsPresets() (*tdlib.AutoDownloadSettingsPresets, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getAutoDownloadSettingsPresets", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var autoDownloadSettingsPresets tdlib.AutoDownloadSettingsPresets + err = json.Unmarshal(result.Raw, &autoDownloadSettingsPresets) + return &autoDownloadSettingsPresets, err + +} diff --git a/client/background.go b/client/background.go new file mode 100644 index 0000000..92684c7 --- /dev/null +++ b/client/background.go @@ -0,0 +1,57 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// SearchBackground Searches for a background by its name +// @param name The name of the background +func (client *Client) SearchBackground(name string) (*tdlib.Background, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchBackground", + "name": name, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var background tdlib.Background + err = json.Unmarshal(result.Raw, &background) + return &background, err + +} + +// SetBackground Changes the background selected by the user; adds background to the list of installed backgrounds +// @param background The input background to use. Pass null to create a new filled backgrounds. Pass null to remove the current background +// @param typeParam Background type. Pass null to use default type of the remote background. Pass null to remove the current background +// @param forDarkTheme True, if the background is chosen for dark theme +func (client *Client) SetBackground(background tdlib.InputBackground, typeParam tdlib.BackgroundType, forDarkTheme bool) (*tdlib.Background, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setBackground", + "background": background, + "type": typeParam, + "for_dark_theme": forDarkTheme, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var backgroundDummy tdlib.Background + err = json.Unmarshal(result.Raw, &backgroundDummy) + return &backgroundDummy, err + +} diff --git a/client/backgrounds.go b/client/backgrounds.go new file mode 100644 index 0000000..6d6d936 --- /dev/null +++ b/client/backgrounds.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetBackgrounds Returns backgrounds installed by the user +// @param forDarkTheme True, if the backgrounds must be ordered for dark theme +func (client *Client) GetBackgrounds(forDarkTheme bool) (*tdlib.Backgrounds, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getBackgrounds", + "for_dark_theme": forDarkTheme, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var backgrounds tdlib.Backgrounds + err = json.Unmarshal(result.Raw, &backgrounds) + return &backgrounds, err + +} diff --git a/client/bankCardInfo.go b/client/bankCardInfo.go new file mode 100644 index 0000000..dbca1f1 --- /dev/null +++ b/client/bankCardInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetBankCardInfo Returns information about a bank card +// @param bankCardNumber The bank card number +func (client *Client) GetBankCardInfo(bankCardNumber string) (*tdlib.BankCardInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getBankCardInfo", + "bank_card_number": bankCardNumber, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var bankCardInfo tdlib.BankCardInfo + err = json.Unmarshal(result.Raw, &bankCardInfo) + return &bankCardInfo, err + +} diff --git a/client/basicGroup.go b/client/basicGroup.go new file mode 100644 index 0000000..9909b0e --- /dev/null +++ b/client/basicGroup.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 int64) (*tdlib.BasicGroup, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getBasicGroup", + "basic_group_id": basicGroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var basicGroupDummy tdlib.BasicGroup + err = json.Unmarshal(result.Raw, &basicGroupDummy) + return &basicGroupDummy, err + +} diff --git a/client/basicGroupFullInfo.go b/client/basicGroupFullInfo.go new file mode 100644 index 0000000..143f567 --- /dev/null +++ b/client/basicGroupFullInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetBasicGroupFullInfo Returns full information about a basic group by its identifier +// @param basicGroupID Basic group identifier +func (client *Client) GetBasicGroupFullInfo(basicGroupID int64) (*tdlib.BasicGroupFullInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getBasicGroupFullInfo", + "basic_group_id": basicGroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var basicGroupFullInfo tdlib.BasicGroupFullInfo + err = json.Unmarshal(result.Raw, &basicGroupFullInfo) + return &basicGroupFullInfo, err + +} diff --git a/client/botCommands.go b/client/botCommands.go new file mode 100644 index 0000000..096caab --- /dev/null +++ b/client/botCommands.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetCommands Returns the list of commands supported by the bot for the given user scope and language; for bots only +// @param scope The scope to which the commands are relevant +// @param languageCode A two-letter ISO 639-1 country code or an empty string +func (client *Client) GetCommands(scope tdlib.BotCommandScope, languageCode string) (*tdlib.BotCommands, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getCommands", + "scope": scope, + "language_code": languageCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var botCommands tdlib.BotCommands + err = json.Unmarshal(result.Raw, &botCommands) + return &botCommands, err + +} diff --git a/client/callID.go b/client/callID.go new file mode 100644 index 0000000..b2b165d --- /dev/null +++ b/client/callID.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// CreateCall Creates a new call +// @param userID Identifier of the user to be called +// @param protocol Description of the call protocols supported by the application +// @param isVideo True, if a video call needs to be created +func (client *Client) CreateCall(userID int64, protocol *tdlib.CallProtocol, isVideo bool) (*tdlib.CallID, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createCall", + "user_id": userID, + "protocol": protocol, + "is_video": isVideo, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var callID tdlib.CallID + err = json.Unmarshal(result.Raw, &callID) + return &callID, err + +} diff --git a/client/callbackQueryAnswer.go b/client/callbackQueryAnswer.go new file mode 100644 index 0000000..68d8648 --- /dev/null +++ b/client/callbackQueryAnswer.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 tdlib.CallbackQueryPayload) (*tdlib.CallbackQueryAnswer, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var callbackQueryAnswer tdlib.CallbackQueryAnswer + err = json.Unmarshal(result.Raw, &callbackQueryAnswer) + return &callbackQueryAnswer, err + +} diff --git a/client/canTransferOwnershipResult.go b/client/canTransferOwnershipResult.go new file mode 100644 index 0000000..42212d6 --- /dev/null +++ b/client/canTransferOwnershipResult.go @@ -0,0 +1,51 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// CanTransferOwnership Checks whether the current session can be used to transfer a chat ownership to another user +func (client *Client) CanTransferOwnership() (tdlib.CanTransferOwnershipResult, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "canTransferOwnership", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.CanTransferOwnershipResultEnum(result.Data["@type"].(string)) { + + case tdlib.CanTransferOwnershipResultOkType: + var canTransferOwnershipResult tdlib.CanTransferOwnershipResultOk + err = json.Unmarshal(result.Raw, &canTransferOwnershipResult) + return &canTransferOwnershipResult, err + + case tdlib.CanTransferOwnershipResultPasswordNeededType: + var canTransferOwnershipResult tdlib.CanTransferOwnershipResultPasswordNeeded + err = json.Unmarshal(result.Raw, &canTransferOwnershipResult) + return &canTransferOwnershipResult, err + + case tdlib.CanTransferOwnershipResultPasswordTooFreshType: + var canTransferOwnershipResult tdlib.CanTransferOwnershipResultPasswordTooFresh + err = json.Unmarshal(result.Raw, &canTransferOwnershipResult) + return &canTransferOwnershipResult, err + + case tdlib.CanTransferOwnershipResultSessionTooFreshType: + var canTransferOwnershipResult tdlib.CanTransferOwnershipResultSessionTooFresh + err = json.Unmarshal(result.Raw, &canTransferOwnershipResult) + return &canTransferOwnershipResult, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/chat.go b/client/chat.go new file mode 100644 index 0000000..a935f9a --- /dev/null +++ b/client/chat.go @@ -0,0 +1,267 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatDummy tdlib.Chat + err = json.Unmarshal(result.Raw, &chatDummy) + return &chatDummy, 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) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchPublicChat", + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, 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 int64, force bool) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createPrivateChat", + "user_id": userID, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.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 int64, force bool) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createBasicGroupChat", + "basic_group_id": basicGroupID, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.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 int64, force bool) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createSupergroupChat", + "supergroup_id": supergroupID, + "force": force, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.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) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createSecretChat", + "secret_chat_id": secretChatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatDummy tdlib.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-128 characters +func (client *Client) CreateNewBasicGroupChat(userIDs []int64, title string) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createNewBasicGroupChat", + "user_ids": userIDs, + "title": title, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.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-128 characters +// @param isChannel True, if a channel chat needs to be created +// @param description Chat description; 0-255 characters +// @param location Chat location if a location-based supergroup is being created +// @param forImport True, if the supergroup is created for importing messages using importMessage +func (client *Client) CreateNewSupergroupChat(title string, isChannel bool, description string, location *tdlib.ChatLocation, forImport bool) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createNewSupergroupChat", + "title": title, + "is_channel": isChannel, + "description": description, + "location": location, + "for_import": forImport, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.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 int64) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createNewSecretChat", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.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; requires creator privileges. Deactivates the original basic group +// @param chatID Identifier of the chat to upgrade +func (client *Client) UpgradeBasicGroupChatToSupergroupChat(chatID int64) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "upgradeBasicGroupChatToSupergroupChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatDummy tdlib.Chat + err = json.Unmarshal(result.Raw, &chatDummy) + return &chatDummy, err + +} + +// JoinChatByInviteLink Uses an invite link to add the current user to the chat if possible +// @param inviteLink Invite link to use +func (client *Client) JoinChatByInviteLink(inviteLink string) (*tdlib.Chat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "joinChatByInviteLink", + "invite_link": inviteLink, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chat tdlib.Chat + err = json.Unmarshal(result.Raw, &chat) + return &chat, err + +} diff --git a/client/chatAdministrators.go b/client/chatAdministrators.go new file mode 100644 index 0000000..8efbe7c --- /dev/null +++ b/client/chatAdministrators.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatAdministrators Returns a list of administrators of the chat with their custom titles +// @param chatID Chat identifier +func (client *Client) GetChatAdministrators(chatID int64) (*tdlib.ChatAdministrators, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatAdministrators", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatAdministrators tdlib.ChatAdministrators + err = json.Unmarshal(result.Raw, &chatAdministrators) + return &chatAdministrators, err + +} diff --git a/client/chatEvents.go b/client/chatEvents.go new file mode 100644 index 0000000..bbb2c3e --- /dev/null +++ b/client/chatEvents.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatEventLog Returns a list of service actions taken by chat members and administrators in the last 48 hours. Available only for 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 The 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 *tdlib.JSONInt64, limit int32, filters *tdlib.ChatEventLogFilters, userIDs []int64) (*tdlib.ChatEvents, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatEvents tdlib.ChatEvents + err = json.Unmarshal(result.Raw, &chatEvents) + return &chatEvents, err + +} diff --git a/client/chatFilter.go b/client/chatFilter.go new file mode 100644 index 0000000..03a1d7a --- /dev/null +++ b/client/chatFilter.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatFilter Returns information about a chat filter by its identifier +// @param chatFilterID Chat filter identifier +func (client *Client) GetChatFilter(chatFilterID int32) (*tdlib.ChatFilter, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatFilter", + "chat_filter_id": chatFilterID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatFilterDummy tdlib.ChatFilter + err = json.Unmarshal(result.Raw, &chatFilterDummy) + return &chatFilterDummy, err + +} diff --git a/client/chatFilterInfo.go b/client/chatFilterInfo.go new file mode 100644 index 0000000..d30c347 --- /dev/null +++ b/client/chatFilterInfo.go @@ -0,0 +1,55 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// CreateChatFilter Creates new chat filter. Returns information about the created chat filter +// @param filter Chat filter +func (client *Client) CreateChatFilter(filter *tdlib.ChatFilter) (*tdlib.ChatFilterInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createChatFilter", + "filter": filter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatFilterInfo tdlib.ChatFilterInfo + err = json.Unmarshal(result.Raw, &chatFilterInfo) + return &chatFilterInfo, err + +} + +// EditChatFilter Edits existing chat filter. Returns information about the edited chat filter +// @param chatFilterID Chat filter identifier +// @param filter The edited chat filter +func (client *Client) EditChatFilter(chatFilterID int32, filter *tdlib.ChatFilter) (*tdlib.ChatFilterInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "editChatFilter", + "chat_filter_id": chatFilterID, + "filter": filter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatFilterInfo tdlib.ChatFilterInfo + err = json.Unmarshal(result.Raw, &chatFilterInfo) + return &chatFilterInfo, err + +} diff --git a/client/chatInviteLink.go b/client/chatInviteLink.go new file mode 100644 index 0000000..1e69ce8 --- /dev/null +++ b/client/chatInviteLink.go @@ -0,0 +1,109 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// ReplacePrimaryChatInviteLink Replaces current primary invite link for a chat with a new primary invite link. Available for basic groups, supergroups, and channels. Requires administrator privileges and can_invite_users right +// @param chatID Chat identifier +func (client *Client) ReplacePrimaryChatInviteLink(chatID int64) (*tdlib.ChatInviteLink, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "replacePrimaryChatInviteLink", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLink tdlib.ChatInviteLink + err = json.Unmarshal(result.Raw, &chatInviteLink) + return &chatInviteLink, err + +} + +// CreateChatInviteLink Creates a new invite link for a chat. Available for basic groups, supergroups, and channels. Requires administrator privileges and can_invite_users right in the chat +// @param chatID Chat identifier +// @param expireDate Point in time (Unix timestamp) when the link will expire; pass 0 if never +// @param memberLimit The maximum number of chat members that can join the chat by the link simultaneously; 0-99999; pass 0 if not limited +func (client *Client) CreateChatInviteLink(chatID int64, expireDate int32, memberLimit int32) (*tdlib.ChatInviteLink, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createChatInviteLink", + "chat_id": chatID, + "expire_date": expireDate, + "member_limit": memberLimit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLink tdlib.ChatInviteLink + err = json.Unmarshal(result.Raw, &chatInviteLink) + return &chatInviteLink, err + +} + +// EditChatInviteLink Edits a non-primary invite link for a chat. Available for basic groups, supergroups, and channels. Requires administrator privileges and can_invite_users right in the chat for own links and owner privileges for other links +// @param chatID Chat identifier +// @param inviteLink Invite link to be edited +// @param expireDate Point in time (Unix timestamp) when the link will expire; pass 0 if never +// @param memberLimit The maximum number of chat members that can join the chat by the link simultaneously; 0-99999; pass 0 if not limited +func (client *Client) EditChatInviteLink(chatID int64, inviteLink string, expireDate int32, memberLimit int32) (*tdlib.ChatInviteLink, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "editChatInviteLink", + "chat_id": chatID, + "invite_link": inviteLink, + "expire_date": expireDate, + "member_limit": memberLimit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLink tdlib.ChatInviteLink + err = json.Unmarshal(result.Raw, &chatInviteLink) + return &chatInviteLink, err + +} + +// GetChatInviteLink Returns information about an invite link. Requires administrator privileges and can_invite_users right in the chat to get own links and owner privileges to get other links +// @param chatID Chat identifier +// @param inviteLink Invite link to get +func (client *Client) GetChatInviteLink(chatID int64, inviteLink string) (*tdlib.ChatInviteLink, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatInviteLink", + "chat_id": chatID, + "invite_link": inviteLink, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLink tdlib.ChatInviteLink + err = json.Unmarshal(result.Raw, &chatInviteLink) + return &chatInviteLink, err + +} diff --git a/client/chatInviteLinkCounts.go b/client/chatInviteLinkCounts.go new file mode 100644 index 0000000..c75026b --- /dev/null +++ b/client/chatInviteLinkCounts.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatInviteLinkCounts Returns list of chat administrators with number of their invite links. Requires owner privileges in the chat +// @param chatID Chat identifier +func (client *Client) GetChatInviteLinkCounts(chatID int64) (*tdlib.ChatInviteLinkCounts, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatInviteLinkCounts", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLinkCounts tdlib.ChatInviteLinkCounts + err = json.Unmarshal(result.Raw, &chatInviteLinkCounts) + return &chatInviteLinkCounts, err + +} diff --git a/client/chatInviteLinkInfo.go b/client/chatInviteLinkInfo.go new file mode 100644 index 0000000..7181dce --- /dev/null +++ b/client/chatInviteLinkInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 +func (client *Client) CheckChatInviteLink(inviteLink string) (*tdlib.ChatInviteLinkInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkChatInviteLink", + "invite_link": inviteLink, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLinkInfo tdlib.ChatInviteLinkInfo + err = json.Unmarshal(result.Raw, &chatInviteLinkInfo) + return &chatInviteLinkInfo, err + +} diff --git a/client/chatInviteLinkMembers.go b/client/chatInviteLinkMembers.go new file mode 100644 index 0000000..4ade547 --- /dev/null +++ b/client/chatInviteLinkMembers.go @@ -0,0 +1,37 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatInviteLinkMembers Returns chat members joined a chat by an invite link. Requires administrator privileges and can_invite_users right in the chat for own links and owner privileges for other links +// @param chatID Chat identifier +// @param inviteLink Invite link for which to return chat members +// @param offsetMember A chat member from which to return next chat members; use null to get results from the beginning +// @param limit The maximum number of chat members to return +func (client *Client) GetChatInviteLinkMembers(chatID int64, inviteLink string, offsetMember *tdlib.ChatInviteLinkMember, limit int32) (*tdlib.ChatInviteLinkMembers, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatInviteLinkMembers", + "chat_id": chatID, + "invite_link": inviteLink, + "offset_member": offsetMember, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLinkMembers tdlib.ChatInviteLinkMembers + err = json.Unmarshal(result.Raw, &chatInviteLinkMembers) + return &chatInviteLinkMembers, err + +} diff --git a/client/chatInviteLinks.go b/client/chatInviteLinks.go new file mode 100644 index 0000000..f8801a2 --- /dev/null +++ b/client/chatInviteLinks.go @@ -0,0 +1,65 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatInviteLinks Returns invite links for a chat created by specified administrator. Requires administrator privileges and can_invite_users right in the chat to get own links and owner privileges to get other links +// @param chatID Chat identifier +// @param creatorUserID User identifier of a chat administrator. Must be an identifier of the current user for non-owner +// @param isRevoked Pass true if revoked links needs to be returned instead of active or expired +// @param offsetDate Creation date of an invite link starting after which to return invite links; use 0 to get results from the beginning +// @param offsetInviteLink Invite link starting after which to return invite links; use empty string to get results from the beginning +// @param limit The maximum number of invite links to return +func (client *Client) GetChatInviteLinks(chatID int64, creatorUserID int64, isRevoked bool, offsetDate int32, offsetInviteLink string, limit int32) (*tdlib.ChatInviteLinks, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatInviteLinks", + "chat_id": chatID, + "creator_user_id": creatorUserID, + "is_revoked": isRevoked, + "offset_date": offsetDate, + "offset_invite_link": offsetInviteLink, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLinks tdlib.ChatInviteLinks + err = json.Unmarshal(result.Raw, &chatInviteLinks) + return &chatInviteLinks, err + +} + +// RevokeChatInviteLink Revokes invite link for a chat. Available for basic groups, supergroups, and channels. Requires administrator privileges and can_invite_users right in the chat for own links and owner privileges for other links. If a primary link is revoked, then additionally to the revoked link returns new primary link +// @param chatID Chat identifier +// @param inviteLink Invite link to be revoked +func (client *Client) RevokeChatInviteLink(chatID int64, inviteLink string) (*tdlib.ChatInviteLinks, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "revokeChatInviteLink", + "chat_id": chatID, + "invite_link": inviteLink, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatInviteLinks tdlib.ChatInviteLinks + err = json.Unmarshal(result.Raw, &chatInviteLinks) + return &chatInviteLinks, err + +} diff --git a/client/chatLists.go b/client/chatLists.go new file mode 100644 index 0000000..1691eec --- /dev/null +++ b/client/chatLists.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatListsToAddChat Returns chat lists to which the chat can be added. This is an offline request +// @param chatID Chat identifier +func (client *Client) GetChatListsToAddChat(chatID int64) (*tdlib.ChatLists, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatListsToAddChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatLists tdlib.ChatLists + err = json.Unmarshal(result.Raw, &chatLists) + return &chatLists, err + +} diff --git a/client/chatMember.go b/client/chatMember.go new file mode 100644 index 0000000..7b36c61 --- /dev/null +++ b/client/chatMember.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatMember Returns information about a single member of a chat +// @param chatID Chat identifier +// @param memberID Member identifier +func (client *Client) GetChatMember(chatID int64, memberID tdlib.MessageSender) (*tdlib.ChatMember, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatMember", + "chat_id": chatID, + "member_id": memberID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatMember tdlib.ChatMember + err = json.Unmarshal(result.Raw, &chatMember) + return &chatMember, err + +} diff --git a/client/chatMembers.go b/client/chatMembers.go new file mode 100644 index 0000000..8bdb2f8 --- /dev/null +++ b/client/chatMembers.go @@ -0,0 +1,65 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 tdlib.ChatMembersFilter) (*tdlib.ChatMembers, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatMembers tdlib.ChatMembers + err = json.Unmarshal(result.Raw, &chatMembers) + return &chatMembers, 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, supergroupMembersFilterRecent +// @param offset Number of users to skip +// @param limit The maximum number of users be returned; up to 200 +func (client *Client) GetSupergroupMembers(supergroupID int64, filter tdlib.SupergroupMembersFilter, offset int32, limit int32) (*tdlib.ChatMembers, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatMembers tdlib.ChatMembers + err = json.Unmarshal(result.Raw, &chatMembers) + return &chatMembers, err + +} diff --git a/client/chatPhotos.go b/client/chatPhotos.go new file mode 100644 index 0000000..e33b6c1 --- /dev/null +++ b/client/chatPhotos.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 The maximum number of photos to be returned; up to 100 +func (client *Client) GetUserProfilePhotos(userID int64, offset int32, limit int32) (*tdlib.ChatPhotos, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getUserProfilePhotos", + "user_id": userID, + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatPhotos tdlib.ChatPhotos + err = json.Unmarshal(result.Raw, &chatPhotos) + return &chatPhotos, err + +} diff --git a/client/chatStatistics.go b/client/chatStatistics.go new file mode 100644 index 0000000..ecd60e5 --- /dev/null +++ b/client/chatStatistics.go @@ -0,0 +1,45 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatStatistics Returns detailed statistics about a chat. Currently this method can be used only for supergroups and channels. Can be used only if SupergroupFullInfo.can_get_statistics == true +// @param chatID Chat identifier +// @param isDark Pass true if a dark theme is used by the application +func (client *Client) GetChatStatistics(chatID int64, isDark bool) (tdlib.ChatStatistics, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatStatistics", + "chat_id": chatID, + "is_dark": isDark, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.ChatStatisticsEnum(result.Data["@type"].(string)) { + + case tdlib.ChatStatisticsSupergroupType: + var chatStatistics tdlib.ChatStatisticsSupergroup + err = json.Unmarshal(result.Raw, &chatStatistics) + return &chatStatistics, err + + case tdlib.ChatStatisticsChannelType: + var chatStatistics tdlib.ChatStatisticsChannel + err = json.Unmarshal(result.Raw, &chatStatistics) + return &chatStatistics, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/chats.go b/client/chats.go new file mode 100644 index 0000000..e901d32 --- /dev/null +++ b/client/chats.go @@ -0,0 +1,261 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChats Returns an ordered list of chats from the beginning of a chat list. For informational purposes only. Use loadChats instead to maintain chat lists +// @param chatList The chat list in which to return chats +// @param limit The maximum number of chats to be returned +func (client *Client) GetChats(chatList tdlib.ChatList, limit int32) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChats", + "chat_list": chatList, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, 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) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchPublicChats", + "query": query, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.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 main chat list +// @param query Query to search for. If the query is empty, returns up to 50 recently found chats +// @param limit The maximum number of chats to be returned +func (client *Client) SearchChats(query string, limit int32) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchChats", + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.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 main chat list +// @param query Query to search for +// @param limit The maximum number of chats to be returned +func (client *Client) SearchChatsOnServer(query string, limit int32) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchChatsOnServer", + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.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 The maximum number of chats to be returned; up to 30 +func (client *Client) GetTopChats(category tdlib.TopChatCategory, limit int32) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getTopChats", + "category": category, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetRecentlyOpenedChats Returns recently opened chats, this is an offline request. Returns chats in the order of last opening +// @param limit The maximum number of chats to be returned +func (client *Client) GetRecentlyOpenedChats(limit int32) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRecentlyOpenedChats", + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetCreatedPublicChats Returns a list of public chats of the specified type, owned by the user +// @param typeParam Type of the public chats to return +func (client *Client) GetCreatedPublicChats(typeParam tdlib.PublicChatType) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getCreatedPublicChats", + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetSuitableDiscussionChats Returns a list of basic group and supergroup chats, which can be used as a discussion group for a channel. Returned basic group chats must be first upgraded to supergroups before they can be set as a discussion group. To set a returned supergroup as a discussion group, access to its old messages must be enabled using toggleSupergroupIsAllHistoryAvailable first +func (client *Client) GetSuitableDiscussionChats() (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSuitableDiscussionChats", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetInactiveSupergroupChats Returns a list of recently inactive supergroups and channels. Can be used when user reaches limit on the number of joined supergroups and channels and receives CHANNELS_TOO_MUCH error +func (client *Client) GetInactiveSupergroupChats() (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getInactiveSupergroupChats", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetGroupsInCommon Returns a list of common group 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 The maximum number of chats to be returned; up to 100 +func (client *Client) GetGroupsInCommon(userID int64, offsetChatID int64, limit int32) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} + +// GetChatNotificationSettingsExceptions Returns list of chats with non-default notification settings +// @param scope If specified, only chats from the specified scope will be returned +// @param compareSound If true, also chats with non-default sound will be returned +func (client *Client) GetChatNotificationSettingsExceptions(scope tdlib.NotificationSettingsScope, compareSound bool) (*tdlib.Chats, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatNotificationSettingsExceptions", + "scope": scope, + "compare_sound": compareSound, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chats tdlib.Chats + err = json.Unmarshal(result.Raw, &chats) + return &chats, err + +} diff --git a/client/chatsNearby.go b/client/chatsNearby.go new file mode 100644 index 0000000..04af8ab --- /dev/null +++ b/client/chatsNearby.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// SearchChatsNearby Returns a list of users and location-based supergroups nearby. The list of users nearby will be updated for 60 seconds after the request by the updates updateUsersNearby. The request should be sent again every 25 seconds with adjusted location to not miss new chats +// @param location Current user location +func (client *Client) SearchChatsNearby(location *tdlib.Location) (*tdlib.ChatsNearby, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchChatsNearby", + "location": location, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var chatsNearby tdlib.ChatsNearby + err = json.Unmarshal(result.Raw, &chatsNearby) + return &chatsNearby, err + +} diff --git a/client/checkChatUsernameResult.go b/client/checkChatUsernameResult.go new file mode 100644 index 0000000..5206f6d --- /dev/null +++ b/client/checkChatUsernameResult.go @@ -0,0 +1,60 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 the chat is being created +// @param username Username to be checked +func (client *Client) CheckChatUsername(chatID int64, username string) (tdlib.CheckChatUsernameResult, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkChatUsername", + "chat_id": chatID, + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.CheckChatUsernameResultEnum(result.Data["@type"].(string)) { + + case tdlib.CheckChatUsernameResultOkType: + var checkChatUsernameResult tdlib.CheckChatUsernameResultOk + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case tdlib.CheckChatUsernameResultUsernameInvalidType: + var checkChatUsernameResult tdlib.CheckChatUsernameResultUsernameInvalid + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case tdlib.CheckChatUsernameResultUsernameOccupiedType: + var checkChatUsernameResult tdlib.CheckChatUsernameResultUsernameOccupied + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case tdlib.CheckChatUsernameResultPublicChatsTooMuchType: + var checkChatUsernameResult tdlib.CheckChatUsernameResultPublicChatsTooMuch + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + case tdlib.CheckChatUsernameResultPublicGroupsUnavailableType: + var checkChatUsernameResult tdlib.CheckChatUsernameResultPublicGroupsUnavailable + err = json.Unmarshal(result.Raw, &checkChatUsernameResult) + return &checkChatUsernameResult, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/checkStickerSetNameResult.go b/client/checkStickerSetNameResult.go new file mode 100644 index 0000000..ba41499 --- /dev/null +++ b/client/checkStickerSetNameResult.go @@ -0,0 +1,48 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// CheckStickerSetName Checks whether a name can be used for a new sticker set +// @param name Name to be checked +func (client *Client) CheckStickerSetName(name string) (tdlib.CheckStickerSetNameResult, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkStickerSetName", + "name": name, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.CheckStickerSetNameResultEnum(result.Data["@type"].(string)) { + + case tdlib.CheckStickerSetNameResultOkType: + var checkStickerSetNameResult tdlib.CheckStickerSetNameResultOk + err = json.Unmarshal(result.Raw, &checkStickerSetNameResult) + return &checkStickerSetNameResult, err + + case tdlib.CheckStickerSetNameResultNameInvalidType: + var checkStickerSetNameResult tdlib.CheckStickerSetNameResultNameInvalid + err = json.Unmarshal(result.Raw, &checkStickerSetNameResult) + return &checkStickerSetNameResult, err + + case tdlib.CheckStickerSetNameResultNameOccupiedType: + var checkStickerSetNameResult tdlib.CheckStickerSetNameResultNameOccupied + err = json.Unmarshal(result.Raw, &checkStickerSetNameResult) + return &checkStickerSetNameResult, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/client.go b/client/client.go new file mode 100644 index 0000000..ca2676e --- /dev/null +++ b/client/client.go @@ -0,0 +1,377 @@ +package client + +//#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 -ltdapi -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 -ltdapi -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" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// EventFilterFunc used to filter out unwanted messages in receiver channels +type EventFilterFunc func(msg *tdlib.TdMessage) bool + +// EventReceiver used to retreive updates from tdlib to user +type EventReceiver struct { + Instance tdlib.TdMessage + Chan chan tdlib.TdMessage + FilterFunc EventFilterFunc +} + +// Client is the Telegram TdLib client +type Client struct { + Client unsafe.Pointer + Config Config + rawUpdates chan tdlib.UpdateMsg + receivers []EventReceiver + waiters map[string]chan tdlib.UpdateMsg + receiverLock *sync.Mutex + waitersLock *sync.RWMutex +} + +// 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.waitersLock = &sync.RWMutex{} + client.Config = config + client.waiters = make(map[string]chan tdlib.UpdateMsg) + + go func() { + for { + // get update + updateBytes := client.Receive(10) + var updateData tdlib.UpdateData + json.Unmarshal(updateBytes, &updateData) + + // does new update has @extra field? + if extra, hasExtra := updateData["@extra"].(string); hasExtra { + + client.waitersLock.RLock() + waiter, found := client.waiters[extra] + client.waitersLock.RUnlock() + + // trying to load update with this salt + if found { + // found? send it to waiter channel + waiter <- tdlib.UpdateMsg{Data: updateData, Raw: updateBytes} + + // trying to prevent memory leak + close(waiter) + } + } 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 <- tdlib.UpdateMsg{Data: updateData, Raw: updateBytes} + } + + client.receiverLock.Lock() + for _, receiver := range client.receivers { + if msgType == receiver.Instance.MessageType() { + newMsg := reflect.New(reflect.ValueOf(receiver.Instance).Elem().Type()).Interface().(tdlib.TdMessage) + + err := json.Unmarshal(updateBytes, &newMsg) + if err != nil { + fmt.Printf("Error unmarhaling to type %v", err) + } else { + 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 tdlib.UpdateMsg { + client.rawUpdates = make(chan tdlib.UpdateMsg, capacity) + return client.rawUpdates +} + +// AddEventReceiver adds a new receiver to be subscribed in receiver channels +// @param msgInstance what kind of message do you want to receive? +// @param +func (client *Client) AddEventReceiver(msgInstance tdlib.TdMessage, filterFunc EventFilterFunc, channelCapacity int) EventReceiver { + receiver := EventReceiver{ + Instance: msgInstance, + Chan: make(chan tdlib.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 tdlib.UpdateData: + jsonBytes, _ := json.Marshal(jsonQuery.(tdlib.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{}) tdlib.UpdateMsg { + var query *C.char + + switch jsonQuery.(type) { + case string: + query = C.CString(jsonQuery.(string)) + case tdlib.UpdateData: + jsonBytes, _ := json.Marshal(jsonQuery.(tdlib.UpdateData)) + query = C.CString(string(jsonBytes)) + } + + defer C.free(unsafe.Pointer(query)) + result := C.td_json_client_execute(client.Client, query) + + var update tdlib.UpdateData + json.Unmarshal([]byte(C.GoString(result)), &update) + return tdlib.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) { + bytes, _ := json.Marshal(tdlib.UpdateData{ + "@type": "setLogStream", + "log_stream": tdlib.UpdateData{ + "@type": "logStreamFile", + "path": path, + "max_file_size": 10485760, + }, + }) + + query := C.CString(string(bytes)) + C.td_json_client_execute(nil, query) + C.free(unsafe.Pointer(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) { + bytes, _ := json.Marshal(tdlib.UpdateData{ + "@type": "setLogVerbosityLevel", + "new_verbosity_level": level, + }) + + query := C.CString(string(bytes)) + C.td_json_client_execute(nil, query) + C.free(unsafe.Pointer(query)) +} + +// 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{}) (tdlib.UpdateMsg, error) { + var update tdlib.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 tdlib.UpdateData: + update = jsonQuery.(tdlib.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 tdlib.UpdateMsg, 1) + + client.waitersLock.Lock() + client.waiters[randomString] = waiter + client.waitersLock.Unlock() + + // send it through already implemented method + client.Send(update) + + select { + // wait response from main loop in NewClient() + case response := <-waiter: + client.waitersLock.Lock() + delete(client.waiters, randomString) + client.waitersLock.Unlock() + + return response, nil + // or timeout + case <-time.After(10 * time.Second): + client.waitersLock.Lock() + delete(client.waiters, randomString) + client.waitersLock.Unlock() + + return tdlib.UpdateMsg{}, errors.New("timeout") + } +} + +// Authorize is used to authorize the users +func (client *Client) Authorize() (tdlib.AuthorizationState, error) { + state, err := client.GetAuthorizationState() + if err != nil { + return nil, err + } + + if state.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitEncryptionKeyType { + ok, err := client.CheckDatabaseEncryptionKey(nil) + + if ok == nil || err != nil { + return nil, err + } + } else if state.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitTdlibParametersType { + client.sendTdLibParams() + } + + authState, err := client.GetAuthorizationState() + return authState, err +} + +func (client *Client) sendTdLibParams() { + client.Send(tdlib.UpdateData{ + "@type": "setTdlibParameters", + "parameters": tdlib.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) (tdlib.AuthorizationState, error) { + phoneNumberConfig := tdlib.PhoneNumberAuthenticationSettings{AllowFlashCall: false, IsCurrentPhoneNumber: false, AllowSmsRetrieverAPI: false} + _, err := client.SetAuthenticationPhoneNumber(phoneNumber, &phoneNumberConfig) + + 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) (tdlib.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) (tdlib.AuthorizationState, error) { + _, err := client.CheckAuthenticationPassword(password) + + if err != nil { + return nil, err + } + + authState, err := client.GetAuthorizationState() + return authState, err +} diff --git a/client/connectedWebsites.go b/client/connectedWebsites.go new file mode 100644 index 0000000..d70b4a0 --- /dev/null +++ b/client/connectedWebsites.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetConnectedWebsites Returns all website where the current user used Telegram to log in +func (client *Client) GetConnectedWebsites() (*tdlib.ConnectedWebsites, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getConnectedWebsites", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var connectedWebsites tdlib.ConnectedWebsites + err = json.Unmarshal(result.Raw, &connectedWebsites) + return &connectedWebsites, err + +} diff --git a/client/count.go b/client/count.go new file mode 100644 index 0000000..70c0df9 --- /dev/null +++ b/client/count.go @@ -0,0 +1,79 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 tdlib.SearchMessagesFilter, returnLocal bool) (*tdlib.Count, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var count tdlib.Count + err = json.Unmarshal(result.Raw, &count) + return &count, err + +} + +// GetFileDownloadedPrefixSize Returns file downloaded prefix size from a given offset, in bytes +// @param fileID Identifier of the file +// @param offset Offset from which downloaded prefix size should be calculated +func (client *Client) GetFileDownloadedPrefixSize(fileID int32, offset int32) (*tdlib.Count, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getFileDownloadedPrefixSize", + "file_id": fileID, + "offset": offset, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var count tdlib.Count + err = json.Unmarshal(result.Raw, &count) + return &count, err + +} + +// GetImportedContactCount Returns the total number of imported contacts +func (client *Client) GetImportedContactCount() (*tdlib.Count, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getImportedContactCount", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var count tdlib.Count + err = json.Unmarshal(result.Raw, &count) + return &count, err + +} diff --git a/client/countries.go b/client/countries.go new file mode 100644 index 0000000..297a08c --- /dev/null +++ b/client/countries.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetCountries Returns information about existing countries. Can be called before authorization +func (client *Client) GetCountries() (*tdlib.Countries, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getCountries", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var countries tdlib.Countries + err = json.Unmarshal(result.Raw, &countries) + return &countries, err + +} diff --git a/client/customRequestResult.go b/client/customRequestResult.go new file mode 100644 index 0000000..024b07e --- /dev/null +++ b/client/customRequestResult.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.CustomRequestResult, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendCustomRequest", + "method": method, + "parameters": parameters, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var customRequestResult tdlib.CustomRequestResult + err = json.Unmarshal(result.Raw, &customRequestResult) + return &customRequestResult, err + +} diff --git a/client/databaseStatistics.go b/client/databaseStatistics.go new file mode 100644 index 0000000..7efb27b --- /dev/null +++ b/client/databaseStatistics.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetDatabaseStatistics Returns database statistics +func (client *Client) GetDatabaseStatistics() (*tdlib.DatabaseStatistics, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getDatabaseStatistics", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var databaseStatistics tdlib.DatabaseStatistics + err = json.Unmarshal(result.Raw, &databaseStatistics) + return &databaseStatistics, err + +} diff --git a/client/deepLinkInfo.go b/client/deepLinkInfo.go new file mode 100644 index 0000000..6b83acd --- /dev/null +++ b/client/deepLinkInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.DeepLinkInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getDeepLinkInfo", + "link": link, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var deepLinkInfo tdlib.DeepLinkInfo + err = json.Unmarshal(result.Raw, &deepLinkInfo) + return &deepLinkInfo, err + +} diff --git a/client/emailAddressAuthenticationCodeInfo.go b/client/emailAddressAuthenticationCodeInfo.go new file mode 100644 index 0000000..b00992b --- /dev/null +++ b/client/emailAddressAuthenticationCodeInfo.go @@ -0,0 +1,71 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// RequestPasswordRecovery Requests to send a 2-step verification password recovery code to an email address that was previously set up +func (client *Client) RequestPasswordRecovery() (*tdlib.EmailAddressAuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "requestPasswordRecovery", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var emailAddressAuthenticationCodeInfo tdlib.EmailAddressAuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &emailAddressAuthenticationCodeInfo) + return &emailAddressAuthenticationCodeInfo, 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) (*tdlib.EmailAddressAuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendEmailAddressVerificationCode", + "email_address": emailAddress, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var emailAddressAuthenticationCodeInfo tdlib.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() (*tdlib.EmailAddressAuthenticationCodeInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resendEmailAddressVerificationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var emailAddressAuthenticationCodeInfo tdlib.EmailAddressAuthenticationCodeInfo + err = json.Unmarshal(result.Raw, &emailAddressAuthenticationCodeInfo) + return &emailAddressAuthenticationCodeInfo, err + +} diff --git a/client/emojis.go b/client/emojis.go new file mode 100644 index 0000000..f792a03 --- /dev/null +++ b/client/emojis.go @@ -0,0 +1,57 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetStickerEmojis Returns emoji corresponding to a sticker. The list is only for informational purposes, because a sticker is always sent with a fixed emoji from the corresponding Sticker object +// @param sticker Sticker file identifier +func (client *Client) GetStickerEmojis(sticker tdlib.InputFile) (*tdlib.Emojis, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getStickerEmojis", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var emojis tdlib.Emojis + err = json.Unmarshal(result.Raw, &emojis) + return &emojis, err + +} + +// SearchEmojis Searches for emojis by keywords. Supported only if the file database is enabled +// @param text Text to search for +// @param exactMatch True, if only emojis, which exactly match text needs to be returned +// @param inputLanguageCodes List of possible IETF language tags of the user's input language; may be empty if unknown +func (client *Client) SearchEmojis(text string, exactMatch bool, inputLanguageCodes []string) (*tdlib.Emojis, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchEmojis", + "text": text, + "exact_match": exactMatch, + "input_language_codes": inputLanguageCodes, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var emojis tdlib.Emojis + err = json.Unmarshal(result.Raw, &emojis) + return &emojis, err + +} diff --git a/client/error.go b/client/error.go new file mode 100644 index 0000000..bb27c24 --- /dev/null +++ b/client/error.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestReturnError Returns the specified error and ensures that the Error object is used; for testing only. Can be called synchronously +// @param error The error to be returned +func (client *Client) TestReturnError(error *tdlib.Error) (*tdlib.Error, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testReturnError", + "error": error, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var errorDummy tdlib.Error + err = json.Unmarshal(result.Raw, &errorDummy) + return &errorDummy, err + +} diff --git a/client/file.go b/client/file.go new file mode 100644 index 0000000..44591ad --- /dev/null +++ b/client/file.go @@ -0,0 +1,167 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.File, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getFile", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var fileDummy tdlib.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. Even the request succeeds, the file can be used only if it is still accessible to the user. For example, if the file is from a message, then the message must be not deleted and accessible to the user. If the file database is disabled, then the corresponding object with the file must be preloaded by the application +// @param remoteFileID Remote identifier of the file to get +// @param fileType File type, if known +func (client *Client) GetRemoteFile(remoteFileID string, fileType tdlib.FileType) (*tdlib.File, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRemoteFile", + "remote_file_id": remoteFileID, + "file_type": fileType, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var fileDummy tdlib.File + err = json.Unmarshal(result.Raw, &fileDummy) + return &fileDummy, err + +} + +// DownloadFile Downloads a file from the cloud. Download progress and completion of the download will be notified through updateFile updates +// @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 +// @param offset The starting position from which the file should be downloaded +// @param limit Number of bytes which should be downloaded starting from the "offset" position before the download will be automatically canceled; use 0 to download without a limit +// @param synchronous If false, this request returns file state just after the download has been started. If true, this request returns file state only after the download has succeeded, has failed, has been canceled or a new downloadFile request with different offset/limit parameters was sent +func (client *Client) DownloadFile(fileID int32, priority int32, offset int32, limit int32, synchronous bool) (*tdlib.File, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "downloadFile", + "file_id": fileID, + "priority": priority, + "offset": offset, + "limit": limit, + "synchronous": synchronous, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var fileDummy tdlib.File + err = json.Unmarshal(result.Raw, &fileDummy) + return &fileDummy, 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 tdlib.InputFile, fileType tdlib.FileType, priority int32) (*tdlib.File, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "uploadFile", + "file": file, + "file_type": fileType, + "priority": priority, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var fileDummy tdlib.File + err = json.Unmarshal(result.Raw, &fileDummy) + return &fileDummy, err + +} + +// UploadStickerFile Uploads a PNG image with a sticker; returns the uploaded file +// @param userID Sticker file owner; ignored for regular users +// @param sticker Sticker file to upload +func (client *Client) UploadStickerFile(userID int64, sticker tdlib.InputSticker) (*tdlib.File, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "uploadStickerFile", + "user_id": userID, + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var file tdlib.File + err = json.Unmarshal(result.Raw, &file) + return &file, 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 *tdlib.Location, zoom int32, width int32, height int32, scale int32, chatID int64) (*tdlib.File, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var file tdlib.File + err = json.Unmarshal(result.Raw, &file) + return &file, err + +} diff --git a/client/filePart.go b/client/filePart.go new file mode 100644 index 0000000..1217523 --- /dev/null +++ b/client/filePart.go @@ -0,0 +1,65 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// ReadFilePart Reads a part of a file from the TDLib file cache and returns read bytes. This method is intended to be used only if the application has no direct access to TDLib's file system, because it is usually slower than a direct read from the file +// @param fileID Identifier of the file. The file must be located in the TDLib file cache +// @param offset The offset from which to read the file +// @param count Number of bytes to read. An error will be returned if there are not enough bytes available in the file from the specified position. Pass 0 to read all available data from the specified position +func (client *Client) ReadFilePart(fileID int32, offset int32, count int32) (*tdlib.FilePart, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "readFilePart", + "file_id": fileID, + "offset": offset, + "count": count, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var filePart tdlib.FilePart + err = json.Unmarshal(result.Raw, &filePart) + return &filePart, err + +} + +// GetGroupCallStreamSegment Returns a file with a segment of a group call stream in a modified OGG format for audio or MPEG-4 format for video +// @param groupCallID Group call identifier +// @param timeOffset Point in time when the stream segment begins; Unix timestamp in milliseconds +// @param scale Segment duration scale; 0-1. Segment's duration is 1000/(2**scale) milliseconds +// @param channelID Identifier of an audio/video channel to get as received from tgcalls +// @param videoQuality Video quality as received from tgcalls +func (client *Client) GetGroupCallStreamSegment(groupCallID int32, timeOffset int64, scale int32, channelID int32, videoQuality tdlib.GroupCallVideoQuality) (*tdlib.FilePart, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getGroupCallStreamSegment", + "group_call_id": groupCallID, + "time_offset": timeOffset, + "scale": scale, + "channel_id": channelID, + "video_quality": videoQuality, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var filePart tdlib.FilePart + err = json.Unmarshal(result.Raw, &filePart) + return &filePart, err + +} diff --git a/client/formattedText.go b/client/formattedText.go new file mode 100644 index 0000000..bcb3103 --- /dev/null +++ b/client/formattedText.go @@ -0,0 +1,77 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// ParseTextEntities Parses Bold, Italic, Underline, Strikethrough, Code, Pre, PreCode, TextUrl and MentionName entities contained in the text. Can be called synchronously +// @param text The text to parse +// @param parseMode Text parse mode +func (client *Client) ParseTextEntities(text string, parseMode tdlib.TextParseMode) (*tdlib.FormattedText, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "parseTextEntities", + "text": text, + "parse_mode": parseMode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var formattedText tdlib.FormattedText + err = json.Unmarshal(result.Raw, &formattedText) + return &formattedText, err + +} + +// ParseMarkdown Parses Markdown entities in a human-friendly format, ignoring markup errors. Can be called synchronously +// @param text The text to parse. For example, "__italic__ ~~strikethrough~~ **bold** `code` ```pre``` __[italic__ text_url](telegram.org) __italic**bold italic__bold**" +func (client *Client) ParseMarkdown(text *tdlib.FormattedText) (*tdlib.FormattedText, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "parseMarkdown", + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var formattedText tdlib.FormattedText + err = json.Unmarshal(result.Raw, &formattedText) + return &formattedText, err + +} + +// GetMarkdownText Replaces text entities with Markdown formatting in a human-friendly format. Entities that can't be represented in Markdown unambiguously are kept as is. Can be called synchronously +// @param text The text +func (client *Client) GetMarkdownText(text *tdlib.FormattedText) (*tdlib.FormattedText, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMarkdownText", + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var formattedText tdlib.FormattedText + err = json.Unmarshal(result.Raw, &formattedText) + return &formattedText, err + +} diff --git a/client/foundMessages.go b/client/foundMessages.go new file mode 100644 index 0000000..2cb98ce --- /dev/null +++ b/client/foundMessages.go @@ -0,0 +1,67 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 TDLib +// @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 offset Offset of the first entry to return as received from the previous request; use empty string to get first chunk of results +// @param limit The maximum number of messages to be returned; up to 100. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +// @param filter A filter for message content in the search results +func (client *Client) SearchSecretMessages(chatID int64, query string, offset string, limit int32, filter tdlib.SearchMessagesFilter) (*tdlib.FoundMessages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchSecretMessages", + "chat_id": chatID, + "query": query, + "offset": offset, + "limit": limit, + "filter": filter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var foundMessages tdlib.FoundMessages + err = json.Unmarshal(result.Raw, &foundMessages) + return &foundMessages, err + +} + +// GetMessagePublicForwards Returns forwarded copies of a channel message to different public channels. For optimal performance, the number of returned messages is chosen by TDLib +// @param chatID Chat identifier of the message +// @param messageID Message identifier +// @param offset Offset of the first entry to return as received from the previous request; use empty string to get first chunk of results +// @param limit The maximum number of messages to be returned; must be positive and can't be greater than 100. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +func (client *Client) GetMessagePublicForwards(chatID int64, messageID int64, offset string, limit int32) (*tdlib.FoundMessages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessagePublicForwards", + "chat_id": chatID, + "message_id": messageID, + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var foundMessages tdlib.FoundMessages + err = json.Unmarshal(result.Raw, &foundMessages) + return &foundMessages, err + +} diff --git a/client/gameHighScores.go b/client/gameHighScores.go new file mode 100644 index 0000000..de72a61 --- /dev/null +++ b/client/gameHighScores.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 int64) (*tdlib.GameHighScores, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var gameHighScores tdlib.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 int64) (*tdlib.GameHighScores, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getInlineGameHighScores", + "inline_message_id": inlineMessageID, + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var gameHighScores tdlib.GameHighScores + err = json.Unmarshal(result.Raw, &gameHighScores) + return &gameHighScores, err + +} diff --git a/client/groupCall.go b/client/groupCall.go new file mode 100644 index 0000000..889cfcb --- /dev/null +++ b/client/groupCall.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetGroupCall Returns information about a group call +// @param groupCallID Group call identifier +func (client *Client) GetGroupCall(groupCallID int32) (*tdlib.GroupCall, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getGroupCall", + "group_call_id": groupCallID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var groupCallDummy tdlib.GroupCall + err = json.Unmarshal(result.Raw, &groupCallDummy) + return &groupCallDummy, err + +} diff --git a/client/groupCallID.go b/client/groupCallID.go new file mode 100644 index 0000000..c75992e --- /dev/null +++ b/client/groupCallID.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// CreateVoiceChat Creates a voice chat (a group call bound to a chat). Available only for basic groups, supergroups and channels; requires can_manage_voice_chats rights +// @param chatID Chat identifier, in which the voice chat will be created +// @param title Group call title; if empty, chat title will be used +// @param startDate Point in time (Unix timestamp) when the group call is supposed to be started by an administrator; 0 to start the voice chat immediately. The date must be at least 10 seconds and at most 8 days in the future +func (client *Client) CreateVoiceChat(chatID int64, title string, startDate int32) (*tdlib.GroupCallID, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createVoiceChat", + "chat_id": chatID, + "title": title, + "start_date": startDate, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var groupCallID tdlib.GroupCallID + err = json.Unmarshal(result.Raw, &groupCallID) + return &groupCallID, err + +} diff --git a/client/hashtags.go b/client/hashtags.go new file mode 100644 index 0000000..631ff3d --- /dev/null +++ b/client/hashtags.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// SearchHashtags Searches for recently used hashtags by their prefix +// @param prefix Hashtag prefix to search for +// @param limit The maximum number of hashtags to be returned +func (client *Client) SearchHashtags(prefix string, limit int32) (*tdlib.Hashtags, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchHashtags", + "prefix": prefix, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var hashtags tdlib.Hashtags + err = json.Unmarshal(result.Raw, &hashtags) + return &hashtags, err + +} diff --git a/client/httpURL.go b/client/httpURL.go new file mode 100644 index 0000000..c782971 --- /dev/null +++ b/client/httpURL.go @@ -0,0 +1,199 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLoginURL Returns an HTTP URL which can be used to automatically authorize the user on a website after clicking an inline button of type inlineKeyboardButtonTypeLoginUrl. Use the method getLoginUrlInfo to find whether a prior user confirmation is needed. If an error is returned, then the button must be handled as an ordinary URL button +// @param chatID Chat identifier of the message with the button +// @param messageID Message identifier of the message with the button +// @param buttonID Button identifier +// @param allowWriteAccess True, if the user allowed the bot to send them messages +func (client *Client) GetLoginURL(chatID int64, messageID int64, buttonID int64, allowWriteAccess bool) (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLoginUrl", + "chat_id": chatID, + "message_id": messageID, + "button_id": buttonID, + "allow_write_access": allowWriteAccess, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, err + +} + +// GetExternalLink Returns an HTTP URL which can be used to automatically authorize the current user on a website after clicking an HTTP link. Use the method getExternalLinkInfo to find whether a prior user confirmation is needed +// @param link The HTTP link +// @param allowWriteAccess True, if the current user allowed the bot, returned in getExternalLinkInfo, to send them messages +func (client *Client) GetExternalLink(link string, allowWriteAccess bool) (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getExternalLink", + "link": link, + "allow_write_access": allowWriteAccess, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, err + +} + +// GetGroupCallInviteLink Returns invite link to a voice chat in a public chat +// @param groupCallID Group call identifier +// @param canSelfUnmute Pass true if the invite_link should contain an invite hash, passing which to joinGroupCall would allow the invited user to unmute themselves. Requires groupCall.can_be_managed group call flag +func (client *Client) GetGroupCallInviteLink(groupCallID int32, canSelfUnmute bool) (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getGroupCallInviteLink", + "group_call_id": groupCallID, + "can_self_unmute": canSelfUnmute, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, err + +} + +// GetEmojiSuggestionsURL Returns an HTTP URL which can be used to automatically log in to the translation platform and suggest new emoji replacements. The URL will be valid for 30 seconds after generation +// @param languageCode Language code for which the emoji replacements will be suggested +func (client *Client) GetEmojiSuggestionsURL(languageCode string) (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getEmojiSuggestionsUrl", + "language_code": languageCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, err + +} + +// GetBackgroundURL Constructs a persistent HTTP URL for a background +// @param name Background name +// @param typeParam Background type +func (client *Client) GetBackgroundURL(name string, typeParam tdlib.BackgroundType) (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getBackgroundUrl", + "name": name, + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, err + +} + +// GetChatStatisticsURL Returns an HTTP URL with the chat statistics. Currently this method of getting the statistics are disabled and can be deleted in the future +// @param chatID Chat identifier +// @param parameters Parameters for the request +// @param isDark Pass true if a URL with the dark theme must be returned +func (client *Client) GetChatStatisticsURL(chatID int64, parameters string, isDark bool) (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatStatisticsUrl", + "chat_id": chatID, + "parameters": parameters, + "is_dark": isDark, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, err + +} + +// GetApplicationDownloadLink Returns the link for downloading official Telegram application to be used when the current user invites friends to Telegram +func (client *Client) GetApplicationDownloadLink() (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getApplicationDownloadLink", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, 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) (*tdlib.HttpURL, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getProxyLink", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var httpURL tdlib.HttpURL + err = json.Unmarshal(result.Raw, &httpURL) + return &httpURL, err + +} diff --git a/client/importedContacts.go b/client/importedContacts.go new file mode 100644 index 0000000..6e86767 --- /dev/null +++ b/client/importedContacts.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// ImportContacts Adds new contacts or edits existing contacts by their phone numbers; contacts' user identifiers are ignored +// @param contacts The list of contacts to import or edit; contacts' vCard are ignored and are not imported +func (client *Client) ImportContacts(contacts []tdlib.Contact) (*tdlib.ImportedContacts, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "importContacts", + "contacts": contacts, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var importedContacts tdlib.ImportedContacts + err = json.Unmarshal(result.Raw, &importedContacts) + return &importedContacts, err + +} + +// ChangeImportedContacts Changes imported contacts using the list of contacts saved on the device. Imports newly added contacts and, if at least the file database is enabled, deletes recently deleted contacts. Query result depends on the result of the previous query, so only one query is possible at the same time +// @param contacts The new list of contacts, contact's vCard are ignored and are not imported +func (client *Client) ChangeImportedContacts(contacts []tdlib.Contact) (*tdlib.ImportedContacts, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "changeImportedContacts", + "contacts": contacts, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var importedContacts tdlib.ImportedContacts + err = json.Unmarshal(result.Raw, &importedContacts) + return &importedContacts, err + +} diff --git a/client/inlineQueryResults.go b/client/inlineQueryResults.go new file mode 100644 index 0000000..baaae0c --- /dev/null +++ b/client/inlineQueryResults.go @@ -0,0 +1,39 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 int64, chatID int64, userLocation *tdlib.Location, query string, offset string) (*tdlib.InlineQueryResults, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var inlineQueryResults tdlib.InlineQueryResults + err = json.Unmarshal(result.Raw, &inlineQueryResults) + return &inlineQueryResults, err + +} diff --git a/client/internalLinkType.go b/client/internalLinkType.go new file mode 100644 index 0000000..13ec014 --- /dev/null +++ b/client/internalLinkType.go @@ -0,0 +1,148 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetInternalLinkType Returns information about the type of an internal link. Returns a 404 error if the link is not internal. Can be called before authorization +// @param link The link +func (client *Client) GetInternalLinkType(link string) (tdlib.InternalLinkType, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getInternalLinkType", + "link": link, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.InternalLinkTypeEnum(result.Data["@type"].(string)) { + + case tdlib.InternalLinkTypeActiveSessionsType: + var internalLinkType tdlib.InternalLinkTypeActiveSessions + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeAuthenticationCodeType: + var internalLinkType tdlib.InternalLinkTypeAuthenticationCode + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeBackgroundType: + var internalLinkType tdlib.InternalLinkTypeBackground + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeBotStartType: + var internalLinkType tdlib.InternalLinkTypeBotStart + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeBotStartInGroupType: + var internalLinkType tdlib.InternalLinkTypeBotStartInGroup + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeChangePhoneNumberType: + var internalLinkType tdlib.InternalLinkTypeChangePhoneNumber + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeChatInviteType: + var internalLinkType tdlib.InternalLinkTypeChatInvite + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeFilterSettingsType: + var internalLinkType tdlib.InternalLinkTypeFilterSettings + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeGameType: + var internalLinkType tdlib.InternalLinkTypeGame + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeLanguagePackType: + var internalLinkType tdlib.InternalLinkTypeLanguagePack + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeMessageType: + var internalLinkType tdlib.InternalLinkTypeMessage + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeMessageDraftType: + var internalLinkType tdlib.InternalLinkTypeMessageDraft + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypePassportDataRequestType: + var internalLinkType tdlib.InternalLinkTypePassportDataRequest + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypePhoneNumberConfirmationType: + var internalLinkType tdlib.InternalLinkTypePhoneNumberConfirmation + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeProxyType: + var internalLinkType tdlib.InternalLinkTypeProxy + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypePublicChatType: + var internalLinkType tdlib.InternalLinkTypePublicChat + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeQrCodeAuthenticationType: + var internalLinkType tdlib.InternalLinkTypeQrCodeAuthentication + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeSettingsType: + var internalLinkType tdlib.InternalLinkTypeSettings + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeStickerSetType: + var internalLinkType tdlib.InternalLinkTypeStickerSet + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeThemeType: + var internalLinkType tdlib.InternalLinkTypeTheme + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeThemeSettingsType: + var internalLinkType tdlib.InternalLinkTypeThemeSettings + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeUnknownDeepLinkType: + var internalLinkType tdlib.InternalLinkTypeUnknownDeepLink + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + case tdlib.InternalLinkTypeVoiceChatType: + var internalLinkType tdlib.InternalLinkTypeVoiceChat + err = json.Unmarshal(result.Raw, &internalLinkType) + return &internalLinkType, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/jsonValue.go b/client/jsonValue.go new file mode 100644 index 0000000..debc9dc --- /dev/null +++ b/client/jsonValue.go @@ -0,0 +1,114 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetJsonValue Converts a JSON-serialized string to corresponding JsonValue object. Can be called synchronously +// @param jsonString The JSON-serialized string +func (client *Client) GetJsonValue(jsonString string) (tdlib.JsonValue, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getJsonValue", + "json": jsonString, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.JsonValueEnum(result.Data["@type"].(string)) { + + case tdlib.JsonValueNullType: + var jsonValue tdlib.JsonValueNull + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueBooleanType: + var jsonValue tdlib.JsonValueBoolean + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueNumberType: + var jsonValue tdlib.JsonValueNumber + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueStringType: + var jsonValue tdlib.JsonValueString + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueArrayType: + var jsonValue tdlib.JsonValueArray + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueObjectType: + var jsonValue tdlib.JsonValueObject + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// GetApplicationConfig Returns application config, provided by the server. Can be called before authorization +func (client *Client) GetApplicationConfig() (tdlib.JsonValue, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getApplicationConfig", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.JsonValueEnum(result.Data["@type"].(string)) { + + case tdlib.JsonValueNullType: + var jsonValue tdlib.JsonValueNull + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueBooleanType: + var jsonValue tdlib.JsonValueBoolean + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueNumberType: + var jsonValue tdlib.JsonValueNumber + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueStringType: + var jsonValue tdlib.JsonValueString + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueArrayType: + var jsonValue tdlib.JsonValueArray + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + case tdlib.JsonValueObjectType: + var jsonValue tdlib.JsonValueObject + err = json.Unmarshal(result.Raw, &jsonValue) + return &jsonValue, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/languagePackInfo.go b/client/languagePackInfo.go new file mode 100644 index 0000000..663e09d --- /dev/null +++ b/client/languagePackInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLanguagePackInfo Returns information about a language pack. Returned language pack identifier may be different from a provided one. Can be called before authorization +// @param languagePackID Language pack identifier +func (client *Client) GetLanguagePackInfo(languagePackID string) (*tdlib.LanguagePackInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLanguagePackInfo", + "language_pack_id": languagePackID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var languagePackInfo tdlib.LanguagePackInfo + err = json.Unmarshal(result.Raw, &languagePackInfo) + return &languagePackInfo, err + +} diff --git a/client/languagePackStringValue.go b/client/languagePackStringValue.go new file mode 100644 index 0000000..57ddf8c --- /dev/null +++ b/client/languagePackStringValue.go @@ -0,0 +1,54 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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. 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) (tdlib.LanguagePackStringValue, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.LanguagePackStringValueEnum(result.Data["@type"].(string)) { + + case tdlib.LanguagePackStringValueOrdinaryType: + var languagePackStringValue tdlib.LanguagePackStringValueOrdinary + err = json.Unmarshal(result.Raw, &languagePackStringValue) + return &languagePackStringValue, err + + case tdlib.LanguagePackStringValuePluralizedType: + var languagePackStringValue tdlib.LanguagePackStringValuePluralized + err = json.Unmarshal(result.Raw, &languagePackStringValue) + return &languagePackStringValue, err + + case tdlib.LanguagePackStringValueDeletedType: + var languagePackStringValue tdlib.LanguagePackStringValueDeleted + err = json.Unmarshal(result.Raw, &languagePackStringValue) + return &languagePackStringValue, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/languagePackStrings.go b/client/languagePackStrings.go new file mode 100644 index 0000000..0964538 --- /dev/null +++ b/client/languagePackStrings.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLanguagePackStrings Returns strings from a language pack in the current localization target by their keys. Can be called before authorization +// @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) (*tdlib.LanguagePackStrings, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLanguagePackStrings", + "language_pack_id": languagePackID, + "keys": keys, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var languagePackStrings tdlib.LanguagePackStrings + err = json.Unmarshal(result.Raw, &languagePackStrings) + return &languagePackStrings, err + +} diff --git a/client/localizationTargetInfo.go b/client/localizationTargetInfo.go new file mode 100644 index 0000000..3a3de88 --- /dev/null +++ b/client/localizationTargetInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLocalizationTargetInfo Returns information about the current localization target. This is an offline request if only_local is true. Can be called before authorization +// @param onlyLocal If true, returns only locally available information without sending network requests +func (client *Client) GetLocalizationTargetInfo(onlyLocal bool) (*tdlib.LocalizationTargetInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLocalizationTargetInfo", + "only_local": onlyLocal, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var localizationTargetInfo tdlib.LocalizationTargetInfo + err = json.Unmarshal(result.Raw, &localizationTargetInfo) + return &localizationTargetInfo, err + +} diff --git a/client/logStream.go b/client/logStream.go new file mode 100644 index 0000000..bde05f7 --- /dev/null +++ b/client/logStream.go @@ -0,0 +1,46 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLogStream Returns information about currently used log stream for internal logging of TDLib. Can be called synchronously +func (client *Client) GetLogStream() (tdlib.LogStream, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLogStream", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.LogStreamEnum(result.Data["@type"].(string)) { + + case tdlib.LogStreamDefaultType: + var logStream tdlib.LogStreamDefault + err = json.Unmarshal(result.Raw, &logStream) + return &logStream, err + + case tdlib.LogStreamFileType: + var logStream tdlib.LogStreamFile + err = json.Unmarshal(result.Raw, &logStream) + return &logStream, err + + case tdlib.LogStreamEmptyType: + var logStream tdlib.LogStreamEmpty + err = json.Unmarshal(result.Raw, &logStream) + return &logStream, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/logTags.go b/client/logTags.go new file mode 100644 index 0000000..3a0c29a --- /dev/null +++ b/client/logTags.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLogTags Returns list of available TDLib internal log tags, for example, ["actor", "binlog", "connections", "notifications", "proxy"]. Can be called synchronously +func (client *Client) GetLogTags() (*tdlib.LogTags, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLogTags", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var logTags tdlib.LogTags + err = json.Unmarshal(result.Raw, &logTags) + return &logTags, err + +} diff --git a/client/logVerbosityLevel.go b/client/logVerbosityLevel.go new file mode 100644 index 0000000..5c0ed4a --- /dev/null +++ b/client/logVerbosityLevel.go @@ -0,0 +1,51 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLogVerbosityLevel Returns current verbosity level of the internal logging of TDLib. Can be called synchronously +func (client *Client) GetLogVerbosityLevel() (*tdlib.LogVerbosityLevel, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLogVerbosityLevel", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var logVerbosityLevel tdlib.LogVerbosityLevel + err = json.Unmarshal(result.Raw, &logVerbosityLevel) + return &logVerbosityLevel, err + +} + +// GetLogTagVerbosityLevel Returns current verbosity level for a specified TDLib internal log tag. Can be called synchronously +// @param tag Logging tag to change verbosity level +func (client *Client) GetLogTagVerbosityLevel(tag string) (*tdlib.LogVerbosityLevel, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLogTagVerbosityLevel", + "tag": tag, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var logVerbosityLevel tdlib.LogVerbosityLevel + err = json.Unmarshal(result.Raw, &logVerbosityLevel) + return &logVerbosityLevel, err + +} diff --git a/client/loginURLInfo.go b/client/loginURLInfo.go new file mode 100644 index 0000000..1ad6fd0 --- /dev/null +++ b/client/loginURLInfo.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetLoginURLInfo Returns information about a button of type inlineKeyboardButtonTypeLoginUrl. The method needs to be called when the user presses the button +// @param chatID Chat identifier of the message with the button +// @param messageID Message identifier of the message with the button +// @param buttonID Button identifier +func (client *Client) GetLoginURLInfo(chatID int64, messageID int64, buttonID int64) (tdlib.LoginURLInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getLoginUrlInfo", + "chat_id": chatID, + "message_id": messageID, + "button_id": buttonID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.LoginURLInfoEnum(result.Data["@type"].(string)) { + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// GetExternalLinkInfo Returns information about an action to be done when the current user clicks an external link. Don't use this method for links from secret chats if web page preview is disabled in secret chats +// @param link The link +func (client *Client) GetExternalLinkInfo(link string) (tdlib.LoginURLInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getExternalLinkInfo", + "link": link, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.LoginURLInfoEnum(result.Data["@type"].(string)) { + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/message.go b/client/message.go new file mode 100644 index 0000000..b0c58e9 --- /dev/null +++ b/client/message.go @@ -0,0 +1,449 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessage", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// GetMessageLocally Returns information about a message, if it is available locally without sending network request. This is an offline request +// @param chatID Identifier of the chat the message belongs to +// @param messageID Identifier of the message to get +func (client *Client) GetMessageLocally(chatID int64, messageID int64) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageLocally", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// GetRepliedMessage Returns information about a message that is replied by a given message. Also returns the pinned message, the game message, and the invoice message for messages of the types messagePinMessage, messageGameScore, and messagePaymentSuccessful respectively +// @param chatID Identifier of the chat the message belongs to +// @param messageID Identifier of the message reply to which to get +func (client *Client) GetRepliedMessage(chatID int64, messageID int64) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRepliedMessage", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} + +// GetChatPinnedMessage Returns information about a newest pinned message in the chat +// @param chatID Identifier of the chat the message belongs to +func (client *Client) GetChatPinnedMessage(chatID int64) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatPinnedMessage", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var message tdlib.Message + err = json.Unmarshal(result.Raw, &message) + return &message, err + +} + +// GetCallbackQueryMessage Returns information about a message with the callback button that originated a callback query; for bots only +// @param chatID Identifier of the chat the message belongs to +// @param messageID Message identifier +// @param callbackQueryID Identifier of the callback query +func (client *Client) GetCallbackQueryMessage(chatID int64, messageID int64, callbackQueryID *tdlib.JSONInt64) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getCallbackQueryMessage", + "chat_id": chatID, + "message_id": messageID, + "callback_query_id": callbackQueryID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, 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) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatMessageByDate", + "chat_id": chatID, + "date": date, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var message tdlib.Message + err = json.Unmarshal(result.Raw, &message) + return &message, err + +} + +// SendMessage Sends a message. Returns the sent message +// @param chatID Target chat +// @param messageThreadID If not 0, a message thread identifier in which the message will be sent +// @param replyToMessageID Identifier of the message to reply to or 0 +// @param options Options to be used to send the message +// @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, messageThreadID int64, replyToMessageID int64, options *tdlib.MessageSendOptions, replyMarkup tdlib.ReplyMarkup, inputMessageContent tdlib.InputMessageContent) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendMessage", + "chat_id": chatID, + "message_thread_id": messageThreadID, + "reply_to_message_id": replyToMessageID, + "options": options, + "reply_markup": replyMarkup, + "input_message_content": inputMessageContent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, 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://core.telegram.org/bots#deep-linking) +func (client *Client) SendBotStartMessage(botUserID int64, chatID int64, parameter string) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var message tdlib.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 messageThreadID If not 0, a message thread identifier in which the message will be sent +// @param replyToMessageID Identifier of a message to reply to or 0 +// @param options Options to be used to send the message +// @param queryID Identifier of the inline query +// @param resultID Identifier of the inline result +// @param hideViaBot If true, there will be no mention of a bot, via which the message is sent. Can be used only for bots GetOption("animation_search_bot_username"), GetOption("photo_search_bot_username") and GetOption("venue_search_bot_username") +func (client *Client) SendInlineQueryResultMessage(chatID int64, messageThreadID int64, replyToMessageID int64, options *tdlib.MessageSendOptions, queryID *tdlib.JSONInt64, resultID string, hideViaBot bool) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendInlineQueryResultMessage", + "chat_id": chatID, + "message_thread_id": messageThreadID, + "reply_to_message_id": replyToMessageID, + "options": options, + "query_id": queryID, + "result_id": resultID, + "hide_via_bot": hideViaBot, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, 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 sender The sender sender of the message +// @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, sender tdlib.MessageSender, replyToMessageID int64, disableNotification bool, inputMessageContent tdlib.InputMessageContent) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addLocalMessage", + "chat_id": chatID, + "sender": sender, + "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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, 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 tdlib.ReplyMarkup, inputMessageContent tdlib.InputMessageContent) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.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 +// @param heading The new direction in which the location moves, in degrees; 1-360. Pass 0 if unknown +// @param proximityAlertRadius The new maximum distance for proximity alerts, in meters (0-100000). Pass 0 if the notification is disabled +func (client *Client) EditMessageLiveLocation(chatID int64, messageID int64, replyMarkup tdlib.ReplyMarkup, location *tdlib.Location, heading int32, proximityAlertRadius int32) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "editMessageLiveLocation", + "chat_id": chatID, + "message_id": messageID, + "reply_markup": replyMarkup, + "location": location, + "heading": heading, + "proximity_alert_radius": proximityAlertRadius, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.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, including message caption. If only the caption needs to be edited, use editMessageCaption instead. The media can't be edited if the message was set to self-destruct or to a self-destructing media. The type of message content in an album can't be changed with exception of replacing a photo with a video or vice versa. 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 tdlib.ReplyMarkup, inputMessageContent tdlib.InputMessageContent) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.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 tdlib.ReplyMarkup, caption *tdlib.FormattedText) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.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 tdlib.ReplyMarkup) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, 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 belongs +// @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 int64, score int32, force bool) (*tdlib.Message, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageDummy tdlib.Message + err = json.Unmarshal(result.Raw, &messageDummy) + return &messageDummy, err + +} diff --git a/client/messageFileType.go b/client/messageFileType.go new file mode 100644 index 0000000..65dae8a --- /dev/null +++ b/client/messageFileType.go @@ -0,0 +1,48 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetMessageFileType Returns information about a file with messages exported from another app +// @param messageFileHead Beginning of the message file; up to 100 first lines +func (client *Client) GetMessageFileType(messageFileHead string) (tdlib.MessageFileType, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageFileType", + "message_file_head": messageFileHead, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.MessageFileTypeEnum(result.Data["@type"].(string)) { + + case tdlib.MessageFileTypePrivateType: + var messageFileType tdlib.MessageFileTypePrivate + err = json.Unmarshal(result.Raw, &messageFileType) + return &messageFileType, err + + case tdlib.MessageFileTypeGroupType: + var messageFileType tdlib.MessageFileTypeGroup + err = json.Unmarshal(result.Raw, &messageFileType) + return &messageFileType, err + + case tdlib.MessageFileTypeUnknownType: + var messageFileType tdlib.MessageFileTypeUnknown + err = json.Unmarshal(result.Raw, &messageFileType) + return &messageFileType, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/messageLink.go b/client/messageLink.go new file mode 100644 index 0000000..0e28b1c --- /dev/null +++ b/client/messageLink.go @@ -0,0 +1,39 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetMessageLink Returns an HTTPS link to a message in a chat. Available only for already sent messages in supergroups and channels, or if message.can_get_media_timestamp_links and a media timestamp link is generated. This is an offline request +// @param chatID Identifier of the chat to which the message belongs +// @param messageID Identifier of the message +// @param mediaTimestamp If not 0, timestamp from which the video/audio/video note/voice note playing should start, in seconds. The media can be in the message content or in its web page preview +// @param forAlbum Pass true to create a link for the whole media album +// @param forComment Pass true to create a link to the message as a channel post comment, or from a message thread +func (client *Client) GetMessageLink(chatID int64, messageID int64, mediaTimestamp int32, forAlbum bool, forComment bool) (*tdlib.MessageLink, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageLink", + "chat_id": chatID, + "message_id": messageID, + "media_timestamp": mediaTimestamp, + "for_album": forAlbum, + "for_comment": forComment, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageLink tdlib.MessageLink + err = json.Unmarshal(result.Raw, &messageLink) + return &messageLink, err + +} diff --git a/client/messageLinkInfo.go b/client/messageLinkInfo.go new file mode 100644 index 0000000..046e6bc --- /dev/null +++ b/client/messageLinkInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetMessageLinkInfo Returns information about a public or private message link. Can be called for any internal link of the type internalLinkTypeMessage +// @param uRL The message link +func (client *Client) GetMessageLinkInfo(uRL string) (*tdlib.MessageLinkInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageLinkInfo", + "url": uRL, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageLinkInfo tdlib.MessageLinkInfo + err = json.Unmarshal(result.Raw, &messageLinkInfo) + return &messageLinkInfo, err + +} diff --git a/client/messageSenders.go b/client/messageSenders.go new file mode 100644 index 0000000..d14b67b --- /dev/null +++ b/client/messageSenders.go @@ -0,0 +1,55 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetVoiceChatAvailableParticipants Returns list of participant identifiers, which can be used to join voice chats in a chat +// @param chatID Chat identifier +func (client *Client) GetVoiceChatAvailableParticipants(chatID int64) (*tdlib.MessageSenders, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getVoiceChatAvailableParticipants", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageSenders tdlib.MessageSenders + err = json.Unmarshal(result.Raw, &messageSenders) + return &messageSenders, err + +} + +// GetBlockedMessageSenders Returns users and chats that were blocked by the current user +// @param offset Number of users and chats to skip in the result; must be non-negative +// @param limit The maximum number of users and chats to return; up to 100 +func (client *Client) GetBlockedMessageSenders(offset int32, limit int32) (*tdlib.MessageSenders, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getBlockedMessageSenders", + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageSenders tdlib.MessageSenders + err = json.Unmarshal(result.Raw, &messageSenders) + return &messageSenders, err + +} diff --git a/client/messageStatistics.go b/client/messageStatistics.go new file mode 100644 index 0000000..92bcf8c --- /dev/null +++ b/client/messageStatistics.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetMessageStatistics Returns detailed statistics about a message. Can be used only if Message.can_get_statistics == true +// @param chatID Chat identifier +// @param messageID Message identifier +// @param isDark Pass true if a dark theme is used by the application +func (client *Client) GetMessageStatistics(chatID int64, messageID int64, isDark bool) (*tdlib.MessageStatistics, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageStatistics", + "chat_id": chatID, + "message_id": messageID, + "is_dark": isDark, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageStatistics tdlib.MessageStatistics + err = json.Unmarshal(result.Raw, &messageStatistics) + return &messageStatistics, err + +} diff --git a/client/messageThreadInfo.go b/client/messageThreadInfo.go new file mode 100644 index 0000000..209a2d4 --- /dev/null +++ b/client/messageThreadInfo.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetMessageThread Returns information about a message thread. Can be used only if message.can_get_message_thread == true +// @param chatID Chat identifier +// @param messageID Identifier of the message +func (client *Client) GetMessageThread(chatID int64, messageID int64) (*tdlib.MessageThreadInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageThread", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messageThreadInfo tdlib.MessageThreadInfo + err = json.Unmarshal(result.Raw, &messageThreadInfo) + return &messageThreadInfo, err + +} diff --git a/client/messages.go b/client/messages.go new file mode 100644 index 0000000..f4ba42d --- /dev/null +++ b/client/messages.go @@ -0,0 +1,347 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessages", + "chat_id": chatID, + "message_ids": messageIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// GetChatHistory Returns messages in a chat. The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id). For optimal performance, the number of returned messages is chosen by TDLib. This is an offline request if only_local is true +// @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 up to 99 to get additionally 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 or equal to -offset. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +// @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) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// GetMessageThreadHistory Returns messages in a message thread of a message. Can be used only if message.can_get_message_thread == true. Message thread of a channel message is in the channel's linked supergroup. The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id). For optimal performance, the number of returned messages is chosen by TDLib +// @param chatID Chat identifier +// @param messageID Message identifier, which thread history needs to be returned +// @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 up to 99 to get additionally 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 or equal to -offset. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +func (client *Client) GetMessageThreadHistory(chatID int64, messageID int64, fromMessageID int64, offset int32, limit int32) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageThreadHistory", + "chat_id": chatID, + "message_id": messageID, + "from_message_id": fromMessageID, + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, 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 (searchSecretMessages should be used instead), or without an enabled message database. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +// @param chatID Identifier of the chat in which to search messages +// @param query Query to search for +// @param sender If not null, only messages sent by the specified sender 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. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +// @param filter Filter for message content in the search results +// @param messageThreadID If not 0, only messages in the specified thread will be returned; supergroups only +func (client *Client) SearchChatMessages(chatID int64, query string, sender tdlib.MessageSender, fromMessageID int64, offset int32, limit int32, filter tdlib.SearchMessagesFilter, messageThreadID int64) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchChatMessages", + "chat_id": chatID, + "query": query, + "sender": sender, + "from_message_id": fromMessageID, + "offset": offset, + "limit": limit, + "filter": filter, + "message_thread_id": messageThreadID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.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)). For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +// @param chatList Chat list in which to search messages; pass null to search in all chats regardless of their chat list. Only Main and Archive chat lists are supported +// @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. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +// @param filter Filter for message content in the search results; searchMessagesFilterCall, searchMessagesFilterMissedCall, searchMessagesFilterMention, searchMessagesFilterUnreadMention, searchMessagesFilterFailedToSend and searchMessagesFilterPinned are unsupported in this function +// @param minDate If not 0, the minimum date of the messages to return +// @param maxDate If not 0, the maximum date of the messages to return +func (client *Client) SearchMessages(chatList tdlib.ChatList, query string, offsetDate int32, offsetChatID int64, offsetMessageID int64, limit int32, filter tdlib.SearchMessagesFilter, minDate int32, maxDate int32) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchMessages", + "chat_list": chatList, + "query": query, + "offset_date": offsetDate, + "offset_chat_id": offsetChatID, + "offset_message_id": offsetMessageID, + "limit": limit, + "filter": filter, + "min_date": minDate, + "max_date": maxDate, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, 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 TDLib +// @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. For optimal performance, the number of returned messages is chosen by TDLib and can be smaller than the specified limit +// @param onlyMissed If true, returns only messages with missed calls +func (client *Client) SearchCallMessages(fromMessageID int64, limit int32, onlyMissed bool) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.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 The maximum number of messages to be returned +func (client *Client) SearchChatRecentLocationMessages(chatID int64, limit int32) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchChatRecentLocationMessages", + "chat_id": chatID, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// GetActiveLiveLocationMessages Returns all active live locations that should be updated by the application. The list is persistent across application restarts only if the message database is used +func (client *Client) GetActiveLiveLocationMessages() (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getActiveLiveLocationMessages", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// GetChatScheduledMessages Returns all scheduled 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 +func (client *Client) GetChatScheduledMessages(chatID int64) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatScheduledMessages", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// SendMessageAlbum Sends 2-10 messages grouped together into an album. Currently only audio, document, photo and video messages can be grouped into an album. Documents and audio files can be only grouped in an album with messages of the same type. Returns sent messages +// @param chatID Target chat +// @param messageThreadID If not 0, a message thread identifier in which the messages will be sent +// @param replyToMessageID Identifier of a message to reply to or 0 +// @param options Options to be used to send the messages +// @param inputMessageContents Contents of messages to be sent. At most 10 messages can be added to an album +func (client *Client) SendMessageAlbum(chatID int64, messageThreadID int64, replyToMessageID int64, options *tdlib.MessageSendOptions, inputMessageContents []tdlib.InputMessageContent) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendMessageAlbum", + "chat_id": chatID, + "message_thread_id": messageThreadID, + "reply_to_message_id": replyToMessageID, + "options": options, + "input_message_contents": inputMessageContents, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, 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. Message identifiers must be in a strictly increasing order. At most 100 messages can be forwarded simultaneously +// @param options Options to be used to send the messages +// @param sendCopy If true, content of the messages will be copied without links to the original messages. Always true if the messages are forwarded to a secret chat +// @param removeCaption If true, media caption of message copies will be removed. Ignored if send_copy is false +// @param onlyPreview If true, messages will not be forwarded and instead fake messages will be returned +func (client *Client) ForwardMessages(chatID int64, fromChatID int64, messageIDs []int64, options *tdlib.MessageSendOptions, sendCopy bool, removeCaption bool, onlyPreview bool) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "forwardMessages", + "chat_id": chatID, + "from_chat_id": fromChatID, + "message_ids": messageIDs, + "options": options, + "send_copy": sendCopy, + "remove_caption": removeCaption, + "only_preview": onlyPreview, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} + +// ResendMessages Resends messages which failed to send. Can be called only for messages for which messageSendingStateFailed.can_retry is true and after specified in messageSendingStateFailed.retry_after time passed. If a message is re-sent, the corresponding failed to send message is deleted. Returns the sent messages in the same order as the message identifiers passed in message_ids. If a message can't be re-sent, null will be returned instead of the message +// @param chatID Identifier of the chat to send messages +// @param messageIDs Identifiers of the messages to resend. Message identifiers must be in a strictly increasing order +func (client *Client) ResendMessages(chatID int64, messageIDs []int64) (*tdlib.Messages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resendMessages", + "chat_id": chatID, + "message_ids": messageIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var messages tdlib.Messages + err = json.Unmarshal(result.Raw, &messages) + return &messages, err + +} diff --git a/client/networkStatistics.go b/client/networkStatistics.go new file mode 100644 index 0000000..08b6c42 --- /dev/null +++ b/client/networkStatistics.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.NetworkStatistics, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getNetworkStatistics", + "only_current": onlyCurrent, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var networkStatistics tdlib.NetworkStatistics + err = json.Unmarshal(result.Raw, &networkStatistics) + return &networkStatistics, err + +} diff --git a/client/ok.go b/client/ok.go new file mode 100644 index 0000000..fab8bea --- /dev/null +++ b/client/ok.go @@ -0,0 +1,4759 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// SetTdlibParameters Sets the parameters for TDLib initialization. Works only when the current authorization state is authorizationStateWaitTdlibParameters +// @param parameters Parameters +func (client *Client) SetTdlibParameters(parameters *tdlib.TdlibParameters) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setTdlibParameters", + "parameters": parameters, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkDatabaseEncryptionKey", + "encryption_key": encryptionKey, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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, or if there is no pending authentication query and the current authorization state is authorizationStateWaitCode, authorizationStateWaitRegistration, or authorizationStateWaitPassword +// @param phoneNumber The phone number of the user, in international format +// @param settings Settings for the authentication of the user's phone number +func (client *Client) SetAuthenticationPhoneNumber(phoneNumber string, settings *tdlib.PhoneNumberAuthenticationSettings) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setAuthenticationPhoneNumber", + "phone_number": phoneNumber, + "settings": settings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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, the next_code_type of the result is not null and the server-specified timeout has passed +func (client *Client) ResendAuthenticationCode() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resendAuthenticationCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 +func (client *Client) CheckAuthenticationCode(code string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkAuthenticationCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RequestQrCodeAuthentication Requests QR code authentication by scanning a QR code on another logged in device. Works only when the current authorization state is authorizationStateWaitPhoneNumber, or if there is no pending authentication query and the current authorization state is authorizationStateWaitCode, authorizationStateWaitRegistration, or authorizationStateWaitPassword +// @param otherUserIDs List of user identifiers of other users currently using the application +func (client *Client) RequestQrCodeAuthentication(otherUserIDs []int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "requestQrCodeAuthentication", + "other_user_ids": otherUserIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RegisterUser Finishes user registration. Works only when the current authorization state is authorizationStateWaitRegistration +// @param firstName The first name of the user; 1-64 characters +// @param lastName The last name of the user; 0-64 characters +func (client *Client) RegisterUser(firstName string, lastName string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "registerUser", + "first_name": firstName, + "last_name": lastName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkAuthenticationPassword", + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "requestAuthenticationPasswordRecovery", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckAuthenticationPasswordRecoveryCode Checks whether a password recovery code sent to an email address is valid. Works only when the current authorization state is authorizationStateWaitPassword +// @param recoveryCode Recovery code to check +func (client *Client) CheckAuthenticationPasswordRecoveryCode(recoveryCode string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkAuthenticationPasswordRecoveryCode", + "recovery_code": recoveryCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 +// @param newPassword New password of the user; may be empty to remove the password +// @param newHint New password hint; may be empty +func (client *Client) RecoverAuthenticationPassword(recoveryCode string, newPassword string, newHint string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "recoverAuthenticationPassword", + "recovery_code": recoveryCode, + "new_password": newPassword, + "new_hint": newHint, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkAuthenticationBotToken", + "token": token, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var okDummy tdlib.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() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "logOut", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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. Can be called before initialization +func (client *Client) Close() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "close", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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. Can be called before authorization +func (client *Client) Destroy() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "destroy", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setDatabaseEncryptionKey", + "new_encryption_key": newEncryptionKey, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckPasswordRecoveryCode Checks whether a 2-step verification password recovery code sent to an email address is valid +// @param recoveryCode Recovery code to check +func (client *Client) CheckPasswordRecoveryCode(recoveryCode string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkPasswordRecoveryCode", + "recovery_code": recoveryCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CancelPasswordReset Cancels reset of 2-step verification password. The method can be called if passwordState.pending_reset_date > 0 +func (client *Client) CancelPasswordReset() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "cancelPasswordReset", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// LoadChats Loads more chats from a chat list. The loaded chats and their positions in the chat list will be sent through updates. Chats are sorted by the pair (chat.position.order, chat.id) in descending order. Returns a 404 error if all chats has been loaded +// @param chatList The chat list in which to load chats +// @param limit The maximum number of chats to be loaded. For optimal performance, the number of loaded chats is chosen by TDLib and can be smaller than the specified limit, even if the end of the list is not reached +func (client *Client) LoadChats(chatList tdlib.ChatList, limit int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "loadChats", + "chat_list": chatList, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.TopChatCategory, chatID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeTopChat", + "category": category, + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addRecentlyFoundChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeRecentlyFoundChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ClearRecentlyFoundChats Clears the list of recently found chats +func (client *Client) ClearRecentlyFoundChats() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "clearRecentlyFoundChats", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckCreatedPublicChatsLimit Checks whether the maximum number of owned public chats has been reached. Returns corresponding error if the limit was reached +// @param typeParam Type of the public chats, for which to check the limit +func (client *Client) CheckCreatedPublicChatsLimit(typeParam tdlib.PublicChatType) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkCreatedPublicChatsLimit", + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteChatHistory Deletes all messages in the chat. Use Chat.can_be_deleted_only_for_self and Chat.can_be_deleted_for_all_users fields to find whether and how the method can be applied to the chat +// @param chatID Chat identifier +// @param removeFromChatList Pass true if the chat should be removed from the chat list +// @param revoke Pass true to try to delete chat history for all users +func (client *Client) DeleteChatHistory(chatID int64, removeFromChatList bool, revoke bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteChatHistory", + "chat_id": chatID, + "remove_from_chat_list": removeFromChatList, + "revoke": revoke, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var okDummy tdlib.Ok + err = json.Unmarshal(result.Raw, &okDummy) + return &okDummy, err + +} + +// DeleteChat Deletes a chat along with all messages in the corresponding chat for all chat members; requires owner privileges. For group chats this will release the username and remove all members. Chats with more than 1000 members can't be deleted using this method +// @param chatID Chat identifier +func (client *Client) DeleteChat(chatID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteAllCallMessages Deletes all call messages +// @param revoke Pass true to delete the messages for all users +func (client *Client) DeleteAllCallMessages(revoke bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteAllCallMessages", + "revoke": revoke, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var okDummy tdlib.Ok + err = json.Unmarshal(result.Raw, &okDummy) + return &okDummy, err + +} + +// ViewSponsoredMessage Informs TDLib that a sponsored message was viewed by the user +// @param chatID Identifier of the chat with the sponsored message +// @param sponsoredMessageID The identifier of the sponsored message being viewed +func (client *Client) ViewSponsoredMessage(chatID int64, sponsoredMessageID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "viewSponsoredMessage", + "chat_id": chatID, + "sponsored_message_id": sponsoredMessageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveNotification Removes an active notification from notification list. Needs to be called only if the notification is removed by the current user +// @param notificationGroupID Identifier of notification group to which the notification belongs +// @param notificationID Identifier of removed notification +func (client *Client) RemoveNotification(notificationGroupID int32, notificationID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeNotification", + "notification_group_id": notificationGroupID, + "notification_id": notificationID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveNotificationGroup Removes a group of active notifications. Needs to be called only if the notification group is removed by the current user +// @param notificationGroupID Notification group identifier +// @param maxNotificationID The maximum identifier of removed notifications +func (client *Client) RemoveNotificationGroup(notificationGroupID int32, maxNotificationID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeNotificationGroup", + "notification_group_id": notificationGroupID, + "max_notification_id": maxNotificationID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendChatScreenshotTakenNotification", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 messages for all chat members. Always true for supergroups, channels and secret chats +func (client *Client) DeleteMessages(chatID int64, messageIDs []int64, revoke bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var okDummy tdlib.Ok + err = json.Unmarshal(result.Raw, &okDummy) + return &okDummy, err + +} + +// DeleteChatMessagesFromUser Deletes all messages sent by the specified user to a chat. Supported only for supergroups; requires can_delete_messages administrator privileges +// @param chatID Chat identifier +// @param userID User identifier +func (client *Client) DeleteChatMessagesFromUser(chatID int64, userID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteChatMessagesFromUser", + "chat_id": chatID, + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.ReplyMarkup, inputMessageContent tdlib.InputMessageContent) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 +// @param heading The new direction in which the location moves, in degrees; 1-360. Pass 0 if unknown +// @param proximityAlertRadius The new maximum distance for proximity alerts, in meters (0-100000). Pass 0 if the notification is disabled +func (client *Client) EditInlineMessageLiveLocation(inlineMessageID string, replyMarkup tdlib.ReplyMarkup, location *tdlib.Location, heading int32, proximityAlertRadius int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "editInlineMessageLiveLocation", + "inline_message_id": inlineMessageID, + "reply_markup": replyMarkup, + "location": location, + "heading": heading, + "proximity_alert_radius": proximityAlertRadius, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 tdlib.ReplyMarkup, inputMessageContent tdlib.InputMessageContent) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 tdlib.ReplyMarkup, caption *tdlib.FormattedText) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 tdlib.ReplyMarkup) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "editInlineMessageReplyMarkup", + "inline_message_id": inlineMessageID, + "reply_markup": replyMarkup, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditMessageSchedulingState Edits the time when a scheduled message will be sent. Scheduling state of all messages in the same album or forwarded together with the message will be also changed +// @param chatID The chat the message belongs to +// @param messageID Identifier of the message +// @param schedulingState The new message scheduling state. Pass null to send the message immediately +func (client *Client) EditMessageSchedulingState(chatID int64, messageID int64, schedulingState tdlib.MessageSchedulingState) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "editMessageSchedulingState", + "chat_id": chatID, + "message_id": messageID, + "scheduling_state": schedulingState, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetPollAnswer Changes the user answer to a poll. A poll in quiz mode can be answered only once +// @param chatID Identifier of the chat to which the poll belongs +// @param messageID Identifier of the message containing the poll +// @param optionIDs 0-based identifiers of answer options, chosen by the user. User can choose more than 1 answer option only is the poll allows multiple answers +func (client *Client) SetPollAnswer(chatID int64, messageID int64, optionIDs []int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setPollAnswer", + "chat_id": chatID, + "message_id": messageID, + "option_ids": optionIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// StopPoll Stops a poll. A poll in a message can be stopped when the message has can_be_edited flag set +// @param chatID Identifier of the chat to which the poll belongs +// @param messageID Identifier of the message containing the poll +// @param replyMarkup The new message reply markup; for bots only +func (client *Client) StopPoll(chatID int64, messageID int64, replyMarkup tdlib.ReplyMarkup) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "stopPoll", + "chat_id": chatID, + "message_id": messageID, + "reply_markup": replyMarkup, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// HideSuggestedAction Hides a suggested action +// @param action Suggested action to hide +func (client *Client) HideSuggestedAction(action tdlib.SuggestedAction) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "hideSuggestedAction", + "action": action, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 *tdlib.JSONInt64, isPersonal bool, results []tdlib.InputInlineQueryResult, cacheTime int32, nextOffset string, switchPmText string, switchPmParameter string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 *tdlib.JSONInt64, text string, showAlert bool, uRL string, cacheTime int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 *tdlib.JSONInt64, shippingOptions []tdlib.ShippingOption, errorMessage string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 *tdlib.JSONInt64, errorMessage string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 int64, score int32, force bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteChatReplyMarkup", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 messageThreadID If not 0, a message thread identifier in which the action was performed +// @param action The action description +func (client *Client) SendChatAction(chatID int64, messageThreadID int64, action tdlib.ChatAction) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendChatAction", + "chat_id": chatID, + "message_thread_id": messageThreadID, + "action": action, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// OpenChat Informs TDLib that 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "openChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CloseChat Informs TDLib that 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "closeChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ViewMessages Informs TDLib that 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 messageThreadID If not 0, a message thread identifier in which the messages are being viewed +// @param messageIDs The identifiers of the messages being viewed +// @param forceRead True, if messages in closed chats should be marked as read by the request +func (client *Client) ViewMessages(chatID int64, messageThreadID int64, messageIDs []int64, forceRead bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "viewMessages", + "chat_id": chatID, + "message_thread_id": messageThreadID, + "message_ids": messageIDs, + "force_read": forceRead, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// OpenMessageContent Informs TDLib that 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "openMessageContent", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "readAllChatMentions", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddChatToList Adds a chat to a chat list. A chat can't be simultaneously in Main and Archive chat lists, so it is automatically removed from another one if needed +// @param chatID Chat identifier +// @param chatList The chat list. Use getChatListsToAddChat to get suitable chat lists +func (client *Client) AddChatToList(chatID int64, chatList tdlib.ChatList) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addChatToList", + "chat_id": chatID, + "chat_list": chatList, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteChatFilter Deletes existing chat filter +// @param chatFilterID Chat filter identifier +func (client *Client) DeleteChatFilter(chatFilterID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteChatFilter", + "chat_filter_id": chatFilterID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ReorderChatFilters Changes the order of chat filters +// @param chatFilterIDs Identifiers of chat filters in the new correct order +func (client *Client) ReorderChatFilters(chatFilterIDs []int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "reorderChatFilters", + "chat_filter_ids": chatFilterIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatTitle Changes the chat title. Supported only for basic groups, supergroups and channels. Requires can_change_info administrator right +// @param chatID Chat identifier +// @param title New title of the chat; 1-128 characters +func (client *Client) SetChatTitle(chatID int64, title string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatTitle", + "chat_id": chatID, + "title": title, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 can_change_info administrator right +// @param chatID Chat identifier +// @param photo New chat photo. Pass null to delete the chat photo +func (client *Client) SetChatPhoto(chatID int64, photo tdlib.InputChatPhoto) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatPhoto", + "chat_id": chatID, + "photo": photo, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatMessageTTLSetting Changes the message TTL setting (sets a new self-destruct timer) in a chat. Requires can_delete_messages administrator right in basic groups, supergroups and channels Message TTL setting of a chat with the current user (Saved Messages) and the chat 777000 (Telegram) can't be changed +// @param chatID Chat identifier +// @param tTL New TTL value, in seconds; must be one of 0, 86400, 7 * 86400, or 31 * 86400 unless the chat is secret +func (client *Client) SetChatMessageTTLSetting(chatID int64, tTL int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatMessageTtlSetting", + "chat_id": chatID, + "ttl": tTL, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatPermissions Changes the chat members permissions. Supported only for basic groups and supergroups. Requires can_restrict_members administrator right +// @param chatID Chat identifier +// @param permissions New non-administrator members permissions in the chat +func (client *Client) SetChatPermissions(chatID int64, permissions *tdlib.ChatPermissions) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatPermissions", + "chat_id": chatID, + "permissions": permissions, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatTheme Changes the chat theme. Supported only in private and secret chats +// @param chatID Chat identifier +// @param themeName Name of the new chat theme; may be empty to return the default theme +func (client *Client) SetChatTheme(chatID int64, themeName string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatTheme", + "chat_id": chatID, + "theme_name": themeName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatDraftMessage Changes the draft message in a chat +// @param chatID Chat identifier +// @param messageThreadID If not 0, a message thread identifier in which the draft was changed +// @param draftMessage New draft message; may be null +func (client *Client) SetChatDraftMessage(chatID int64, messageThreadID int64, draftMessage *tdlib.DraftMessage) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatDraftMessage", + "chat_id": chatID, + "message_thread_id": messageThreadID, + "draft_message": draftMessage, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatNotificationSettings Changes the notification settings of a chat. Notification settings of a chat with the current user (Saved Messages) can't be changed +// @param chatID Chat identifier +// @param notificationSettings New notification settings for the chat. If the chat is muted for more than 1 week, it is considered to be muted forever +func (client *Client) SetChatNotificationSettings(chatID int64, notificationSettings *tdlib.ChatNotificationSettings) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatNotificationSettings", + "chat_id": chatID, + "notification_settings": notificationSettings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleChatDefaultDisableNotification", + "chat_id": chatID, + "default_disable_notification": defaultDisableNotification, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatClientData Changes application-specific data associated with a chat +// @param chatID Chat identifier +// @param clientData New value of client_data +func (client *Client) SetChatClientData(chatID int64, clientData string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatClientData", + "chat_id": chatID, + "client_data": clientData, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatDescription Changes information about a chat. Available for basic groups, supergroups, and channels. Requires can_change_info administrator right +// @param chatID Identifier of the chat +// @param description New chat description; 0-255 characters +func (client *Client) SetChatDescription(chatID int64, description string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatDescription", + "chat_id": chatID, + "description": description, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatDiscussionGroup Changes the discussion group of a channel chat; requires can_change_info administrator right in the channel if it is specified +// @param chatID Identifier of the channel chat. Pass 0 to remove a link from the supergroup passed in the second argument to a linked channel chat (requires can_pin_messages rights in the supergroup) +// @param discussionChatID Identifier of a new channel's discussion group. Use 0 to remove the discussion group. Use the method getSuitableDiscussionChats to find all suitable groups. Basic group chats must be first upgraded to supergroup chats. If new chat members don't have access to old messages in the supergroup, then toggleSupergroupIsAllHistoryAvailable must be used first to change that +func (client *Client) SetChatDiscussionGroup(chatID int64, discussionChatID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatDiscussionGroup", + "chat_id": chatID, + "discussion_chat_id": discussionChatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatLocation Changes the location of a chat. Available only for some location-based supergroups, use supergroupFullInfo.can_set_location to check whether the method is allowed to use +// @param chatID Chat identifier +// @param location New location for the chat; must be valid and not null +func (client *Client) SetChatLocation(chatID int64, location *tdlib.ChatLocation) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatLocation", + "chat_id": chatID, + "location": location, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetChatSlowModeDelay Changes the slow mode delay of a chat. Available only for supergroups; requires can_restrict_members rights +// @param chatID Chat identifier +// @param slowModeDelay New slow mode delay for the chat; must be one of 0, 10, 30, 60, 300, 900, 3600 +func (client *Client) SetChatSlowModeDelay(chatID int64, slowModeDelay int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatSlowModeDelay", + "chat_id": chatID, + "slow_mode_delay": slowModeDelay, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// PinChatMessage Pins a message in a chat; requires can_pin_messages rights or can_edit_messages rights in the channel +// @param chatID Identifier of the chat +// @param messageID Identifier of the new pinned message +// @param disableNotification True, if there should be no notification about the pinned message. Notifications are always disabled in channels and private chats +// @param onlyForSelf True, if the message needs to be pinned for one side only; private chats only +func (client *Client) PinChatMessage(chatID int64, messageID int64, disableNotification bool, onlyForSelf bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "pinChatMessage", + "chat_id": chatID, + "message_id": messageID, + "disable_notification": disableNotification, + "only_for_self": onlyForSelf, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// UnpinChatMessage Removes a pinned message from a chat; requires can_pin_messages rights in the group or can_edit_messages rights in the channel +// @param chatID Identifier of the chat +// @param messageID Identifier of the removed pinned message +func (client *Client) UnpinChatMessage(chatID int64, messageID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "unpinChatMessage", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// UnpinAllChatMessages Removes all pinned messages from a chat; requires can_pin_messages rights in the group or can_edit_messages rights in the channel +// @param chatID Identifier of the chat +func (client *Client) UnpinAllChatMessages(chatID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "unpinAllChatMessages", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// JoinChat Adds the 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "joinChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// LeaveChat Removes the 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "leaveChat", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 +// @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 100. Ignored for supergroups and channels +func (client *Client) AddChatMember(chatID int64, userID int64, forwardLimit int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddChatMembers Adds multiple new members to a chat. Currently this method is only available for supergroups and channels. This method can't be used to join a chat. Members can't be added to a channel if it has more than 200 members +// @param chatID Chat identifier +// @param userIDs Identifiers of the users to be added to the chat. The maximum number of added users is 20 for supergroups and 100 for channels +func (client *Client) AddChatMembers(chatID int64, userIDs []int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addChatMembers", + "chat_id": chatID, + "user_ids": userIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 and transferring chat ownership; instead, use addChatMember or transferChatOwnership +// @param chatID Chat identifier +// @param memberID Member identifier. Chats can be only banned and unbanned in supergroups and channels +// @param status The new status of the member in the chat +func (client *Client) SetChatMemberStatus(chatID int64, memberID tdlib.MessageSender, status tdlib.ChatMemberStatus) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setChatMemberStatus", + "chat_id": chatID, + "member_id": memberID, + "status": status, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// BanChatMember Bans a member in a chat. Members can't be banned in private or secret chats. In supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first +// @param chatID Chat identifier +// @param memberID Member identifier +// @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. Ignored in basic groups +// @param revokeMessages Pass true to delete all messages in the chat for the user that is being removed. Always true for supergroups and channels +func (client *Client) BanChatMember(chatID int64, memberID tdlib.MessageSender, bannedUntilDate int32, revokeMessages bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "banChatMember", + "chat_id": chatID, + "member_id": memberID, + "banned_until_date": bannedUntilDate, + "revoke_messages": revokeMessages, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var okDummy tdlib.Ok + err = json.Unmarshal(result.Raw, &okDummy) + return &okDummy, err + +} + +// TransferChatOwnership Changes the owner of a chat. The current user must be a current owner of the chat. Use the method canTransferOwnership to check whether the ownership can be transferred from the current session. Available only for supergroups and channel chats +// @param chatID Chat identifier +// @param userID Identifier of the user to which transfer the ownership. The ownership can't be transferred to a bot or to a deleted user +// @param password The password of the current user +func (client *Client) TransferChatOwnership(chatID int64, userID int64, password string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "transferChatOwnership", + "chat_id": chatID, + "user_id": userID, + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "clearAllDraftMessages", + "exclude_secret_chats": excludeSecretChats, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.NotificationSettingsScope, notificationSettings *tdlib.ScopeNotificationSettings) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setScopeNotificationSettings", + "scope": scope, + "notification_settings": notificationSettings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resetAllNotificationSettings", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleChatIsPinned Changes the pinned state of a chat. There can be up to GetOption("pinned_chat_count_max")/GetOption("pinned_archived_chat_count_max") pinned non-secret chats and the same number of secret chats in the main/arhive chat list +// @param chatList Chat list in which to change the pinned state of the chat +// @param chatID Chat identifier +// @param isPinned True, if the chat is pinned +func (client *Client) ToggleChatIsPinned(chatList tdlib.ChatList, chatID int64, isPinned bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleChatIsPinned", + "chat_list": chatList, + "chat_id": chatID, + "is_pinned": isPinned, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetPinnedChats Changes the order of pinned chats +// @param chatList Chat list in which to change the order of pinned chats +// @param chatIDs The new list of pinned chats +func (client *Client) SetPinnedChats(chatList tdlib.ChatList, chatIDs []int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setPinnedChats", + "chat_list": chatList, + "chat_ids": chatIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "cancelDownloadFile", + "file_id": fileID, + "only_if_pending": onlyIfPending, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "cancelUploadFile", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// WriteGeneratedFilePart Writes a part of a generated file. This method is intended to be used only if the application has no direct access to TDLib's file system, because it is usually slower than a direct write to the destination file +// @param generationID The identifier of the generation process +// @param offset The offset from which to write the data to the file +// @param data The data to write +func (client *Client) WriteGeneratedFilePart(generationID *tdlib.JSONInt64, offset int32, data []byte) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "writeGeneratedFilePart", + "generation_id": generationID, + "offset": offset, + "data": data, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetFileGenerationProgress Informs TDLib on a file generation progress +// @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 *tdlib.JSONInt64, expectedSize int32, localPrefixSize int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 *tdlib.JSONInt64, error *tdlib.Error) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "finishFileGeneration", + "generation_id": generationID, + "error": error, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteFile", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ImportMessages Imports messages exported from another app +// @param chatID Identifier of a chat to which the messages will be imported. It must be an identifier of a private chat with a mutual contact or an identifier of a supergroup chat with can_change_info administrator right +// @param messageFile File with messages to import. Only inputFileLocal and inputFileGenerated are supported. The file must not be previously uploaded +// @param attachedFiles Files used in the imported messages. Only inputFileLocal and inputFileGenerated are supported. The files must not be previously uploaded +func (client *Client) ImportMessages(chatID int64, messageFile tdlib.InputFile, attachedFiles []tdlib.InputFile) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "importMessages", + "chat_id": chatID, + "message_file": messageFile, + "attached_files": attachedFiles, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteRevokedChatInviteLink Deletes revoked chat invite links. Requires administrator privileges and can_invite_users right in the chat for own links and owner privileges for other links +// @param chatID Chat identifier +// @param inviteLink Invite link to revoke +func (client *Client) DeleteRevokedChatInviteLink(chatID int64, inviteLink string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteRevokedChatInviteLink", + "chat_id": chatID, + "invite_link": inviteLink, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteAllRevokedChatInviteLinks Deletes all revoked chat invite links created by a given chat administrator. Requires administrator privileges and can_invite_users right in the chat for own links and owner privileges for other links +// @param chatID Chat identifier +// @param creatorUserID User identifier of a chat administrator, which links will be deleted. Must be an identifier of the current user for non-owner +func (client *Client) DeleteAllRevokedChatInviteLinks(chatID int64, creatorUserID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteAllRevokedChatInviteLinks", + "chat_id": chatID, + "creator_user_id": creatorUserID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AcceptCall Accepts an incoming call +// @param callID Call identifier +// @param protocol Description of the call protocols supported by the application +func (client *Client) AcceptCall(callID int32, protocol *tdlib.CallProtocol) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "acceptCall", + "call_id": callID, + "protocol": protocol, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendCallSignalingData Sends call signaling data +// @param callID Call identifier +// @param data The data +func (client *Client) SendCallSignalingData(callID int32, data []byte) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendCallSignalingData", + "call_id": callID, + "data": data, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 isVideo True, if the call was a video call +// @param connectionID Identifier of the connection used during the call +func (client *Client) DiscardCall(callID int32, isDisconnected bool, duration int32, isVideo bool, connectionID *tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "discardCall", + "call_id": callID, + "is_disconnected": isDisconnected, + "duration": duration, + "is_video": isVideo, + "connection_id": connectionID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 +// @param problems List of the exact types of problems with the call, specified by the user +func (client *Client) SendCallRating(callID int32, rating int32, comment string, problems []tdlib.CallProblem) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendCallRating", + "call_id": callID, + "rating": rating, + "comment": comment, + "problems": problems, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendCallDebugInformation", + "call_id": callID, + "debug_information": debugInformation, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetVoiceChatDefaultParticipant Changes default participant identifier, which can be used to join voice chats in a chat +// @param chatID Chat identifier +// @param defaultParticipantID Default group call participant identifier to join the voice chats +func (client *Client) SetVoiceChatDefaultParticipant(chatID int64, defaultParticipantID tdlib.MessageSender) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setVoiceChatDefaultParticipant", + "chat_id": chatID, + "default_participant_id": defaultParticipantID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// StartScheduledGroupCall Starts a scheduled group call +// @param groupCallID Group call identifier +func (client *Client) StartScheduledGroupCall(groupCallID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "startScheduledGroupCall", + "group_call_id": groupCallID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleGroupCallEnabledStartNotification Toggles whether the current user will receive a notification when the group call will start; scheduled group calls only +// @param groupCallID Group call identifier +// @param enabledStartNotification New value of the enabled_start_notification setting +func (client *Client) ToggleGroupCallEnabledStartNotification(groupCallID int32, enabledStartNotification bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleGroupCallEnabledStartNotification", + "group_call_id": groupCallID, + "enabled_start_notification": enabledStartNotification, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleGroupCallScreenSharingIsPaused Pauses or unpauses screen sharing in a joined group call +// @param groupCallID Group call identifier +// @param isPaused True if screen sharing is paused +func (client *Client) ToggleGroupCallScreenSharingIsPaused(groupCallID int32, isPaused bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleGroupCallScreenSharingIsPaused", + "group_call_id": groupCallID, + "is_paused": isPaused, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EndGroupCallScreenSharing Ends screen sharing in a joined group call +// @param groupCallID Group call identifier +func (client *Client) EndGroupCallScreenSharing(groupCallID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "endGroupCallScreenSharing", + "group_call_id": groupCallID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetGroupCallTitle Sets group call title. Requires groupCall.can_be_managed group call flag +// @param groupCallID Group call identifier +// @param title New group call title; 1-64 characters +func (client *Client) SetGroupCallTitle(groupCallID int32, title string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setGroupCallTitle", + "group_call_id": groupCallID, + "title": title, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleGroupCallMuteNewParticipants Toggles whether new participants of a group call can be unmuted only by administrators of the group call. Requires groupCall.can_change_mute_new_participants group call flag +// @param groupCallID Group call identifier +// @param muteNewParticipants New value of the mute_new_participants setting +func (client *Client) ToggleGroupCallMuteNewParticipants(groupCallID int32, muteNewParticipants bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleGroupCallMuteNewParticipants", + "group_call_id": groupCallID, + "mute_new_participants": muteNewParticipants, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RevokeGroupCallInviteLink Revokes invite link for a group call. Requires groupCall.can_be_managed group call flag +// @param groupCallID Group call identifier +func (client *Client) RevokeGroupCallInviteLink(groupCallID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "revokeGroupCallInviteLink", + "group_call_id": groupCallID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// InviteGroupCallParticipants Invites users to an active group call. Sends a service message of type messageInviteToGroupCall for voice chats +// @param groupCallID Group call identifier +// @param userIDs User identifiers. At most 10 users can be invited simultaneously +func (client *Client) InviteGroupCallParticipants(groupCallID int32, userIDs []int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "inviteGroupCallParticipants", + "group_call_id": groupCallID, + "user_ids": userIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// StartGroupCallRecording Starts recording of an active group call. Requires groupCall.can_be_managed group call flag +// @param groupCallID Group call identifier +// @param title Group call recording title; 0-64 characters +// @param recordVideo Pass true to record a video file instead of an audio file +// @param usePortraitOrientation Pass true to use portrait orientation for video instead of landscape one +func (client *Client) StartGroupCallRecording(groupCallID int32, title string, recordVideo bool, usePortraitOrientation bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "startGroupCallRecording", + "group_call_id": groupCallID, + "title": title, + "record_video": recordVideo, + "use_portrait_orientation": usePortraitOrientation, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EndGroupCallRecording Ends recording of an active group call. Requires groupCall.can_be_managed group call flag +// @param groupCallID Group call identifier +func (client *Client) EndGroupCallRecording(groupCallID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "endGroupCallRecording", + "group_call_id": groupCallID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleGroupCallIsMyVideoPaused Toggles whether current user's video is paused +// @param groupCallID Group call identifier +// @param isMyVideoPaused Pass true if the current user's video is paused +func (client *Client) ToggleGroupCallIsMyVideoPaused(groupCallID int32, isMyVideoPaused bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleGroupCallIsMyVideoPaused", + "group_call_id": groupCallID, + "is_my_video_paused": isMyVideoPaused, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleGroupCallIsMyVideoEnabled Toggles whether current user's video is enabled +// @param groupCallID Group call identifier +// @param isMyVideoEnabled Pass true if the current user's video is enabled +func (client *Client) ToggleGroupCallIsMyVideoEnabled(groupCallID int32, isMyVideoEnabled bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleGroupCallIsMyVideoEnabled", + "group_call_id": groupCallID, + "is_my_video_enabled": isMyVideoEnabled, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetGroupCallParticipantIsSpeaking Informs TDLib that speaking state of a participant of an active group has changed +// @param groupCallID Group call identifier +// @param audioSource Group call participant's synchronization audio source identifier, or 0 for the current user +// @param isSpeaking True, if the user is speaking +func (client *Client) SetGroupCallParticipantIsSpeaking(groupCallID int32, audioSource int32, isSpeaking bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setGroupCallParticipantIsSpeaking", + "group_call_id": groupCallID, + "audio_source": audioSource, + "is_speaking": isSpeaking, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleGroupCallParticipantIsMuted Toggles whether a participant of an active group call is muted, unmuted, or allowed to unmute themselves +// @param groupCallID Group call identifier +// @param participantID Participant identifier +// @param isMuted Pass true if the user must be muted and false otherwise +func (client *Client) ToggleGroupCallParticipantIsMuted(groupCallID int32, participantID tdlib.MessageSender, isMuted bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleGroupCallParticipantIsMuted", + "group_call_id": groupCallID, + "participant_id": participantID, + "is_muted": isMuted, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetGroupCallParticipantVolumeLevel Changes volume level of a participant of an active group call. If the current user can manage the group call, then the participant's volume level will be changed for all users with default volume level +// @param groupCallID Group call identifier +// @param participantID Participant identifier +// @param volumeLevel New participant's volume level; 1-20000 in hundreds of percents +func (client *Client) SetGroupCallParticipantVolumeLevel(groupCallID int32, participantID tdlib.MessageSender, volumeLevel int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setGroupCallParticipantVolumeLevel", + "group_call_id": groupCallID, + "participant_id": participantID, + "volume_level": volumeLevel, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleGroupCallParticipantIsHandRaised Toggles whether a group call participant hand is rased +// @param groupCallID Group call identifier +// @param participantID Participant identifier +// @param isHandRaised Pass true if the user's hand should be raised. Only self hand can be raised. Requires groupCall.can_be_managed group call flag to lower other's hand +func (client *Client) ToggleGroupCallParticipantIsHandRaised(groupCallID int32, participantID tdlib.MessageSender, isHandRaised bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleGroupCallParticipantIsHandRaised", + "group_call_id": groupCallID, + "participant_id": participantID, + "is_hand_raised": isHandRaised, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// LoadGroupCallParticipants Loads more participants of a group call. The loaded participants will be received through updates. Use the field groupCall.loaded_all_participants to check whether all participants has already been loaded +// @param groupCallID Group call identifier. The group call must be previously received through getGroupCall and must be joined or being joined +// @param limit The maximum number of participants to load +func (client *Client) LoadGroupCallParticipants(groupCallID int32, limit int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "loadGroupCallParticipants", + "group_call_id": groupCallID, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// LeaveGroupCall Leaves a group call +// @param groupCallID Group call identifier +func (client *Client) LeaveGroupCall(groupCallID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "leaveGroupCall", + "group_call_id": groupCallID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DiscardGroupCall Discards a group call. Requires groupCall.can_be_managed +// @param groupCallID Group call identifier +func (client *Client) DiscardGroupCall(groupCallID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "discardGroupCall", + "group_call_id": groupCallID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleMessageSenderIsBlocked Changes the block state of a message sender. Currently, only users and supergroup chats can be blocked +// @param sender Message Sender +// @param isBlocked New value of is_blocked +func (client *Client) ToggleMessageSenderIsBlocked(sender tdlib.MessageSender, isBlocked bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleMessageSenderIsBlocked", + "sender": sender, + "is_blocked": isBlocked, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// BlockMessageSenderFromReplies Blocks an original sender of a message in the Replies chat +// @param messageID The identifier of an incoming message in the Replies chat +// @param deleteMessage Pass true if the message must be deleted +// @param deleteAllMessages Pass true if all messages from the same sender must be deleted +// @param reportSpam Pass true if the sender must be reported to the Telegram moderators +func (client *Client) BlockMessageSenderFromReplies(messageID int64, deleteMessage bool, deleteAllMessages bool, reportSpam bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "blockMessageSenderFromReplies", + "message_id": messageID, + "delete_message": deleteMessage, + "delete_all_messages": deleteAllMessages, + "report_spam": reportSpam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddContact Adds a user to the contact list or edits an existing contact by their user identifier +// @param contact The contact to add or edit; phone number can be empty and needs to be specified only if known, vCard is ignored +// @param sharePhoneNumber True, if the new contact needs to be allowed to see current user's phone number. A corresponding rule to userPrivacySettingShowPhoneNumber will be added if needed. Use the field UserFullInfo.need_phone_number_privacy_exception to check whether the current user needs to be asked to share their phone number +func (client *Client) AddContact(contact *tdlib.Contact, sharePhoneNumber bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addContact", + "contact": contact, + "share_phone_number": sharePhoneNumber, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveContacts Removes users from the contact list +// @param userIDs Identifiers of users to be deleted +func (client *Client) RemoveContacts(userIDs []int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeContacts", + "user_ids": userIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ClearImportedContacts Clears all imported contacts, contact list remains unchanged +func (client *Client) ClearImportedContacts() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "clearImportedContacts", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SharePhoneNumber Shares the phone number of the current user with a mutual contact. Supposed to be called when the user clicks on chatActionBarSharePhoneNumber +// @param userID Identifier of the user with whom to share the phone number. The user must be a mutual contact +func (client *Client) SharePhoneNumber(userID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sharePhoneNumber", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 *tdlib.JSONInt64, isInstalled bool, isArchived bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 []tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "viewTrendingStickerSets", + "sticker_set_ids": stickerSetIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 []tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "reorderInstalledStickerSets", + "is_masks": isMasks, + "sticker_set_ids": stickerSetIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.InputFile) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeRecentSticker", + "is_attached": isAttached, + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "clearRecentStickers", + "is_attached": isAttached, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.InputFile) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addFavoriteSticker", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 tdlib.InputFile) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeFavoriteSticker", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.InputFile) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addSavedAnimation", + "animation": animation, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 tdlib.InputFile) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeSavedAnimation", + "animation": animation, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveRecentHashtag Removes a hashtag from the list of recently used hashtags +// @param hashtag Hashtag to delete +func (client *Client) RemoveRecentHashtag(hashtag string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeRecentHashtag", + "hashtag": hashtag, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetProfilePhoto Changes a profile photo for the current user +// @param photo Profile photo to set +func (client *Client) SetProfilePhoto(photo tdlib.InputChatPhoto) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setProfilePhoto", + "photo": photo, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteProfilePhoto Deletes a profile photo +// @param profilePhotoID Identifier of the profile photo to delete +func (client *Client) DeleteProfilePhoto(profilePhotoID *tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteProfilePhoto", + "profile_photo_id": profilePhotoID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetName Changes the first and last name of the current user +// @param firstName The new value of the first name for the current user; 1-64 characters +// @param lastName The new value of the optional last name for the current user; 0-64 characters +func (client *Client) SetName(firstName string, lastName string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setName", + "first_name": firstName, + "last_name": lastName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setBio", + "bio": bio, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetUsername Changes the username of the current user +// @param username The new value of the username. Use an empty string to remove the username +func (client *Client) SetUsername(username string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setUsername", + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetLocation Changes the location of the current user. Needs to be called if GetOption("is_location_visible") is true and location changes for more than 1 kilometer +// @param location The new location of the user +func (client *Client) SetLocation(location *tdlib.Location) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setLocation", + "location": location, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkChangePhoneNumberCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetCommands Sets the list of commands supported by the bot for the given user scope and language; for bots only +// @param scope The scope to which the commands are relevant +// @param languageCode A two-letter ISO 639-1 country code. If empty, the commands will be applied to all users from the given scope, for which language there are no dedicated commands +// @param commands List of the bot's commands +func (client *Client) SetCommands(scope tdlib.BotCommandScope, languageCode string, commands []tdlib.BotCommand) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setCommands", + "scope": scope, + "language_code": languageCode, + "commands": commands, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteCommands Deletes commands supported by the bot for the given user scope and language; for bots only +// @param scope The scope to which the commands are relevant +// @param languageCode A two-letter ISO 639-1 country code or an empty string +func (client *Client) DeleteCommands(scope tdlib.BotCommandScope, languageCode string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteCommands", + "scope": scope, + "language_code": languageCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TerminateSession Terminates a session of the current user +// @param sessionID Session identifier +func (client *Client) TerminateSession(sessionID *tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "terminateSession", + "session_id": sessionID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TerminateAllOtherSessions Terminates all other sessions of the current user +func (client *Client) TerminateAllOtherSessions() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "terminateAllOtherSessions", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DisconnectWebsite Disconnects website from the current user's Telegram account +// @param websiteID Website identifier +func (client *Client) DisconnectWebsite(websiteID *tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "disconnectWebsite", + "website_id": websiteID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "disconnectAllWebsites", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetSupergroupUsername Changes the username of a supergroup or channel, requires owner 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 int64, username string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setSupergroupUsername", + "supergroup_id": supergroupID, + "username": username, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetSupergroupStickerSet Changes the sticker set of a supergroup; requires can_change_info administrator right +// @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 int64, stickerSetID *tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setSupergroupStickerSet", + "supergroup_id": supergroupID, + "sticker_set_id": stickerSetID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleSupergroupSignMessages Toggles sender signatures messages sent in a channel; requires can_change_info administrator right +// @param supergroupID Identifier of the channel +// @param signMessages New value of sign_messages +func (client *Client) ToggleSupergroupSignMessages(supergroupID int64, signMessages bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleSupergroupSignMessages", + "supergroup_id": supergroupID, + "sign_messages": signMessages, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 can_change_info administrator right +// @param supergroupID The identifier of the supergroup +// @param isAllHistoryAvailable The new value of is_all_history_available +func (client *Client) ToggleSupergroupIsAllHistoryAvailable(supergroupID int64, isAllHistoryAvailable bool) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ToggleSupergroupIsBroadcastGroup Upgrades supergroup to a broadcast group; requires owner privileges in the supergroup +// @param supergroupID Identifier of the supergroup +func (client *Client) ToggleSupergroupIsBroadcastGroup(supergroupID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "toggleSupergroupIsBroadcastGroup", + "supergroup_id": supergroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 int64, userID int64, messageIDs []int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CloseSecretChat Closes a secret chat, effectively transferring its state to secretChatStateClosed +// @param secretChatID Secret chat identifier +func (client *Client) CloseSecretChat(secretChatID int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "closeSecretChat", + "secret_chat_id": secretChatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteSavedOrderInfo Deletes saved order info +func (client *Client) DeleteSavedOrderInfo() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteSavedOrderInfo", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeleteSavedCredentials Deletes saved credentials for all payment provider bots +func (client *Client) DeleteSavedCredentials() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteSavedCredentials", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveBackground Removes background from the list of installed backgrounds +// @param backgroundID The background identifier +func (client *Client) RemoveBackground(backgroundID *tdlib.JSONInt64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeBackground", + "background_id": backgroundID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ResetBackgrounds Resets list of installed backgrounds to its default value +func (client *Client) ResetBackgrounds() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resetBackgrounds", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SynchronizeLanguagePack Fetches the latest versions of all strings from a language pack in the current localization target from the server. This method shouldn't be called explicitly for the current used/base language packs. Can be called before authorization +// @param languagePackID Language pack identifier +func (client *Client) SynchronizeLanguagePack(languagePackID string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "synchronizeLanguagePack", + "language_pack_id": languagePackID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddCustomServerLanguagePack Adds a custom server language pack to the list of installed language packs in current localization target. Can be called before authorization +// @param languagePackID Identifier of a language pack to be added; may be different from a name that is used in an "https://t.me/setlanguage/" link +func (client *Client) AddCustomServerLanguagePack(languagePackID string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addCustomServerLanguagePack", + "language_pack_id": languagePackID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetCustomLanguagePack Adds or changes a custom local 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. Can be called before authorization +// @param strings Strings of the new language pack +func (client *Client) SetCustomLanguagePack(info *tdlib.LanguagePackInfo, strings []tdlib.LanguagePackString) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setCustomLanguagePack", + "info": info, + "strings": strings, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// EditCustomLanguagePackInfo Edits information about a custom local language pack in the current localization target. Can be called before authorization +// @param info New information about the custom local language pack +func (client *Client) EditCustomLanguagePackInfo(info *tdlib.LanguagePackInfo) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "editCustomLanguagePackInfo", + "info": info, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetCustomLanguagePackString Adds, edits or deletes a string in a custom local language pack. Can be called before authorization +// @param languagePackID Identifier of a previously added custom local language pack in the current localization target +// @param newString New language pack string +func (client *Client) SetCustomLanguagePackString(languagePackID string, newString *tdlib.LanguagePackString) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setCustomLanguagePackString", + "language_pack_id": languagePackID, + "new_string": newString, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 which is currently in use (including base language pack) or is being synchronized can't be deleted. Can be called before authorization +// @param languagePackID Identifier of the language pack to delete +func (client *Client) DeleteLanguagePack(languagePackID string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteLanguagePack", + "language_pack_id": languagePackID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ProcessPushNotification Handles a push notification. Returns error with code 406 if the push notification is not supported and connection to the server is required to fetch new data. Can be called before authorization +// @param payload JSON-encoded push notification payload with all fields sent by the server, and "google.sent_time" and "google.notification.sound" fields added +func (client *Client) ProcessPushNotification(payload string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "processPushNotification", + "payload": payload, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetUserPrivacySettingRules Changes user privacy settings +// @param setting The privacy setting +// @param rules The new privacy rules +func (client *Client) SetUserPrivacySettingRules(setting tdlib.UserPrivacySetting, rules *tdlib.UserPrivacySettingRules) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setUserPrivacySettingRules", + "setting": setting, + "rules": rules, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// 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 tdlib.OptionValue) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setOption", + "name": name, + "value": value, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 *tdlib.AccountTTL) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setAccountTtl", + "ttl": tTL, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deleteAccount", + "reason": reason, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// RemoveChatActionBar Removes a chat action bar without any other action +// @param chatID Chat identifier +func (client *Client) RemoveChatActionBar(chatID int64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeChatActionBar", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ReportChat Reports a chat to the Telegram moderators. A chat can be reported only from the chat action bar, or if this is a private chat with a bot, a private chat with a user sharing their location, a supergroup, or a channel, since other chats can't be checked by moderators +// @param chatID Chat identifier +// @param messageIDs Identifiers of reported messages, if any +// @param reason The reason for reporting the chat +// @param text Additional report details; 0-1024 characters +func (client *Client) ReportChat(chatID int64, messageIDs []int64, reason tdlib.ChatReportReason, text string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "reportChat", + "chat_id": chatID, + "message_ids": messageIDs, + "reason": reason, + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// ReportChatPhoto Reports a chat photo to the Telegram moderators. A chat photo can be reported only if this is a private chat with a bot, a private chat with a user sharing their location, a supergroup, or a channel, since other chats can't be checked by moderators +// @param chatID Chat identifier +// @param fileID Identifier of the photo to report. Only full photos from chatPhoto can be reported +// @param reason The reason for reporting the chat photo +// @param text Additional report details; 0-1024 characters +func (client *Client) ReportChatPhoto(chatID int64, fileID int32, reason tdlib.ChatReportReason, text string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "reportChatPhoto", + "chat_id": chatID, + "file_id": fileID, + "reason": reason, + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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. Network type is used to check whether the library can use the network at all and also for collecting detailed network data usage statistics +// @param typeParam The new network type. By default, networkTypeOther +func (client *Client) SetNetworkType(typeParam tdlib.NetworkType) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setNetworkType", + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.NetworkStatisticsEntry) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addNetworkStatistics", + "entry": entry, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resetNetworkStatistics", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetAutoDownloadSettings Sets auto-download settings +// @param settings New user auto-download settings +// @param typeParam Type of the network for which the new settings are relevant +func (client *Client) SetAutoDownloadSettings(settings *tdlib.AutoDownloadSettings, typeParam tdlib.NetworkType) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setAutoDownloadSettings", + "settings": settings, + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// DeletePassportElement Deletes a Telegram Passport element +// @param typeParam Element type +func (client *Client) DeletePassportElement(typeParam tdlib.PassportElementType) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "deletePassportElement", + "type": typeParam, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 int64, errors []tdlib.InputPassportElementError) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setPassportElementErrors", + "user_id": userID, + "errors": errors, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckPhoneNumberVerificationCode Checks the phone number verification code for Telegram Passport +// @param code Verification code +func (client *Client) CheckPhoneNumberVerificationCode(code string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkPhoneNumberVerificationCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckEmailAddressVerificationCode Checks the email address verification code for Telegram Passport +// @param code Verification code +func (client *Client) CheckEmailAddressVerificationCode(code string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkEmailAddressVerificationCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SendPassportAuthorizationForm Sends a Telegram Passport authorization form, effectively sharing data with the service. This method must be called after getPassportAuthorizationFormAvailableElements if some previously available elements are going to be reused +// @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 []tdlib.PassportElementType) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendPassportAuthorizationForm", + "autorization_form_id": autorizationFormID, + "types": typeParams, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// CheckPhoneNumberConfirmationCode Checks phone number confirmation code +// @param code The phone number confirmation code +func (client *Client) CheckPhoneNumberConfirmationCode(code string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkPhoneNumberConfirmationCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setBotUpdatesStatus", + "pending_update_count": pendingUpdateCount, + "error_message": errorMessage, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 tdlib.InputFile, position int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setStickerPositionInSet", + "sticker": sticker, + "position": position, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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 tdlib.InputFile) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeStickerFromSet", + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AcceptTermsOfService Accepts Telegram terms of services +// @param termsOfServiceID Terms of service identifier +func (client *Client) AcceptTermsOfService(termsOfServiceID string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "acceptTermsOfService", + "terms_of_service_id": termsOfServiceID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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 *tdlib.JSONInt64, data string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "answerCustomQuery", + "custom_query_id": customQueryID, + "data": data, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetAlarm Succeeds after a specified amount of time has passed. Can be called before initialization +// @param seconds Number of seconds before the function returns +func (client *Client) SetAlarm(seconds float64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setAlarm", + "seconds": seconds, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SaveApplicationLogEvent Saves application log event on the server. Can be called before authorization +// @param typeParam Event type +// @param chatID Optional chat identifier, associated with the event +// @param data The log event data +func (client *Client) SaveApplicationLogEvent(typeParam string, chatID int64, data tdlib.JsonValue) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "saveApplicationLogEvent", + "type": typeParam, + "chat_id": chatID, + "data": data, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, 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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "enableProxy", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "disableProxy", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "removeProxy", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetLogStream Sets new log stream for internal logging of TDLib. Can be called synchronously +// @param logStream New log stream +func (client *Client) SetLogStream(logStream tdlib.LogStream) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setLogStream", + "log_stream": logStream, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetLogVerbosityLevel Sets the verbosity level of the internal logging of TDLib. Can be called synchronously +// @param newVerbosityLevel New value of the verbosity level for logging. Value 0 corresponds to fatal errors, value 1 corresponds to errors, value 2 corresponds to warnings and debug warnings, value 3 corresponds to informational, value 4 corresponds to debug, value 5 corresponds to verbose debug, value greater than 5 and up to 1023 can be used to enable even more logging +func (client *Client) SetLogVerbosityLevel(newVerbosityLevel int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setLogVerbosityLevel", + "new_verbosity_level": newVerbosityLevel, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// SetLogTagVerbosityLevel Sets the verbosity level for a specified TDLib internal log tag. Can be called synchronously +// @param tag Logging tag to change verbosity level +// @param newVerbosityLevel New verbosity level; 1-1024 +func (client *Client) SetLogTagVerbosityLevel(tag string, newVerbosityLevel int32) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setLogTagVerbosityLevel", + "tag": tag, + "new_verbosity_level": newVerbosityLevel, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// AddLogMessage Adds a message to TDLib internal log. Can be called synchronously +// @param verbosityLevel The minimum verbosity level needed for the message to be logged; 0-1023 +// @param text Text of a message to log +func (client *Client) AddLogMessage(verbosityLevel int32, text string) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addLogMessage", + "verbosity_level": verbosityLevel, + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TestCallEmpty Does nothing; for testing only. This is an offline method. Can be called before authorization +func (client *Client) TestCallEmpty() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testCallEmpty", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TestNetwork Sends a simple network request to the Telegram servers; for testing only. Can be called before authorization +func (client *Client) TestNetwork() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testNetwork", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} + +// TestProxy Sends a simple network request to the Telegram servers via proxy; for testing only. Can be called before authorization +// @param server Proxy server IP address +// @param port Proxy server port +// @param typeParam Proxy type +// @param dcID Identifier of a datacenter, with which to test connection +// @param timeout The maximum overall timeout for the request +func (client *Client) TestProxy(server string, port int32, typeParam tdlib.ProxyType, dcID int32, timeout float64) (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testProxy", + "server": server, + "port": port, + "type": typeParam, + "dc_id": dcID, + "timeout": timeout, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.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() (*tdlib.Ok, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testGetDifference", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var ok tdlib.Ok + err = json.Unmarshal(result.Raw, &ok) + return &ok, err + +} diff --git a/client/optionValue.go b/client/optionValue.go new file mode 100644 index 0000000..03e5674 --- /dev/null +++ b/client/optionValue.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (tdlib.OptionValue, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getOption", + "name": name, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.OptionValueEnum(result.Data["@type"].(string)) { + + case tdlib.OptionValueBooleanType: + var optionValue tdlib.OptionValueBoolean + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + case tdlib.OptionValueEmptyType: + var optionValue tdlib.OptionValueEmpty + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + case tdlib.OptionValueIntegerType: + var optionValue tdlib.OptionValueInteger + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + case tdlib.OptionValueStringType: + var optionValue tdlib.OptionValueString + err = json.Unmarshal(result.Raw, &optionValue) + return &optionValue, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/orderInfo.go b/client/orderInfo.go new file mode 100644 index 0000000..ca8a5d1 --- /dev/null +++ b/client/orderInfo.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetSavedOrderInfo Returns saved order info, if any +func (client *Client) GetSavedOrderInfo() (*tdlib.OrderInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSavedOrderInfo", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var orderInfo tdlib.OrderInfo + err = json.Unmarshal(result.Raw, &orderInfo) + return &orderInfo, err + +} diff --git a/client/passportAuthorizationForm.go b/client/passportAuthorizationForm.go new file mode 100644 index 0000000..b122bfb --- /dev/null +++ b/client/passportAuthorizationForm.go @@ -0,0 +1,37 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 Unique request identifier provided by the service +func (client *Client) GetPassportAuthorizationForm(botUserID int64, scope string, publicKey string, nonce string) (*tdlib.PassportAuthorizationForm, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPassportAuthorizationForm", + "bot_user_id": botUserID, + "scope": scope, + "public_key": publicKey, + "nonce": nonce, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passportAuthorizationForm tdlib.PassportAuthorizationForm + err = json.Unmarshal(result.Raw, &passportAuthorizationForm) + return &passportAuthorizationForm, err + +} diff --git a/client/passportElement.go b/client/passportElement.go new file mode 100644 index 0000000..70191ca --- /dev/null +++ b/client/passportElement.go @@ -0,0 +1,190 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 tdlib.PassportElementType, password string) (tdlib.PassportElement, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPassportElement", + "type": typeParam, + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.PassportElementEnum(result.Data["@type"].(string)) { + + case tdlib.PassportElementPersonalDetailsType: + var passportElement tdlib.PassportElementPersonalDetails + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementPassportType: + var passportElement tdlib.PassportElementPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementDriverLicenseType: + var passportElement tdlib.PassportElementDriverLicense + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementIDentityCardType: + var passportElement tdlib.PassportElementIDentityCard + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementInternalPassportType: + var passportElement tdlib.PassportElementInternalPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementAddressType: + var passportElement tdlib.PassportElementAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementUtilityBillType: + var passportElement tdlib.PassportElementUtilityBill + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementBankStatementType: + var passportElement tdlib.PassportElementBankStatement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementRentalAgreementType: + var passportElement tdlib.PassportElementRentalAgreement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementPassportRegistrationType: + var passportElement tdlib.PassportElementPassportRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementTemporaryRegistrationType: + var passportElement tdlib.PassportElementTemporaryRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementPhoneNumberType: + var passportElement tdlib.PassportElementPhoneNumber + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementEmailAddressType: + var passportElement tdlib.PassportElementEmailAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} + +// 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 tdlib.InputPassportElement, password string) (tdlib.PassportElement, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setPassportElement", + "element": element, + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.PassportElementEnum(result.Data["@type"].(string)) { + + case tdlib.PassportElementPersonalDetailsType: + var passportElement tdlib.PassportElementPersonalDetails + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementPassportType: + var passportElement tdlib.PassportElementPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementDriverLicenseType: + var passportElement tdlib.PassportElementDriverLicense + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementIDentityCardType: + var passportElement tdlib.PassportElementIDentityCard + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementInternalPassportType: + var passportElement tdlib.PassportElementInternalPassport + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementAddressType: + var passportElement tdlib.PassportElementAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementUtilityBillType: + var passportElement tdlib.PassportElementUtilityBill + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementBankStatementType: + var passportElement tdlib.PassportElementBankStatement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementRentalAgreementType: + var passportElement tdlib.PassportElementRentalAgreement + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementPassportRegistrationType: + var passportElement tdlib.PassportElementPassportRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementTemporaryRegistrationType: + var passportElement tdlib.PassportElementTemporaryRegistration + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementPhoneNumberType: + var passportElement tdlib.PassportElementPhoneNumber + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + case tdlib.PassportElementEmailAddressType: + var passportElement tdlib.PassportElementEmailAddress + err = json.Unmarshal(result.Raw, &passportElement) + return &passportElement, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/passportElements.go b/client/passportElements.go new file mode 100644 index 0000000..06f0c2f --- /dev/null +++ b/client/passportElements.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetAllPassportElements Returns all available Telegram Passport elements +// @param password Password of the current user +func (client *Client) GetAllPassportElements(password string) (*tdlib.PassportElements, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getAllPassportElements", + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passportElements tdlib.PassportElements + err = json.Unmarshal(result.Raw, &passportElements) + return &passportElements, err + +} diff --git a/client/passportElementsWithErrors.go b/client/passportElementsWithErrors.go new file mode 100644 index 0000000..517cd1c --- /dev/null +++ b/client/passportElementsWithErrors.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetPassportAuthorizationFormAvailableElements Returns already available Telegram Passport elements suitable for completing a Telegram Passport authorization form. Result can be received only once for each authorization form +// @param autorizationFormID Authorization form identifier +// @param password Password of the current user +func (client *Client) GetPassportAuthorizationFormAvailableElements(autorizationFormID int32, password string) (*tdlib.PassportElementsWithErrors, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPassportAuthorizationFormAvailableElements", + "autorization_form_id": autorizationFormID, + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passportElementsWithErrors tdlib.PassportElementsWithErrors + err = json.Unmarshal(result.Raw, &passportElementsWithErrors) + return &passportElementsWithErrors, err + +} diff --git a/client/passwordState.go b/client/passwordState.go new file mode 100644 index 0000000..38ce61f --- /dev/null +++ b/client/passwordState.go @@ -0,0 +1,151 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetPasswordState Returns the current state of 2-step verification +func (client *Client) GetPasswordState() (*tdlib.PasswordState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPasswordState", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passwordState tdlib.PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// SetPassword Changes the password for the current user. If a new recovery email address is specified, then the change will not be applied until the new recovery email address is 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) (*tdlib.PasswordState, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passwordState tdlib.PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// SetRecoveryEmailAddress Changes the 2-step verification recovery email address of the user. If a new recovery email address is specified, then the change will not be applied until the new recovery email address is confirmed. If new_recovery_email_address is the same as the email address that is currently set up, this call succeeds immediately and aborts all other requests waiting for an email confirmation +// @param password Password of the current user +// @param newRecoveryEmailAddress New recovery email address +func (client *Client) SetRecoveryEmailAddress(password string, newRecoveryEmailAddress string) (*tdlib.PasswordState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setRecoveryEmailAddress", + "password": password, + "new_recovery_email_address": newRecoveryEmailAddress, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passwordState tdlib.PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// CheckRecoveryEmailAddressCode Checks the 2-step verification recovery email address verification code +// @param code Verification code +func (client *Client) CheckRecoveryEmailAddressCode(code string) (*tdlib.PasswordState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "checkRecoveryEmailAddressCode", + "code": code, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passwordState tdlib.PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// ResendRecoveryEmailAddressCode Resends the 2-step verification recovery email address verification code +func (client *Client) ResendRecoveryEmailAddressCode() (*tdlib.PasswordState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resendRecoveryEmailAddressCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passwordState tdlib.PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} + +// RecoverPassword Recovers the 2-step verification password using a recovery code sent to an email address that was previously set up +// @param recoveryCode Recovery code to check +// @param newPassword New password of the user; may be empty to remove the password +// @param newHint New password hint; may be empty +func (client *Client) RecoverPassword(recoveryCode string, newPassword string, newHint string) (*tdlib.PasswordState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "recoverPassword", + "recovery_code": recoveryCode, + "new_password": newPassword, + "new_hint": newHint, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var passwordState tdlib.PasswordState + err = json.Unmarshal(result.Raw, &passwordState) + return &passwordState, err + +} diff --git a/client/paymentForm.go b/client/paymentForm.go new file mode 100644 index 0000000..a39a650 --- /dev/null +++ b/client/paymentForm.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 +// @param theme Preferred payment form theme +func (client *Client) GetPaymentForm(chatID int64, messageID int64, theme *tdlib.PaymentFormTheme) (*tdlib.PaymentForm, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPaymentForm", + "chat_id": chatID, + "message_id": messageID, + "theme": theme, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var paymentForm tdlib.PaymentForm + err = json.Unmarshal(result.Raw, &paymentForm) + return &paymentForm, err + +} diff --git a/client/paymentReceipt.go b/client/paymentReceipt.go new file mode 100644 index 0000000..8b53048 --- /dev/null +++ b/client/paymentReceipt.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.PaymentReceipt, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPaymentReceipt", + "chat_id": chatID, + "message_id": messageID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var paymentReceipt tdlib.PaymentReceipt + err = json.Unmarshal(result.Raw, &paymentReceipt) + return &paymentReceipt, err + +} diff --git a/client/paymentResult.go b/client/paymentResult.go new file mode 100644 index 0000000..9ff0cb2 --- /dev/null +++ b/client/paymentResult.go @@ -0,0 +1,43 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 paymentFormID Payment form identifier returned by getPaymentForm +// @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 +// @param tipAmount Chosen by the user amount of tip in the smallest units of the currency +func (client *Client) SendPaymentForm(chatID int64, messageID int64, paymentFormID *tdlib.JSONInt64, orderInfoID string, shippingOptionID string, credentials tdlib.InputCredentials, tipAmount int64) (*tdlib.PaymentResult, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "sendPaymentForm", + "chat_id": chatID, + "message_id": messageID, + "payment_form_id": paymentFormID, + "order_info_id": orderInfoID, + "shipping_option_id": shippingOptionID, + "credentials": credentials, + "tip_amount": tipAmount, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var paymentResult tdlib.PaymentResult + err = json.Unmarshal(result.Raw, &paymentResult) + return &paymentResult, err + +} diff --git a/client/phoneNumberInfo.go b/client/phoneNumberInfo.go new file mode 100644 index 0000000..7571b2c --- /dev/null +++ b/client/phoneNumberInfo.go @@ -0,0 +1,55 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetPhoneNumberInfo Returns information about a phone number by its prefix. Can be called before authorization +// @param phoneNumberPrefix The phone number prefix +func (client *Client) GetPhoneNumberInfo(phoneNumberPrefix string) (*tdlib.PhoneNumberInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPhoneNumberInfo", + "phone_number_prefix": phoneNumberPrefix, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var phoneNumberInfo tdlib.PhoneNumberInfo + err = json.Unmarshal(result.Raw, &phoneNumberInfo) + return &phoneNumberInfo, err + +} + +// GetPhoneNumberInfoSync Returns information about a phone number by its prefix synchronously. getCountries must be called at least once after changing localization to the specified language if properly localized country information is expected. Can be called synchronously +// @param languageCode A two-letter ISO 639-1 country code for country information localization +// @param phoneNumberPrefix The phone number prefix +func (client *Client) GetPhoneNumberInfoSync(languageCode string, phoneNumberPrefix string) (*tdlib.PhoneNumberInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPhoneNumberInfoSync", + "language_code": languageCode, + "phone_number_prefix": phoneNumberPrefix, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var phoneNumberInfo tdlib.PhoneNumberInfo + err = json.Unmarshal(result.Raw, &phoneNumberInfo) + return &phoneNumberInfo, err + +} diff --git a/client/proxies.go b/client/proxies.go new file mode 100644 index 0000000..a6ef2bb --- /dev/null +++ b/client/proxies.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetProxies Returns list of proxies that are currently set up. Can be called before authorization +func (client *Client) GetProxies() (*tdlib.Proxies, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getProxies", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var proxies tdlib.Proxies + err = json.Unmarshal(result.Raw, &proxies) + return &proxies, err + +} diff --git a/client/proxy.go b/client/proxy.go new file mode 100644 index 0000000..1a77719 --- /dev/null +++ b/client/proxy.go @@ -0,0 +1,67 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 tdlib.ProxyType) (*tdlib.Proxy, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var proxy tdlib.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 tdlib.ProxyType) (*tdlib.Proxy, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var proxyDummy tdlib.Proxy + err = json.Unmarshal(result.Raw, &proxyDummy) + return &proxyDummy, err + +} diff --git a/client/pushReceiverID.go b/client/pushReceiverID.go new file mode 100644 index 0000000..b3447b2 --- /dev/null +++ b/client/pushReceiverID.go @@ -0,0 +1,55 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// RegisterDevice Registers the currently used device for receiving push notifications. Returns a globally unique identifier of the push notification subscription +// @param deviceToken Device token +// @param otherUserIDs List of user identifiers of other users currently using the application +func (client *Client) RegisterDevice(deviceToken tdlib.DeviceToken, otherUserIDs []int64) (*tdlib.PushReceiverID, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "registerDevice", + "device_token": deviceToken, + "other_user_ids": otherUserIDs, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var pushReceiverID tdlib.PushReceiverID + err = json.Unmarshal(result.Raw, &pushReceiverID) + return &pushReceiverID, err + +} + +// GetPushReceiverID Returns a globally unique push notification subscription identifier for identification of an account, which has received a push notification. Can be called synchronously +// @param payload JSON-encoded push notification payload +func (client *Client) GetPushReceiverID(payload string) (*tdlib.PushReceiverID, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPushReceiverId", + "payload": payload, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var pushReceiverID tdlib.PushReceiverID + err = json.Unmarshal(result.Raw, &pushReceiverID) + return &pushReceiverID, err + +} diff --git a/client/recommendedChatFilters.go b/client/recommendedChatFilters.go new file mode 100644 index 0000000..bb759fb --- /dev/null +++ b/client/recommendedChatFilters.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetRecommendedChatFilters Returns recommended chat filters for the current user +func (client *Client) GetRecommendedChatFilters() (*tdlib.RecommendedChatFilters, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRecommendedChatFilters", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var recommendedChatFilters tdlib.RecommendedChatFilters + err = json.Unmarshal(result.Raw, &recommendedChatFilters) + return &recommendedChatFilters, err + +} diff --git a/client/recoveryEmailAddress.go b/client/recoveryEmailAddress.go new file mode 100644 index 0000000..92184f3 --- /dev/null +++ b/client/recoveryEmailAddress.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetRecoveryEmailAddress Returns a 2-step verification 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) (*tdlib.RecoveryEmailAddress, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRecoveryEmailAddress", + "password": password, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var recoveryEmailAddress tdlib.RecoveryEmailAddress + err = json.Unmarshal(result.Raw, &recoveryEmailAddress) + return &recoveryEmailAddress, err + +} diff --git a/client/resetPasswordResult.go b/client/resetPasswordResult.go new file mode 100644 index 0000000..933e778 --- /dev/null +++ b/client/resetPasswordResult.go @@ -0,0 +1,46 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// ResetPassword Removes 2-step verification password without previous password and access to recovery email address. The password can't be reset immediately and the request needs to be repeated after the specified time +func (client *Client) ResetPassword() (tdlib.ResetPasswordResult, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "resetPassword", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.ResetPasswordResultEnum(result.Data["@type"].(string)) { + + case tdlib.ResetPasswordResultOkType: + var resetPasswordResult tdlib.ResetPasswordResultOk + err = json.Unmarshal(result.Raw, &resetPasswordResult) + return &resetPasswordResult, err + + case tdlib.ResetPasswordResultPendingType: + var resetPasswordResult tdlib.ResetPasswordResultPending + err = json.Unmarshal(result.Raw, &resetPasswordResult) + return &resetPasswordResult, err + + case tdlib.ResetPasswordResultDeclinedType: + var resetPasswordResult tdlib.ResetPasswordResultDeclined + err = json.Unmarshal(result.Raw, &resetPasswordResult) + return &resetPasswordResult, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/scopeNotificationSettings.go b/client/scopeNotificationSettings.go new file mode 100644 index 0000000..d7df09a --- /dev/null +++ b/client/scopeNotificationSettings.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 tdlib.NotificationSettingsScope) (*tdlib.ScopeNotificationSettings, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getScopeNotificationSettings", + "scope": scope, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var scopeNotificationSettings tdlib.ScopeNotificationSettings + err = json.Unmarshal(result.Raw, &scopeNotificationSettings) + return &scopeNotificationSettings, err + +} diff --git a/client/seconds.go b/client/seconds.go new file mode 100644 index 0000000..15088a7 --- /dev/null +++ b/client/seconds.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.Seconds, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "pingProxy", + "proxy_id": proxyID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var seconds tdlib.Seconds + err = json.Unmarshal(result.Raw, &seconds) + return &seconds, err + +} diff --git a/client/secretChat.go b/client/secretChat.go new file mode 100644 index 0000000..a6ebe9f --- /dev/null +++ b/client/secretChat.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.SecretChat, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSecretChat", + "secret_chat_id": secretChatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var secretChatDummy tdlib.SecretChat + err = json.Unmarshal(result.Raw, &secretChatDummy) + return &secretChatDummy, err + +} diff --git a/client/session.go b/client/session.go new file mode 100644 index 0000000..62cd5a2 --- /dev/null +++ b/client/session.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// ConfirmQrCodeAuthentication Confirms QR code authentication on another device. Returns created session on success +// @param link A link from a QR code. The link must be scanned by the in-app camera +func (client *Client) ConfirmQrCodeAuthentication(link string) (*tdlib.Session, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "confirmQrCodeAuthentication", + "link": link, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var session tdlib.Session + err = json.Unmarshal(result.Raw, &session) + return &session, err + +} diff --git a/client/sessions.go b/client/sessions.go new file mode 100644 index 0000000..f30f860 --- /dev/null +++ b/client/sessions.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetActiveSessions Returns all active sessions of the current user +func (client *Client) GetActiveSessions() (*tdlib.Sessions, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getActiveSessions", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var sessions tdlib.Sessions + err = json.Unmarshal(result.Raw, &sessions) + return &sessions, err + +} diff --git a/client/sponsoredMessages.go b/client/sponsoredMessages.go new file mode 100644 index 0000000..a43e2de --- /dev/null +++ b/client/sponsoredMessages.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetChatSponsoredMessages Returns sponsored messages to be shown in a chat; for channel chats only +// @param chatID Identifier of the chat +func (client *Client) GetChatSponsoredMessages(chatID int64) (*tdlib.SponsoredMessages, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatSponsoredMessages", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var sponsoredMessages tdlib.SponsoredMessages + err = json.Unmarshal(result.Raw, &sponsoredMessages) + return &sponsoredMessages, err + +} diff --git a/client/statisticalGraph.go b/client/statisticalGraph.go new file mode 100644 index 0000000..5ab6daf --- /dev/null +++ b/client/statisticalGraph.go @@ -0,0 +1,52 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetStatisticalGraph Loads an asynchronous or a zoomed in statistical graph +// @param chatID Chat identifier +// @param token The token for graph loading +// @param x X-value for zoomed in graph or 0 otherwise +func (client *Client) GetStatisticalGraph(chatID int64, token string, x int64) (tdlib.StatisticalGraph, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getStatisticalGraph", + "chat_id": chatID, + "token": token, + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.StatisticalGraphEnum(result.Data["@type"].(string)) { + + case tdlib.StatisticalGraphDataType: + var statisticalGraph tdlib.StatisticalGraphData + err = json.Unmarshal(result.Raw, &statisticalGraph) + return &statisticalGraph, err + + case tdlib.StatisticalGraphAsyncType: + var statisticalGraph tdlib.StatisticalGraphAsync + err = json.Unmarshal(result.Raw, &statisticalGraph) + return &statisticalGraph, err + + case tdlib.StatisticalGraphErrorType: + var statisticalGraph tdlib.StatisticalGraphError + err = json.Unmarshal(result.Raw, &statisticalGraph) + return &statisticalGraph, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/stickerSet.go b/client/stickerSet.go new file mode 100644 index 0000000..0a6abc0 --- /dev/null +++ b/client/stickerSet.go @@ -0,0 +1,137 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetStickerSet Returns information about a sticker set by its identifier +// @param setID Identifier of the sticker set +func (client *Client) GetStickerSet(setID *tdlib.JSONInt64) (*tdlib.StickerSet, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getStickerSet", + "set_id": setID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSet tdlib.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) (*tdlib.StickerSet, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchStickerSet", + "name": name, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSet tdlib.StickerSet + err = json.Unmarshal(result.Raw, &stickerSet) + return &stickerSet, err + +} + +// CreateNewStickerSet Creates a new sticker set. Returns the newly created sticker set +// @param userID Sticker set owner; ignored for regular users +// @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) for bots; 1-64 characters +// @param isMasks True, if stickers are masks. Animated stickers can't be masks +// @param stickers List of stickers to be added to the set; must be non-empty. All stickers must be of the same type. For animated stickers, uploadStickerFile must be used before the sticker is shown +// @param source Source of the sticker set; may be empty if unknown +func (client *Client) CreateNewStickerSet(userID int64, title string, name string, isMasks bool, stickers []tdlib.InputSticker, source string) (*tdlib.StickerSet, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createNewStickerSet", + "user_id": userID, + "title": title, + "name": name, + "is_masks": isMasks, + "stickers": stickers, + "source": source, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSet tdlib.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 int64, name string, sticker tdlib.InputSticker) (*tdlib.StickerSet, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addStickerToSet", + "user_id": userID, + "name": name, + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSet tdlib.StickerSet + err = json.Unmarshal(result.Raw, &stickerSet) + return &stickerSet, err + +} + +// SetStickerSetThumbnail Sets a sticker set thumbnail; for bots only. Returns the sticker set +// @param userID Sticker set owner +// @param name Sticker set name +// @param thumbnail Thumbnail to set in PNG or TGS format. Animated thumbnail must be set for animated sticker sets and only for them. Pass a zero InputFileId to delete the thumbnail +func (client *Client) SetStickerSetThumbnail(userID int64, name string, thumbnail tdlib.InputFile) (*tdlib.StickerSet, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "setStickerSetThumbnail", + "user_id": userID, + "name": name, + "thumbnail": thumbnail, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSet tdlib.StickerSet + err = json.Unmarshal(result.Raw, &stickerSet) + return &stickerSet, err + +} diff --git a/client/stickerSets.go b/client/stickerSets.go new file mode 100644 index 0000000..516b4c6 --- /dev/null +++ b/client/stickerSets.go @@ -0,0 +1,151 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.StickerSets, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getInstalledStickerSets", + "is_masks": isMasks, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSets tdlib.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 The maximum number of sticker sets to return +func (client *Client) GetArchivedStickerSets(isMasks bool, offsetStickerSetID *tdlib.JSONInt64, limit int32) (*tdlib.StickerSets, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSets tdlib.StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} + +// GetTrendingStickerSets Returns a list of trending sticker sets. For optimal performance, the number of returned sticker sets is chosen by TDLib +// @param offset The offset from which to return the sticker sets; must be non-negative +// @param limit The maximum number of sticker sets to be returned; must be non-negative. For optimal performance, the number of returned sticker sets is chosen by TDLib and can be smaller than the specified limit, even if the end of the list has not been reached +func (client *Client) GetTrendingStickerSets(offset int32, limit int32) (*tdlib.StickerSets, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getTrendingStickerSets", + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSets tdlib.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) (*tdlib.StickerSets, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getAttachedStickerSets", + "file_id": fileID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSets tdlib.StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, 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 The maximum number of sticker sets to return +func (client *Client) SearchInstalledStickerSets(isMasks bool, query string, limit int32) (*tdlib.StickerSets, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchInstalledStickerSets", + "is_masks": isMasks, + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSets tdlib.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) (*tdlib.StickerSets, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchStickerSets", + "query": query, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickerSets tdlib.StickerSets + err = json.Unmarshal(result.Raw, &stickerSets) + return &stickerSets, err + +} diff --git a/client/stickers.go b/client/stickers.go new file mode 100644 index 0000000..7156dda --- /dev/null +++ b/client/stickers.go @@ -0,0 +1,123 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 The maximum number of stickers to be returned +func (client *Client) GetStickers(emoji string, limit int32) (*tdlib.Stickers, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getStickers", + "emoji": emoji, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickers tdlib.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 The maximum number of stickers to be returned +func (client *Client) SearchStickers(emoji string, limit int32) (*tdlib.Stickers, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchStickers", + "emoji": emoji, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickers tdlib.Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, 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) (*tdlib.Stickers, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRecentStickers", + "is_attached": isAttached, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickers tdlib.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 tdlib.InputFile) (*tdlib.Stickers, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "addRecentSticker", + "is_attached": isAttached, + "sticker": sticker, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickers tdlib.Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, err + +} + +// GetFavoriteStickers Returns favorite stickers +func (client *Client) GetFavoriteStickers() (*tdlib.Stickers, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getFavoriteStickers", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var stickers tdlib.Stickers + err = json.Unmarshal(result.Raw, &stickers) + return &stickers, err + +} diff --git a/client/storageStatistics.go b/client/storageStatistics.go new file mode 100644 index 0000000..be4e85d --- /dev/null +++ b/client/storageStatistics.go @@ -0,0 +1,69 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetStorageStatistics Returns storage usage statistics. Can be called before authorization +// @param chatLimit The 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) (*tdlib.StorageStatistics, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getStorageStatistics", + "chat_limit": chatLimit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var storageStatistics tdlib.StorageStatistics + err = json.Unmarshal(result.Raw, &storageStatistics) + return &storageStatistics, 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, in bytes. 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 returnDeletedFileStatistics Pass true if statistics about the files that were deleted must be returned instead of the whole storage usage statistics. Affects only returned statistics +// @param chatLimit Same as in getStorageStatistics. Affects only returned statistics +func (client *Client) OptimizeStorage(size int64, tTL int32, count int32, immunityDelay int32, fileTypes []tdlib.FileType, chatIDs []int64, excludeChatIDs []int64, returnDeletedFileStatistics bool, chatLimit int32) (*tdlib.StorageStatistics, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "optimizeStorage", + "size": size, + "ttl": tTL, + "count": count, + "immunity_delay": immunityDelay, + "file_types": fileTypes, + "chat_ids": chatIDs, + "exclude_chat_ids": excludeChatIDs, + "return_deleted_file_statistics": returnDeletedFileStatistics, + "chat_limit": chatLimit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var storageStatistics tdlib.StorageStatistics + err = json.Unmarshal(result.Raw, &storageStatistics) + return &storageStatistics, err + +} diff --git a/client/storageStatisticsFast.go b/client/storageStatisticsFast.go new file mode 100644 index 0000000..cbe670d --- /dev/null +++ b/client/storageStatisticsFast.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetStorageStatisticsFast Quickly returns approximate storage usage statistics. Can be called before authorization +func (client *Client) GetStorageStatisticsFast() (*tdlib.StorageStatisticsFast, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getStorageStatisticsFast", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var storageStatisticsFast tdlib.StorageStatisticsFast + err = json.Unmarshal(result.Raw, &storageStatisticsFast) + return &storageStatisticsFast, err + +} diff --git a/client/supergroup.go b/client/supergroup.go new file mode 100644 index 0000000..37d77a2 --- /dev/null +++ b/client/supergroup.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetSupergroup Returns information about a supergroup or a 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 int64) (*tdlib.Supergroup, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSupergroup", + "supergroup_id": supergroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var supergroupDummy tdlib.Supergroup + err = json.Unmarshal(result.Raw, &supergroupDummy) + return &supergroupDummy, err + +} diff --git a/client/supergroupFullInfo.go b/client/supergroupFullInfo.go new file mode 100644 index 0000000..69c511a --- /dev/null +++ b/client/supergroupFullInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetSupergroupFullInfo Returns full information about a supergroup or a channel by its identifier, cached for up to 1 minute +// @param supergroupID Supergroup or channel identifier +func (client *Client) GetSupergroupFullInfo(supergroupID int64) (*tdlib.SupergroupFullInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSupergroupFullInfo", + "supergroup_id": supergroupID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var supergroupFullInfo tdlib.SupergroupFullInfo + err = json.Unmarshal(result.Raw, &supergroupFullInfo) + return &supergroupFullInfo, err + +} diff --git a/client/tMeURLs.go b/client/tMeURLs.go new file mode 100644 index 0000000..8cfb542 --- /dev/null +++ b/client/tMeURLs.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.TMeURLs, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRecentlyVisitedTMeUrls", + "referrer": referrer, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var tMeURLs tdlib.TMeURLs + err = json.Unmarshal(result.Raw, &tMeURLs) + return &tMeURLs, err + +} diff --git a/client/temporaryPasswordState.go b/client/temporaryPasswordState.go new file mode 100644 index 0000000..1b933e2 --- /dev/null +++ b/client/temporaryPasswordState.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.TemporaryPasswordState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "createTemporaryPassword", + "password": password, + "valid_for": validFor, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var temporaryPasswordState tdlib.TemporaryPasswordState + err = json.Unmarshal(result.Raw, &temporaryPasswordState) + return &temporaryPasswordState, err + +} + +// GetTemporaryPasswordState Returns information about the current temporary password +func (client *Client) GetTemporaryPasswordState() (*tdlib.TemporaryPasswordState, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getTemporaryPasswordState", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var temporaryPasswordState tdlib.TemporaryPasswordState + err = json.Unmarshal(result.Raw, &temporaryPasswordState) + return &temporaryPasswordState, err + +} diff --git a/client/testBytes.go b/client/testBytes.go new file mode 100644 index 0000000..7e65050 --- /dev/null +++ b/client/testBytes.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestCallBytes Returns the received bytes; for testing only. This is an offline method. Can be called before authorization +// @param x Bytes to return +func (client *Client) TestCallBytes(x []byte) (*tdlib.TestBytes, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testCallBytes", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var testBytes tdlib.TestBytes + err = json.Unmarshal(result.Raw, &testBytes) + return &testBytes, err + +} diff --git a/client/testInt.go b/client/testInt.go new file mode 100644 index 0000000..09a5a7b --- /dev/null +++ b/client/testInt.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestSquareInt Returns the squared received number; for testing only. This is an offline method. Can be called before authorization +// @param x Number to square +func (client *Client) TestSquareInt(x int32) (*tdlib.TestInt, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testSquareInt", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var testInt tdlib.TestInt + err = json.Unmarshal(result.Raw, &testInt) + return &testInt, err + +} diff --git a/client/testString.go b/client/testString.go new file mode 100644 index 0000000..d5a1489 --- /dev/null +++ b/client/testString.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestCallString Returns the received string; for testing only. This is an offline method. Can be called before authorization +// @param x String to return +func (client *Client) TestCallString(x string) (*tdlib.TestString, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testCallString", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var testString tdlib.TestString + err = json.Unmarshal(result.Raw, &testString) + return &testString, err + +} diff --git a/client/testVectorInt.go b/client/testVectorInt.go new file mode 100644 index 0000000..dc513f0 --- /dev/null +++ b/client/testVectorInt.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestCallVectorInt Returns the received vector of numbers; for testing only. This is an offline method. Can be called before authorization +// @param x Vector of numbers to return +func (client *Client) TestCallVectorInt(x []int32) (*tdlib.TestVectorInt, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testCallVectorInt", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var testVectorInt tdlib.TestVectorInt + err = json.Unmarshal(result.Raw, &testVectorInt) + return &testVectorInt, err + +} diff --git a/client/testVectorIntObject.go b/client/testVectorIntObject.go new file mode 100644 index 0000000..8519a39 --- /dev/null +++ b/client/testVectorIntObject.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestCallVectorIntObject Returns the received vector of objects containing a number; for testing only. This is an offline method. Can be called before authorization +// @param x Vector of objects to return +func (client *Client) TestCallVectorIntObject(x []tdlib.TestInt) (*tdlib.TestVectorIntObject, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testCallVectorIntObject", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var testVectorIntObject tdlib.TestVectorIntObject + err = json.Unmarshal(result.Raw, &testVectorIntObject) + return &testVectorIntObject, err + +} diff --git a/client/testVectorString.go b/client/testVectorString.go new file mode 100644 index 0000000..a0cbc26 --- /dev/null +++ b/client/testVectorString.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestCallVectorString Returns the received vector of strings; for testing only. This is an offline method. Can be called before authorization +// @param x Vector of strings to return +func (client *Client) TestCallVectorString(x []string) (*tdlib.TestVectorString, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testCallVectorString", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var testVectorString tdlib.TestVectorString + err = json.Unmarshal(result.Raw, &testVectorString) + return &testVectorString, err + +} diff --git a/client/testVectorStringObject.go b/client/testVectorStringObject.go new file mode 100644 index 0000000..1171483 --- /dev/null +++ b/client/testVectorStringObject.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestCallVectorStringObject Returns the received vector of objects containing a string; for testing only. This is an offline method. Can be called before authorization +// @param x Vector of objects to return +func (client *Client) TestCallVectorStringObject(x []tdlib.TestString) (*tdlib.TestVectorStringObject, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testCallVectorStringObject", + "x": x, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var testVectorStringObject tdlib.TestVectorStringObject + err = json.Unmarshal(result.Raw, &testVectorStringObject) + return &testVectorStringObject, err + +} diff --git a/client/text.go b/client/text.go new file mode 100644 index 0000000..3108fe6 --- /dev/null +++ b/client/text.go @@ -0,0 +1,315 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetMessageEmbeddingCode Returns an HTML code for embedding the message. Available only for messages in supergroups and channels with a username +// @param chatID Identifier of the chat to which the message belongs +// @param messageID Identifier of the message +// @param forAlbum Pass true to return an HTML code for embedding of the whole media album +func (client *Client) GetMessageEmbeddingCode(chatID int64, messageID int64, forAlbum bool) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageEmbeddingCode", + "chat_id": chatID, + "message_id": messageID, + "for_album": forAlbum, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetFileMimeType Returns the MIME type of a file, guessed by its extension. Returns an empty string on failure. Can be called synchronously +// @param fileName The name of the file or path to the file +func (client *Client) GetFileMimeType(fileName string) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getFileMimeType", + "file_name": fileName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.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. Can be called synchronously +// @param mimeType The MIME type of the file +func (client *Client) GetFileExtension(mimeType string) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getFileExtension", + "mime_type": mimeType, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.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. Can be called synchronously +// @param fileName File name or path to the file +func (client *Client) CleanFileName(fileName string) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "cleanFileName", + "file_name": fileName, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetJsonString Converts a JsonValue object to corresponding JSON-serialized string. Can be called synchronously +// @param jsonStringValue The JsonValue object +func (client *Client) GetJsonString(jsonStringValue tdlib.JsonValue) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getJsonString", + "json_value": jsonStringValue, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetChatFilterDefaultIconName Returns default icon name for a filter. Can be called synchronously +// @param filter Chat filter +func (client *Client) GetChatFilterDefaultIconName(filter *tdlib.ChatFilter) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getChatFilterDefaultIconName", + "filter": filter, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetSuggestedFileName Returns suggested name for saving a file in a given directory +// @param fileID Identifier of the file +// @param directory Directory in which the file is supposed to be saved +func (client *Client) GetSuggestedFileName(fileID int32, directory string) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSuggestedFileName", + "file_id": fileID, + "directory": directory, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetMessageImportConfirmationText Returns a confirmation text to be shown to the user before starting message import +// @param chatID Identifier of a chat to which the messages will be imported. It must be an identifier of a private chat with a mutual contact or an identifier of a supergroup chat with can_change_info administrator right +func (client *Client) GetMessageImportConfirmationText(chatID int64) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMessageImportConfirmationText", + "chat_id": chatID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// JoinGroupCall Joins an active group call. Returns join response payload for tgcalls +// @param groupCallID Group call identifier +// @param participantID Identifier of a group call participant, which will be used to join the call; voice chats only +// @param audioSourceID Caller audio channel synchronization source identifier; received from tgcalls +// @param payload Group call join payload; received from tgcalls +// @param isMuted True, if the user's microphone is muted +// @param isMyVideoEnabled True, if the user's video is enabled +// @param inviteHash If non-empty, invite hash to be used to join the group call without being muted by administrators +func (client *Client) JoinGroupCall(groupCallID int32, participantID tdlib.MessageSender, audioSourceID int32, payload string, isMuted bool, isMyVideoEnabled bool, inviteHash string) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "joinGroupCall", + "group_call_id": groupCallID, + "participant_id": participantID, + "audio_source_id": audioSourceID, + "payload": payload, + "is_muted": isMuted, + "is_my_video_enabled": isMyVideoEnabled, + "invite_hash": inviteHash, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// StartGroupCallScreenSharing Starts screen sharing in a joined group call. Returns join response payload for tgcalls +// @param groupCallID Group call identifier +// @param audioSourceID Screen sharing audio channel synchronization source identifier; received from tgcalls +// @param payload Group call join payload; received from tgcalls +func (client *Client) StartGroupCallScreenSharing(groupCallID int32, audioSourceID int32, payload string) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "startGroupCallScreenSharing", + "group_call_id": groupCallID, + "audio_source_id": audioSourceID, + "payload": payload, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, 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) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPreferredCountryLanguage", + "country_code": countryCode, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetSuggestedStickerSetName Returns a suggested name for a new sticker set with a given title +// @param title Sticker set title; 1-64 characters +func (client *Client) GetSuggestedStickerSetName(title string) (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSuggestedStickerSetName", + "title": title, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} + +// GetCountryCode Uses the current IP address to find the current country. Returns two-letter ISO 3166-1 alpha-2 country code. Can be called before authorization +func (client *Client) GetCountryCode() (*tdlib.Text, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getCountryCode", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var text tdlib.Text + err = json.Unmarshal(result.Raw, &text) + return &text, err + +} diff --git a/client/textEntities.go b/client/textEntities.go new file mode 100644 index 0000000..a6d125d --- /dev/null +++ b/client/textEntities.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetTextEntities Returns all entities (mentions, hashtags, cashtags, bot commands, bank card numbers, URLs, and email addresses) contained in the text. Can be called synchronously +// @param text The text in which to look for entites +func (client *Client) GetTextEntities(text string) (*tdlib.TextEntities, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getTextEntities", + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var textEntities tdlib.TextEntities + err = json.Unmarshal(result.Raw, &textEntities) + return &textEntities, err + +} diff --git a/client/update.go b/client/update.go new file mode 100644 index 0000000..4035de7 --- /dev/null +++ b/client/update.go @@ -0,0 +1,466 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + "fmt" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// TestUseUpdate Does nothing and ensures that the Update object is used; for testing only. This is an offline method. Can be called before authorization +func (client *Client) TestUseUpdate() (tdlib.Update, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "testUseUpdate", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + switch tdlib.UpdateEnum(result.Data["@type"].(string)) { + + case tdlib.UpdateAuthorizationStateType: + var update tdlib.UpdateAuthorizationState + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewMessageType: + var update tdlib.UpdateNewMessage + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageSendAcknowledgedType: + var update tdlib.UpdateMessageSendAcknowledged + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageSendSucceededType: + var update tdlib.UpdateMessageSendSucceeded + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageSendFailedType: + var update tdlib.UpdateMessageSendFailed + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageContentType: + var update tdlib.UpdateMessageContent + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageEditedType: + var update tdlib.UpdateMessageEdited + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageIsPinnedType: + var update tdlib.UpdateMessageIsPinned + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageInteractionInfoType: + var update tdlib.UpdateMessageInteractionInfo + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageContentOpenedType: + var update tdlib.UpdateMessageContentOpened + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageMentionReadType: + var update tdlib.UpdateMessageMentionRead + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateMessageLiveLocationViewedType: + var update tdlib.UpdateMessageLiveLocationViewed + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewChatType: + var update tdlib.UpdateNewChat + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatTitleType: + var update tdlib.UpdateChatTitle + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatPhotoType: + var update tdlib.UpdateChatPhoto + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatPermissionsType: + var update tdlib.UpdateChatPermissions + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatLastMessageType: + var update tdlib.UpdateChatLastMessage + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatPositionType: + var update tdlib.UpdateChatPosition + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatIsMarkedAsUnreadType: + var update tdlib.UpdateChatIsMarkedAsUnread + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatIsBlockedType: + var update tdlib.UpdateChatIsBlocked + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatHasScheduledMessagesType: + var update tdlib.UpdateChatHasScheduledMessages + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatVoiceChatType: + var update tdlib.UpdateChatVoiceChat + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatDefaultDisableNotificationType: + var update tdlib.UpdateChatDefaultDisableNotification + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatReadInboxType: + var update tdlib.UpdateChatReadInbox + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatReadOutboxType: + var update tdlib.UpdateChatReadOutbox + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatUnreadMentionCountType: + var update tdlib.UpdateChatUnreadMentionCount + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatNotificationSettingsType: + var update tdlib.UpdateChatNotificationSettings + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateScopeNotificationSettingsType: + var update tdlib.UpdateScopeNotificationSettings + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatMessageTTLSettingType: + var update tdlib.UpdateChatMessageTTLSetting + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatActionBarType: + var update tdlib.UpdateChatActionBar + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatThemeType: + var update tdlib.UpdateChatTheme + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatReplyMarkupType: + var update tdlib.UpdateChatReplyMarkup + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatDraftMessageType: + var update tdlib.UpdateChatDraftMessage + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatFiltersType: + var update tdlib.UpdateChatFilters + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatOnlineMemberCountType: + var update tdlib.UpdateChatOnlineMemberCount + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNotificationType: + var update tdlib.UpdateNotification + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNotificationGroupType: + var update tdlib.UpdateNotificationGroup + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateActiveNotificationsType: + var update tdlib.UpdateActiveNotifications + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateHavePendingNotificationsType: + var update tdlib.UpdateHavePendingNotifications + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateDeleteMessagesType: + var update tdlib.UpdateDeleteMessages + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUserChatActionType: + var update tdlib.UpdateUserChatAction + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUserStatusType: + var update tdlib.UpdateUserStatus + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUserType: + var update tdlib.UpdateUser + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateBasicGroupType: + var update tdlib.UpdateBasicGroup + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateSupergroupType: + var update tdlib.UpdateSupergroup + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateSecretChatType: + var update tdlib.UpdateSecretChat + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUserFullInfoType: + var update tdlib.UpdateUserFullInfo + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateBasicGroupFullInfoType: + var update tdlib.UpdateBasicGroupFullInfo + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateSupergroupFullInfoType: + var update tdlib.UpdateSupergroupFullInfo + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateServiceNotificationType: + var update tdlib.UpdateServiceNotification + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateFileType: + var update tdlib.UpdateFile + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateFileGenerationStartType: + var update tdlib.UpdateFileGenerationStart + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateFileGenerationStopType: + var update tdlib.UpdateFileGenerationStop + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateCallType: + var update tdlib.UpdateCall + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateGroupCallType: + var update tdlib.UpdateGroupCall + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateGroupCallParticipantType: + var update tdlib.UpdateGroupCallParticipant + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewCallSignalingDataType: + var update tdlib.UpdateNewCallSignalingData + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUserPrivacySettingRulesType: + var update tdlib.UpdateUserPrivacySettingRules + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUnreadMessageCountType: + var update tdlib.UpdateUnreadMessageCount + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUnreadChatCountType: + var update tdlib.UpdateUnreadChatCount + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateOptionType: + var update tdlib.UpdateOption + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateStickerSetType: + var update tdlib.UpdateStickerSet + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateInstalledStickerSetsType: + var update tdlib.UpdateInstalledStickerSets + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateTrendingStickerSetsType: + var update tdlib.UpdateTrendingStickerSets + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateRecentStickersType: + var update tdlib.UpdateRecentStickers + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateFavoriteStickersType: + var update tdlib.UpdateFavoriteStickers + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateSavedAnimationsType: + var update tdlib.UpdateSavedAnimations + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateSelectedBackgroundType: + var update tdlib.UpdateSelectedBackground + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatThemesType: + var update tdlib.UpdateChatThemes + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateLanguagePackStringsType: + var update tdlib.UpdateLanguagePackStrings + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateConnectionStateType: + var update tdlib.UpdateConnectionState + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateTermsOfServiceType: + var update tdlib.UpdateTermsOfService + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateUsersNearbyType: + var update tdlib.UpdateUsersNearby + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateDiceEmojisType: + var update tdlib.UpdateDiceEmojis + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateAnimationSearchParametersType: + var update tdlib.UpdateAnimationSearchParameters + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateSuggestedActionsType: + var update tdlib.UpdateSuggestedActions + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewInlineQueryType: + var update tdlib.UpdateNewInlineQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewChosenInlineResultType: + var update tdlib.UpdateNewChosenInlineResult + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewCallbackQueryType: + var update tdlib.UpdateNewCallbackQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewInlineCallbackQueryType: + var update tdlib.UpdateNewInlineCallbackQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewShippingQueryType: + var update tdlib.UpdateNewShippingQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewPreCheckoutQueryType: + var update tdlib.UpdateNewPreCheckoutQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewCustomEventType: + var update tdlib.UpdateNewCustomEvent + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateNewCustomQueryType: + var update tdlib.UpdateNewCustomQuery + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdatePollType: + var update tdlib.UpdatePoll + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdatePollAnswerType: + var update tdlib.UpdatePollAnswer + err = json.Unmarshal(result.Raw, &update) + return &update, err + + case tdlib.UpdateChatMemberType: + var update tdlib.UpdateChatMember + err = json.Unmarshal(result.Raw, &update) + return &update, err + + default: + return nil, fmt.Errorf("Invalid type") + } +} diff --git a/client/updates.go b/client/updates.go new file mode 100644 index 0000000..314d176 --- /dev/null +++ b/client/updates.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetCurrentState Returns all updates needed to restore current TDLib state, i.e. all actual UpdateAuthorizationState/UpdateUser/UpdateNewChat and others. This is especially useful if TDLib is run in a separate process. Can be called before initialization +func (client *Client) GetCurrentState() (*tdlib.Updates, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getCurrentState", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var updates tdlib.Updates + err = json.Unmarshal(result.Raw, &updates) + return &updates, err + +} diff --git a/client/user.go b/client/user.go new file mode 100644 index 0000000..946a371 --- /dev/null +++ b/client/user.go @@ -0,0 +1,71 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetMe Returns the current user +func (client *Client) GetMe() (*tdlib.User, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getMe", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var user tdlib.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 int64) (*tdlib.User, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getUser", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var userDummy tdlib.User + err = json.Unmarshal(result.Raw, &userDummy) + return &userDummy, err + +} + +// GetSupportUser Returns a user that can be contacted to get support +func (client *Client) GetSupportUser() (*tdlib.User, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getSupportUser", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var user tdlib.User + err = json.Unmarshal(result.Raw, &user) + return &user, err + +} diff --git a/client/userFullInfo.go b/client/userFullInfo.go new file mode 100644 index 0000000..062814e --- /dev/null +++ b/client/userFullInfo.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetUserFullInfo Returns full information about a user by their identifier +// @param userID User identifier +func (client *Client) GetUserFullInfo(userID int64) (*tdlib.UserFullInfo, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getUserFullInfo", + "user_id": userID, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var userFullInfo tdlib.UserFullInfo + err = json.Unmarshal(result.Raw, &userFullInfo) + return &userFullInfo, err + +} diff --git a/client/userPrivacySettingRules.go b/client/userPrivacySettingRules.go new file mode 100644 index 0000000..4dc44b4 --- /dev/null +++ b/client/userPrivacySettingRules.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetUserPrivacySettingRules Returns the current privacy settings +// @param setting The privacy setting +func (client *Client) GetUserPrivacySettingRules(setting tdlib.UserPrivacySetting) (*tdlib.UserPrivacySettingRules, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getUserPrivacySettingRules", + "setting": setting, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var userPrivacySettingRules tdlib.UserPrivacySettingRules + err = json.Unmarshal(result.Raw, &userPrivacySettingRules) + return &userPrivacySettingRules, err + +} diff --git a/client/users.go b/client/users.go new file mode 100644 index 0000000..e7279bb --- /dev/null +++ b/client/users.go @@ -0,0 +1,103 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// GetPollVoters Returns users voted for the specified option in a non-anonymous polls. For optimal performance, the number of returned users is chosen by TDLib +// @param chatID Identifier of the chat to which the poll belongs +// @param messageID Identifier of the message containing the poll +// @param optionID 0-based identifier of the answer option +// @param offset Number of users to skip in the result; must be non-negative +// @param limit The maximum number of users to be returned; must be positive and can't be greater than 50. For optimal performance, the number of returned users is chosen by TDLib and can be smaller than the specified limit, even if the end of the voter list has not been reached +func (client *Client) GetPollVoters(chatID int64, messageID int64, optionID int32, offset int32, limit int32) (*tdlib.Users, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getPollVoters", + "chat_id": chatID, + "message_id": messageID, + "option_id": optionID, + "offset": offset, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var users tdlib.Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} + +// GetContacts Returns all user contacts +func (client *Client) GetContacts() (*tdlib.Users, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getContacts", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var users tdlib.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; may be empty to return all contacts +// @param limit The maximum number of users to be returned +func (client *Client) SearchContacts(query string, limit int32) (*tdlib.Users, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "searchContacts", + "query": query, + "limit": limit, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var users tdlib.Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} + +// GetRecentInlineBots Returns up to 20 recently used inline bots in the order of their last usage +func (client *Client) GetRecentInlineBots() (*tdlib.Users, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getRecentInlineBots", + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var users tdlib.Users + err = json.Unmarshal(result.Raw, &users) + return &users, err + +} diff --git a/client/validatedOrderInfo.go b/client/validatedOrderInfo.go new file mode 100644 index 0000000..bd286f6 --- /dev/null +++ b/client/validatedOrderInfo.go @@ -0,0 +1,37 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 *tdlib.OrderInfo, allowSave bool) (*tdlib.ValidatedOrderInfo, error) { + result, err := client.SendAndCatch(tdlib.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, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var validatedOrderInfo tdlib.ValidatedOrderInfo + err = json.Unmarshal(result.Raw, &validatedOrderInfo) + return &validatedOrderInfo, err + +} diff --git a/client/webPage.go b/client/webPage.go new file mode 100644 index 0000000..362d82c --- /dev/null +++ b/client/webPage.go @@ -0,0 +1,31 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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 *tdlib.FormattedText) (*tdlib.WebPage, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getWebPagePreview", + "text": text, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var webPage tdlib.WebPage + err = json.Unmarshal(result.Raw, &webPage) + return &webPage, err + +} diff --git a/client/webPageInstantView.go b/client/webPageInstantView.go new file mode 100644 index 0000000..0c11b1b --- /dev/null +++ b/client/webPageInstantView.go @@ -0,0 +1,33 @@ +// AUTOGENERATED - DO NOT EDIT + +package client + +import ( + "encoding/json" + + "github.com/kaoriEl/go-tdlib/tdlib" +) + +// 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) (*tdlib.WebPageInstantView, error) { + result, err := client.SendAndCatch(tdlib.UpdateData{ + "@type": "getWebPageInstantView", + "url": uRL, + "force_full": forceFull, + }) + + if err != nil { + return nil, err + } + + if result.Data["@type"].(string) == "error" { + return nil, tdlib.RequestError{Code: int(result.Data["code"].(float64)), Message: result.Data["message"].(string)} + } + + var webPageInstantView tdlib.WebPageInstantView + err = json.Unmarshal(result.Raw, &webPageInstantView) + return &webPageInstantView, err + +} diff --git a/examples/authorization/basicAuthorization.go b/examples/authorization/basicAuthorization.go index 04c6d0f..5246121 100644 --- a/examples/authorization/basicAuthorization.go +++ b/examples/authorization/basicAuthorization.go @@ -3,15 +3,16 @@ package main import ( "fmt" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) func main() { - tdlib.SetLogVerbosityLevel(1) - tdlib.SetFilePath("./errors.txt") + client.SetLogVerbosityLevel(1) + client.SetFilePath("./errors.txt") // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "187786", APIHash: "e782045df67ba48e441ccb105da8fc85", SystemLanguageCode: "en", diff --git a/examples/authorization/botAuthorization.go b/examples/authorization/botAuthorization.go index 2ed5614..6726465 100644 --- a/examples/authorization/botAuthorization.go +++ b/examples/authorization/botAuthorization.go @@ -3,17 +3,18 @@ package main import ( "fmt" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) const botToken = "" func main() { - tdlib.SetLogVerbosityLevel(1) - tdlib.SetFilePath("./errors.txt") + client.SetLogVerbosityLevel(1) + client.SetFilePath("./errors.txt") // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "187786", APIHash: "e782045df67ba48e441ccb105da8fc85", SystemLanguageCode: "en", diff --git a/examples/customEvents/getCustomEvents.go b/examples/customEvents/getCustomEvents.go index 26d2b08..96d850f 100644 --- a/examples/customEvents/getCustomEvents.go +++ b/examples/customEvents/getCustomEvents.go @@ -7,15 +7,16 @@ import ( "syscall" "time" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) func main() { - tdlib.SetLogVerbosityLevel(1) - tdlib.SetFilePath("./errors.txt") + client.SetLogVerbosityLevel(1) + client.SetFilePath("./errors.txt") // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "187786", APIHash: "e782045df67ba48e441ccb105da8fc85", SystemLanguageCode: "en", @@ -41,7 +42,7 @@ func main() { }() // Wait while we get AuthorizationReady! - // Note: See authorization example for complete auhtorization sequence example + // Note: See authorization example for complete authorization sequence example currentState, _ := client.Authorize() for ; currentState.GetAuthorizationStateEnum() != tdlib.AuthorizationStateReadyType; currentState, _ = client.Authorize() { time.Sleep(300 * time.Millisecond) @@ -51,9 +52,10 @@ func main() { // Create an filter function which will be used to filter out unwanted tdlib messages eventFilter := func(msg *tdlib.TdMessage) bool { updateMsg := (*msg).(*tdlib.UpdateNewMessage) - // For example, we want incomming messages from user with below id: - if updateMsg.Message.SenderUserID == 41507975 { - return true + // For example, we want incoming messages from user with below id: + if updateMsg.Message.Sender.GetMessageSenderEnum() == tdlib.MessageSenderUserType { + sender := updateMsg.Message.Sender.(*tdlib.MessageSenderUser) + return sender.UserID == 1055350095 } return false } @@ -62,7 +64,7 @@ func main() { // We like to get UpdateNewMessage events and with a specific FilterFunc receiver := client.AddEventReceiver(&tdlib.UpdateNewMessage{}, eventFilter, 5) for newMsg := range receiver.Chan { - fmt.Println(newMsg) + // fmt.Println(newMsg) updateMsg := (newMsg).(*tdlib.UpdateNewMessage) // We assume the message content is simple text: (should be more sophisticated for general use) msgText := updateMsg.Message.Content.(*tdlib.MessageText) diff --git a/examples/getChats/getChats.go b/examples/getChats/getChats.go index ec6e046..74cfde1 100644 --- a/examples/getChats/getChats.go +++ b/examples/getChats/getChats.go @@ -2,24 +2,24 @@ package main import ( "fmt" - "math" "os" "os/signal" "syscall" "time" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) var allChats []*tdlib.Chat var haveFullChatList bool func main() { - tdlib.SetLogVerbosityLevel(1) - tdlib.SetFilePath("./errors.txt") + client.SetLogVerbosityLevel(1) + client.SetFilePath("./errors.txt") // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "187786", APIHash: "e782045df67ba48e441ccb105da8fc85", SystemLanguageCode: "en", @@ -64,47 +64,37 @@ func main() { } } -// see https://stackoverflow.com/questions/37782348/how-to-use-getchats-in-tdlib -func getChatList(client *tdlib.Client, limit int) error { - - if !haveFullChatList && limit > len(allChats) { - offsetOrder := int64(math.MaxInt64) - offsetChatID := int64(0) - var chatList = tdlib.NewChatListMain() - var lastChat *tdlib.Chat - - if len(allChats) > 0 { - lastChat = allChats[len(allChats)-1] - for i := 0; i < len(lastChat.Positions); i++ { - //Find the main chat list - if lastChat.Positions[i].List.GetChatListEnum() == tdlib.ChatListMainType { - offsetOrder = int64(lastChat.Positions[i].Order) - } - } - offsetChatID = lastChat.ID - } +func getChatList(client *client.Client, limit int) error { + var chatList = tdlib.NewChatListMain() + + chats, err := client.GetChats(chatList, int32(limit)) + if err != nil { + return err + } + for len(chats.ChatIDs) != limit { // get chats (ids) from tdlib - chats, err := client.GetChats(chatList, tdlib.JSONInt64(offsetOrder), - offsetChatID, int32(limit-len(allChats))) + _, err := client.LoadChats(chatList, int32(limit-len(chats.ChatIDs))) if err != nil { + if err.(tdlib.RequestError).Code != 404 { + chats, err = client.GetChats(chatList, int32(limit)) + break + } return err } - if len(chats.ChatIDs) == 0 { - haveFullChatList = true - return nil - } - for _, chatID := range chats.ChatIDs { - // get chat info from tdlib - chat, err := client.GetChat(chatID) - if err == nil { - allChats = append(allChats, chat) - } else { - return err - } + chats, err = client.GetChats(chatList, int32(limit)) + } + + for _, chatID := range chats.ChatIDs { + // get chat info from tdlib + chat, err := client.GetChat(chatID) + if err == nil { + allChats = append(allChats, chat) + } else { + return err } - return getChatList(client, limit) } + return nil } diff --git a/examples/multipleAccounts/multipleAcounts.go b/examples/multipleAccounts/multipleAcounts.go index b26506e..f8545df 100644 --- a/examples/multipleAccounts/multipleAcounts.go +++ b/examples/multipleAccounts/multipleAcounts.go @@ -11,7 +11,8 @@ import ( "os" "strings" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) var allChats []*tdlib.Chat @@ -19,10 +20,10 @@ var haveFullChatList bool // TdInstance ... type TdInstance struct { - AcountName string `json:"AcountName"` - TdlibDbDirectory string `json:"TdlibDbDirectory"` - TdlibFilesDirectory string `json:"TdlibFilesDirectory"` - TdlibClient *tdlib.Client `json:"-"` + AcountName string `json:"AcountName"` + TdlibDbDirectory string `json:"TdlibDbDirectory"` + TdlibFilesDirectory string `json:"TdlibFilesDirectory"` + TdlibClient *client.Client `json:"-"` } var botInstances []TdInstance @@ -33,7 +34,7 @@ func main() { flag.BoolVar(&reconfig, "reconfig", false, "Pass true if you want to reconfigure the accounts") flag.Parse() - tdlib.SetLogVerbosityLevel(1) + client.SetLogVerbosityLevel(1) // if reconfig flag is set true, we will re-configure the telegram accounts, otherwise we just read the previous config and add the instances if reconfig { @@ -102,7 +103,7 @@ func main() { func (tdInstance *TdInstance) addTdlibClient() { // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "228834", APIHash: "e4d4a67594f3ddadacab55ab48a6187a", SystemLanguageCode: "en", diff --git a/examples/sendPhoto/sendPhoto.go b/examples/sendPhoto/sendPhoto.go index 6a9bf86..d2512f1 100644 --- a/examples/sendPhoto/sendPhoto.go +++ b/examples/sendPhoto/sendPhoto.go @@ -1,20 +1,22 @@ package main import ( + "fmt" "os" "os/signal" "syscall" "time" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) func main() { - tdlib.SetLogVerbosityLevel(1) - tdlib.SetFilePath("./errors.txt") + client.SetLogVerbosityLevel(1) + client.SetFilePath("./errors.txt") // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "187786", APIHash: "e782045df67ba48e441ccb105da8fc85", SystemLanguageCode: "en", @@ -40,7 +42,7 @@ func main() { }() // Wait while we get AuthorizationReady! - // Note: See authorization example for complete auhtorization sequence example + // Note: See authorization example for complete authorization sequence example currentState, _ := client.Authorize() for ; currentState.GetAuthorizationStateEnum() != tdlib.AuthorizationStateReadyType; currentState, _ = client.Authorize() { time.Sleep(300 * time.Millisecond) @@ -48,10 +50,28 @@ func main() { // Send "/start" text every 5 seconds to Forsquare bot chat // Should get chatID somehow, check out "getChats" example - chatID := int64(198529620) // Foursquare bot chat id + chatID := int64(1055350095) // Foursquare bot chat id + // Note: file path ("./bunny.jpg") should be relative to your execution directory. inputMsg := tdlib.NewInputMessagePhoto(tdlib.NewInputFileLocal("./bunny.jpg"), nil, nil, 400, 400, tdlib.NewFormattedText("A photo sent from go-tdlib!", nil), 0) - client.SendMessage(chatID, 0, false, false, nil, inputMsg) + sentMsg, err := client.SendMessage(chatID, 0, 0, nil, nil, inputMsg) + if err != nil { + fmt.Println(err) + return + } + + // Wait until the photo gets uploaded/sent. + for { + statMsg, err := client.GetMessage(sentMsg.ChatID, sentMsg.ID) + if err == nil { + fmt.Println(statMsg.SendingState) + } else { + fmt.Println(err) + return + } + + time.Sleep(2 * time.Second) + } } diff --git a/examples/sendText/sendText.go b/examples/sendText/sendText.go index ef28be9..03ab1ab 100644 --- a/examples/sendText/sendText.go +++ b/examples/sendText/sendText.go @@ -7,15 +7,16 @@ import ( "syscall" "time" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) func main() { - tdlib.SetLogVerbosityLevel(1) - tdlib.SetFilePath("./errors.txt") + client.SetLogVerbosityLevel(1) + client.SetFilePath("./errors.txt") // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "187786", APIHash: "e782045df67ba48e441ccb105da8fc85", SystemLanguageCode: "en", @@ -41,7 +42,7 @@ func main() { }() // Wait while we get AuthorizationReady! - // Note: See authorization example for complete auhtorization sequence example + // Note: See authorization example for complete authorization sequence example currentState, _ := client.Authorize() for ; currentState.GetAuthorizationStateEnum() != tdlib.AuthorizationStateReadyType; currentState, _ = client.Authorize() { time.Sleep(300 * time.Millisecond) @@ -53,7 +54,7 @@ func main() { chatID := int64(198529620) // Foursquare bot chat id inputMsgTxt := tdlib.NewInputMessageText(tdlib.NewFormattedText("/start", nil), true, true) - client.SendMessage(chatID, int64(0), int64(0), nil, nil, inputMsgTxt) + client.SendMessage(chatID, 0, 0, nil, nil, inputMsgTxt) time.Sleep(5 * time.Second) }() diff --git a/examples/socksProxy/socksProxy.go b/examples/socksProxy/socksProxy.go index f7536af..9d1b519 100644 --- a/examples/socksProxy/socksProxy.go +++ b/examples/socksProxy/socksProxy.go @@ -7,15 +7,16 @@ import ( "syscall" "time" - "github.com/Arman92/go-tdlib" + "github.com/Arman92/go-tdlib/v2/client" + "github.com/Arman92/go-tdlib/v2/tdlib" ) func main() { - tdlib.SetLogVerbosityLevel(1) - tdlib.SetFilePath("./errors.txt") + client.SetLogVerbosityLevel(1) + client.SetFilePath("./errors.txt") // Create new instance of client - client := tdlib.NewClient(tdlib.Config{ + client := client.NewClient(client.Config{ APIID: "187786", APIHash: "e782045df67ba48e441ccb105da8fc85", SystemLanguageCode: "en", @@ -49,7 +50,7 @@ func main() { }() // Wait while we get AuthorizationReady! - // Note: See authorization example for complete auhtorization sequence example + // Note: See authorization example for complete authorization sequence example currentState, _ := client.Authorize() for ; currentState.GetAuthorizationStateEnum() != tdlib.AuthorizationStateReadyType; currentState, _ = client.Authorize() { time.Sleep(300 * time.Millisecond) @@ -61,7 +62,7 @@ func main() { chatID := int64(198529620) // Foursquare bot chat id inputMsgTxt := tdlib.NewInputMessageText(tdlib.NewFormattedText("/start", nil), true, true) - client.SendMessage(chatID, 0, false, true, nil, inputMsgTxt) + client.SendMessage(chatID, 0, 0, nil, nil, inputMsgTxt) time.Sleep(5 * time.Second) }() diff --git a/tdlib/accountTTL.go b/tdlib/accountTTL.go new file mode 100644 index 0000000..20a7a4e --- /dev/null +++ b/tdlib/accountTTL.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/address.go b/tdlib/address.go new file mode 100644 index 0000000..82c95a4 --- /dev/null +++ b/tdlib/address.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/animatedChatPhoto.go b/tdlib/animatedChatPhoto.go new file mode 100644 index 0000000..e3afff7 --- /dev/null +++ b/tdlib/animatedChatPhoto.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// AnimatedChatPhoto Animated variant of a chat photo in MPEG4 format +type AnimatedChatPhoto struct { + tdCommon + Length int32 `json:"length"` // Animation width and height + File *File `json:"file"` // Information about the animation file + MainFrameTimestamp float64 `json:"main_frame_timestamp"` // Timestamp of the frame, used as a static chat photo +} + +// MessageType return the string telegram-type of AnimatedChatPhoto +func (animatedChatPhoto *AnimatedChatPhoto) MessageType() string { + return "animatedChatPhoto" +} + +// NewAnimatedChatPhoto creates a new AnimatedChatPhoto +// +// @param length Animation width and height +// @param file Information about the animation file +// @param mainFrameTimestamp Timestamp of the frame, used as a static chat photo +func NewAnimatedChatPhoto(length int32, file *File, mainFrameTimestamp float64) *AnimatedChatPhoto { + animatedChatPhotoTemp := AnimatedChatPhoto{ + tdCommon: tdCommon{Type: "animatedChatPhoto"}, + Length: length, + File: file, + MainFrameTimestamp: mainFrameTimestamp, + } + + return &animatedChatPhotoTemp +} diff --git a/tdlib/animation.go b/tdlib/animation.go new file mode 100644 index 0000000..37f4d3f --- /dev/null +++ b/tdlib/animation.go @@ -0,0 +1,50 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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" + HasStickers bool `json:"has_stickers"` // True, if stickers were added to the animation. The list of corresponding sticker set can be received using getAttachedStickerSets + Minithumbnail *Minithumbnail `json:"minithumbnail"` // Animation minithumbnail; may be null + Thumbnail *Thumbnail `json:"thumbnail"` // Animation thumbnail in JPEG or MPEG4 format; 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 hasStickers True, if stickers were added to the animation. The list of corresponding sticker set can be received using getAttachedStickerSets +// @param minithumbnail Animation minithumbnail; may be null +// @param thumbnail Animation thumbnail in JPEG or MPEG4 format; may be null +// @param animation File containing the animation +func NewAnimation(duration int32, width int32, height int32, fileName string, mimeType string, hasStickers bool, minithumbnail *Minithumbnail, thumbnail *Thumbnail, animation *File) *Animation { + animationTemp := Animation{ + tdCommon: tdCommon{Type: "animation"}, + Duration: duration, + Width: width, + Height: height, + FileName: fileName, + MimeType: mimeType, + HasStickers: hasStickers, + Minithumbnail: minithumbnail, + Thumbnail: thumbnail, + Animation: animation, + } + + return &animationTemp +} diff --git a/tdlib/animations.go b/tdlib/animations.go new file mode 100644 index 0000000..cd74b82 --- /dev/null +++ b/tdlib/animations.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/audio.go b/tdlib/audio.go new file mode 100644 index 0000000..d9c299f --- /dev/null +++ b/tdlib/audio.go @@ -0,0 +1,47 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Audio Describes an audio file. Audio is usually in MP3 or M4A 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 + AlbumCoverMinithumbnail *Minithumbnail `json:"album_cover_minithumbnail"` // The minithumbnail of the album cover; may be null + AlbumCoverThumbnail *Thumbnail `json:"album_cover_thumbnail"` // The thumbnail of the album cover in JPEG format; 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 albumCoverMinithumbnail The minithumbnail of the album cover; may be null +// @param albumCoverThumbnail The thumbnail of the album cover in JPEG format; 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, albumCoverMinithumbnail *Minithumbnail, albumCoverThumbnail *Thumbnail, audio *File) *Audio { + audioTemp := Audio{ + tdCommon: tdCommon{Type: "audio"}, + Duration: duration, + Title: title, + Performer: performer, + FileName: fileName, + MimeType: mimeType, + AlbumCoverMinithumbnail: albumCoverMinithumbnail, + AlbumCoverThumbnail: albumCoverThumbnail, + Audio: audio, + } + + return &audioTemp +} diff --git a/tdlib/authenticationCodeInfo.go b/tdlib/authenticationCodeInfo.go new file mode 100644 index 0000000..45aefd7 --- /dev/null +++ b/tdlib/authenticationCodeInfo.go @@ -0,0 +1,69 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 can 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 can 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 can 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 +} diff --git a/tdlib/authenticationCodeType.go b/tdlib/authenticationCodeType.go new file mode 100644 index 0000000..c119e10 --- /dev/null +++ b/tdlib/authenticationCodeType.go @@ -0,0 +1,173 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// AuthenticationCodeType Provides information about the method by which an authentication code is delivered to the user +type AuthenticationCodeType interface { + GetAuthenticationCodeTypeEnum() AuthenticationCodeTypeEnum +} + +// 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" +) + +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)) + } +} + +// AuthenticationCodeTypeTelegramMessage An authentication code is delivered via a private Telegram message, which can be viewed from another active session +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 canceled 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 +} diff --git a/tdlib/authorizationState.go b/tdlib/authorizationState.go new file mode 100644 index 0000000..7f97796 --- /dev/null +++ b/tdlib/authorizationState.go @@ -0,0 +1,399 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// AuthorizationState Represents the current authorization state of the TDLib client +type AuthorizationState interface { + GetAuthorizationStateEnum() AuthorizationStateEnum +} + +// 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" + AuthorizationStateWaitOtherDeviceConfirmationType AuthorizationStateEnum = "authorizationStateWaitOtherDeviceConfirmation" + AuthorizationStateWaitRegistrationType AuthorizationStateEnum = "authorizationStateWaitRegistration" + AuthorizationStateWaitPasswordType AuthorizationStateEnum = "authorizationStateWaitPassword" + AuthorizationStateReadyType AuthorizationStateEnum = "authorizationStateReady" + AuthorizationStateLoggingOutType AuthorizationStateEnum = "authorizationStateLoggingOut" + AuthorizationStateClosingType AuthorizationStateEnum = "authorizationStateClosing" + AuthorizationStateClosedType AuthorizationStateEnum = "authorizationStateClosed" +) + +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 AuthorizationStateWaitOtherDeviceConfirmationType: + var authorizationStateWaitOtherDeviceConfirmation AuthorizationStateWaitOtherDeviceConfirmation + err := json.Unmarshal(*rawMsg, &authorizationStateWaitOtherDeviceConfirmation) + return &authorizationStateWaitOtherDeviceConfirmation, err + + case AuthorizationStateWaitRegistrationType: + var authorizationStateWaitRegistration AuthorizationStateWaitRegistration + err := json.Unmarshal(*rawMsg, &authorizationStateWaitRegistration) + return &authorizationStateWaitRegistration, 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)) + } +} + +// 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. Call `setAuthenticationPhoneNumber` to provide the phone number, or use `requestQrCodeAuthentication`, or `checkAuthenticationBotToken` for other authentication options +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 authorize +type AuthorizationStateWaitCode struct { + tdCommon + 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 codeInfo Information about the authorization code that was sent +func NewAuthorizationStateWaitCode(codeInfo *AuthenticationCodeInfo) *AuthorizationStateWaitCode { + authorizationStateWaitCodeTemp := AuthorizationStateWaitCode{ + tdCommon: tdCommon{Type: "authorizationStateWaitCode"}, + CodeInfo: codeInfo, + } + + return &authorizationStateWaitCodeTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitCode *AuthorizationStateWaitCode) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitCodeType +} + +// AuthorizationStateWaitOtherDeviceConfirmation The user needs to confirm authorization on another logged in device by scanning a QR code with the provided link +type AuthorizationStateWaitOtherDeviceConfirmation struct { + tdCommon + Link string `json:"link"` // A tg:// URL for the QR code. The link will be updated frequently +} + +// MessageType return the string telegram-type of AuthorizationStateWaitOtherDeviceConfirmation +func (authorizationStateWaitOtherDeviceConfirmation *AuthorizationStateWaitOtherDeviceConfirmation) MessageType() string { + return "authorizationStateWaitOtherDeviceConfirmation" +} + +// NewAuthorizationStateWaitOtherDeviceConfirmation creates a new AuthorizationStateWaitOtherDeviceConfirmation +// +// @param link A tg:// URL for the QR code. The link will be updated frequently +func NewAuthorizationStateWaitOtherDeviceConfirmation(link string) *AuthorizationStateWaitOtherDeviceConfirmation { + authorizationStateWaitOtherDeviceConfirmationTemp := AuthorizationStateWaitOtherDeviceConfirmation{ + tdCommon: tdCommon{Type: "authorizationStateWaitOtherDeviceConfirmation"}, + Link: link, + } + + return &authorizationStateWaitOtherDeviceConfirmationTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitOtherDeviceConfirmation *AuthorizationStateWaitOtherDeviceConfirmation) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitOtherDeviceConfirmationType +} + +// AuthorizationStateWaitRegistration The user is unregistered and need to accept terms of service and enter their first name and last name to finish registration +type AuthorizationStateWaitRegistration struct { + tdCommon + TermsOfService *TermsOfService `json:"terms_of_service"` // Telegram terms of service +} + +// MessageType return the string telegram-type of AuthorizationStateWaitRegistration +func (authorizationStateWaitRegistration *AuthorizationStateWaitRegistration) MessageType() string { + return "authorizationStateWaitRegistration" +} + +// NewAuthorizationStateWaitRegistration creates a new AuthorizationStateWaitRegistration +// +// @param termsOfService Telegram terms of service +func NewAuthorizationStateWaitRegistration(termsOfService *TermsOfService) *AuthorizationStateWaitRegistration { + authorizationStateWaitRegistrationTemp := AuthorizationStateWaitRegistration{ + tdCommon: tdCommon{Type: "authorizationStateWaitRegistration"}, + TermsOfService: termsOfService, + } + + return &authorizationStateWaitRegistrationTemp +} + +// GetAuthorizationStateEnum return the enum type of this object +func (authorizationStateWaitRegistration *AuthorizationStateWaitRegistration) GetAuthorizationStateEnum() AuthorizationStateEnum { + return AuthorizationStateWaitRegistrationType +} + +// 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; may 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; may 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 with error code 500. To continue working, one should create a new instance of the TDLib client +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 +} diff --git a/tdlib/autoDownloadSettings.go b/tdlib/autoDownloadSettings.go new file mode 100644 index 0000000..bdba8f4 --- /dev/null +++ b/tdlib/autoDownloadSettings.go @@ -0,0 +1,47 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// AutoDownloadSettings Contains auto-download settings +type AutoDownloadSettings struct { + tdCommon + IsAutoDownloadEnabled bool `json:"is_auto_download_enabled"` // True, if the auto-download is enabled + MaxPhotoFileSize int32 `json:"max_photo_file_size"` // The maximum size of a photo file to be auto-downloaded, in bytes + MaxVideoFileSize int32 `json:"max_video_file_size"` // The maximum size of a video file to be auto-downloaded, in bytes + MaxOtherFileSize int32 `json:"max_other_file_size"` // The maximum size of other file types to be auto-downloaded, in bytes + VideoUploadBitrate int32 `json:"video_upload_bitrate"` // The maximum suggested bitrate for uploaded videos, in kbit/s + PreloadLargeVideos bool `json:"preload_large_videos"` // True, if the beginning of video files needs to be preloaded for instant playback + PreloadNextAudio bool `json:"preload_next_audio"` // True, if the next audio track needs to be preloaded while the user is listening to an audio file + UseLessDataForCalls bool `json:"use_less_data_for_calls"` // True, if "use less data for calls" option needs to be enabled +} + +// MessageType return the string telegram-type of AutoDownloadSettings +func (autoDownloadSettings *AutoDownloadSettings) MessageType() string { + return "autoDownloadSettings" +} + +// NewAutoDownloadSettings creates a new AutoDownloadSettings +// +// @param isAutoDownloadEnabled True, if the auto-download is enabled +// @param maxPhotoFileSize The maximum size of a photo file to be auto-downloaded, in bytes +// @param maxVideoFileSize The maximum size of a video file to be auto-downloaded, in bytes +// @param maxOtherFileSize The maximum size of other file types to be auto-downloaded, in bytes +// @param videoUploadBitrate The maximum suggested bitrate for uploaded videos, in kbit/s +// @param preloadLargeVideos True, if the beginning of video files needs to be preloaded for instant playback +// @param preloadNextAudio True, if the next audio track needs to be preloaded while the user is listening to an audio file +// @param useLessDataForCalls True, if "use less data for calls" option needs to be enabled +func NewAutoDownloadSettings(isAutoDownloadEnabled bool, maxPhotoFileSize int32, maxVideoFileSize int32, maxOtherFileSize int32, videoUploadBitrate int32, preloadLargeVideos bool, preloadNextAudio bool, useLessDataForCalls bool) *AutoDownloadSettings { + autoDownloadSettingsTemp := AutoDownloadSettings{ + tdCommon: tdCommon{Type: "autoDownloadSettings"}, + IsAutoDownloadEnabled: isAutoDownloadEnabled, + MaxPhotoFileSize: maxPhotoFileSize, + MaxVideoFileSize: maxVideoFileSize, + MaxOtherFileSize: maxOtherFileSize, + VideoUploadBitrate: videoUploadBitrate, + PreloadLargeVideos: preloadLargeVideos, + PreloadNextAudio: preloadNextAudio, + UseLessDataForCalls: useLessDataForCalls, + } + + return &autoDownloadSettingsTemp +} diff --git a/tdlib/autoDownloadSettingsPresets.go b/tdlib/autoDownloadSettingsPresets.go new file mode 100644 index 0000000..019d2eb --- /dev/null +++ b/tdlib/autoDownloadSettingsPresets.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// AutoDownloadSettingsPresets Contains auto-download settings presets for the current user +type AutoDownloadSettingsPresets struct { + tdCommon + Low *AutoDownloadSettings `json:"low"` // Preset with lowest settings; supposed to be used by default when roaming + Medium *AutoDownloadSettings `json:"medium"` // Preset with medium settings; supposed to be used by default when using mobile data + High *AutoDownloadSettings `json:"high"` // Preset with highest settings; supposed to be used by default when connected on Wi-Fi +} + +// MessageType return the string telegram-type of AutoDownloadSettingsPresets +func (autoDownloadSettingsPresets *AutoDownloadSettingsPresets) MessageType() string { + return "autoDownloadSettingsPresets" +} + +// NewAutoDownloadSettingsPresets creates a new AutoDownloadSettingsPresets +// +// @param low Preset with lowest settings; supposed to be used by default when roaming +// @param medium Preset with medium settings; supposed to be used by default when using mobile data +// @param high Preset with highest settings; supposed to be used by default when connected on Wi-Fi +func NewAutoDownloadSettingsPresets(low *AutoDownloadSettings, medium *AutoDownloadSettings, high *AutoDownloadSettings) *AutoDownloadSettingsPresets { + autoDownloadSettingsPresetsTemp := AutoDownloadSettingsPresets{ + tdCommon: tdCommon{Type: "autoDownloadSettingsPresets"}, + Low: low, + Medium: medium, + High: high, + } + + return &autoDownloadSettingsPresetsTemp +} diff --git a/tdlib/background.go b/tdlib/background.go new file mode 100644 index 0000000..916da7d --- /dev/null +++ b/tdlib/background.go @@ -0,0 +1,79 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// Background Describes a chat background +type Background struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique background identifier + IsDefault bool `json:"is_default"` // True, if this is one of default backgrounds + IsDark bool `json:"is_dark"` // True, if the background is dark and is recommended to be used with dark theme + Name string `json:"name"` // Unique background name + Document *Document `json:"document"` // Document with the background; may be null. Null only for filled backgrounds + Type BackgroundType `json:"type"` // Type of the background +} + +// MessageType return the string telegram-type of Background +func (background *Background) MessageType() string { + return "background" +} + +// NewBackground creates a new Background +// +// @param iD Unique background identifier +// @param isDefault True, if this is one of default backgrounds +// @param isDark True, if the background is dark and is recommended to be used with dark theme +// @param name Unique background name +// @param document Document with the background; may be null. Null only for filled backgrounds +// @param typeParam Type of the background +func NewBackground(iD JSONInt64, isDefault bool, isDark bool, name string, document *Document, typeParam BackgroundType) *Background { + backgroundTemp := Background{ + tdCommon: tdCommon{Type: "background"}, + ID: iD, + IsDefault: isDefault, + IsDark: isDark, + Name: name, + Document: document, + Type: typeParam, + } + + return &backgroundTemp +} + +// UnmarshalJSON unmarshal to json +func (background *Background) 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 background identifier + IsDefault bool `json:"is_default"` // True, if this is one of default backgrounds + IsDark bool `json:"is_dark"` // True, if the background is dark and is recommended to be used with dark theme + Name string `json:"name"` // Unique background name + Document *Document `json:"document"` // Document with the background; may be null. Null only for filled backgrounds + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + background.tdCommon = tempObj.tdCommon + background.ID = tempObj.ID + background.IsDefault = tempObj.IsDefault + background.IsDark = tempObj.IsDark + background.Name = tempObj.Name + background.Document = tempObj.Document + + fieldType, _ := unmarshalBackgroundType(objMap["type"]) + background.Type = fieldType + + return nil +} diff --git a/tdlib/backgroundFill.go b/tdlib/backgroundFill.go new file mode 100644 index 0000000..10daefa --- /dev/null +++ b/tdlib/backgroundFill.go @@ -0,0 +1,145 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// BackgroundFill Describes a fill of a background +type BackgroundFill interface { + GetBackgroundFillEnum() BackgroundFillEnum +} + +// BackgroundFillEnum Alias for abstract BackgroundFill 'Sub-Classes', used as constant-enum here +type BackgroundFillEnum string + +// BackgroundFill enums +const ( + BackgroundFillSolidType BackgroundFillEnum = "backgroundFillSolid" + BackgroundFillGradientType BackgroundFillEnum = "backgroundFillGradient" + BackgroundFillFreeformGradientType BackgroundFillEnum = "backgroundFillFreeformGradient" +) + +func unmarshalBackgroundFill(rawMsg *json.RawMessage) (BackgroundFill, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch BackgroundFillEnum(objMap["@type"].(string)) { + case BackgroundFillSolidType: + var backgroundFillSolid BackgroundFillSolid + err := json.Unmarshal(*rawMsg, &backgroundFillSolid) + return &backgroundFillSolid, err + + case BackgroundFillGradientType: + var backgroundFillGradient BackgroundFillGradient + err := json.Unmarshal(*rawMsg, &backgroundFillGradient) + return &backgroundFillGradient, err + + case BackgroundFillFreeformGradientType: + var backgroundFillFreeformGradient BackgroundFillFreeformGradient + err := json.Unmarshal(*rawMsg, &backgroundFillFreeformGradient) + return &backgroundFillFreeformGradient, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// BackgroundFillSolid Describes a solid fill of a background +type BackgroundFillSolid struct { + tdCommon + Color int32 `json:"color"` // A color of the background in the RGB24 format +} + +// MessageType return the string telegram-type of BackgroundFillSolid +func (backgroundFillSolid *BackgroundFillSolid) MessageType() string { + return "backgroundFillSolid" +} + +// NewBackgroundFillSolid creates a new BackgroundFillSolid +// +// @param color A color of the background in the RGB24 format +func NewBackgroundFillSolid(color int32) *BackgroundFillSolid { + backgroundFillSolidTemp := BackgroundFillSolid{ + tdCommon: tdCommon{Type: "backgroundFillSolid"}, + Color: color, + } + + return &backgroundFillSolidTemp +} + +// GetBackgroundFillEnum return the enum type of this object +func (backgroundFillSolid *BackgroundFillSolid) GetBackgroundFillEnum() BackgroundFillEnum { + return BackgroundFillSolidType +} + +// BackgroundFillGradient Describes a gradient fill of a background +type BackgroundFillGradient struct { + tdCommon + TopColor int32 `json:"top_color"` // A top color of the background in the RGB24 format + BottomColor int32 `json:"bottom_color"` // A bottom color of the background in the RGB24 format + RotationAngle int32 `json:"rotation_angle"` // Clockwise rotation angle of the gradient, in degrees; 0-359. Should be always divisible by 45 +} + +// MessageType return the string telegram-type of BackgroundFillGradient +func (backgroundFillGradient *BackgroundFillGradient) MessageType() string { + return "backgroundFillGradient" +} + +// NewBackgroundFillGradient creates a new BackgroundFillGradient +// +// @param topColor A top color of the background in the RGB24 format +// @param bottomColor A bottom color of the background in the RGB24 format +// @param rotationAngle Clockwise rotation angle of the gradient, in degrees; 0-359. Should be always divisible by 45 +func NewBackgroundFillGradient(topColor int32, bottomColor int32, rotationAngle int32) *BackgroundFillGradient { + backgroundFillGradientTemp := BackgroundFillGradient{ + tdCommon: tdCommon{Type: "backgroundFillGradient"}, + TopColor: topColor, + BottomColor: bottomColor, + RotationAngle: rotationAngle, + } + + return &backgroundFillGradientTemp +} + +// GetBackgroundFillEnum return the enum type of this object +func (backgroundFillGradient *BackgroundFillGradient) GetBackgroundFillEnum() BackgroundFillEnum { + return BackgroundFillGradientType +} + +// BackgroundFillFreeformGradient Describes a freeform gradient fill of a background +type BackgroundFillFreeformGradient struct { + tdCommon + Colors []int32 `json:"colors"` // A list of 3 or 4 colors of the freeform gradients in the RGB24 format +} + +// MessageType return the string telegram-type of BackgroundFillFreeformGradient +func (backgroundFillFreeformGradient *BackgroundFillFreeformGradient) MessageType() string { + return "backgroundFillFreeformGradient" +} + +// NewBackgroundFillFreeformGradient creates a new BackgroundFillFreeformGradient +// +// @param colors A list of 3 or 4 colors of the freeform gradients in the RGB24 format +func NewBackgroundFillFreeformGradient(colors []int32) *BackgroundFillFreeformGradient { + backgroundFillFreeformGradientTemp := BackgroundFillFreeformGradient{ + tdCommon: tdCommon{Type: "backgroundFillFreeformGradient"}, + Colors: colors, + } + + return &backgroundFillFreeformGradientTemp +} + +// GetBackgroundFillEnum return the enum type of this object +func (backgroundFillFreeformGradient *BackgroundFillFreeformGradient) GetBackgroundFillEnum() BackgroundFillEnum { + return BackgroundFillFreeformGradientType +} diff --git a/tdlib/backgroundType.go b/tdlib/backgroundType.go new file mode 100644 index 0000000..46c00b3 --- /dev/null +++ b/tdlib/backgroundType.go @@ -0,0 +1,203 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// BackgroundType Describes the type of a background +type BackgroundType interface { + GetBackgroundTypeEnum() BackgroundTypeEnum +} + +// BackgroundTypeEnum Alias for abstract BackgroundType 'Sub-Classes', used as constant-enum here +type BackgroundTypeEnum string + +// BackgroundType enums +const ( + BackgroundTypeWallpaperType BackgroundTypeEnum = "backgroundTypeWallpaper" + BackgroundTypePatternType BackgroundTypeEnum = "backgroundTypePattern" + BackgroundTypeFillType BackgroundTypeEnum = "backgroundTypeFill" +) + +func unmarshalBackgroundType(rawMsg *json.RawMessage) (BackgroundType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch BackgroundTypeEnum(objMap["@type"].(string)) { + case BackgroundTypeWallpaperType: + var backgroundTypeWallpaper BackgroundTypeWallpaper + err := json.Unmarshal(*rawMsg, &backgroundTypeWallpaper) + return &backgroundTypeWallpaper, err + + case BackgroundTypePatternType: + var backgroundTypePattern BackgroundTypePattern + err := json.Unmarshal(*rawMsg, &backgroundTypePattern) + return &backgroundTypePattern, err + + case BackgroundTypeFillType: + var backgroundTypeFill BackgroundTypeFill + err := json.Unmarshal(*rawMsg, &backgroundTypeFill) + return &backgroundTypeFill, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// BackgroundTypeWallpaper A wallpaper in JPEG format +type BackgroundTypeWallpaper struct { + tdCommon + IsBlurred bool `json:"is_blurred"` // True, if the wallpaper must be downscaled to fit in 450x450 square and then box-blurred with radius 12 + IsMoving bool `json:"is_moving"` // True, if the background needs to be slightly moved when device is tilted +} + +// MessageType return the string telegram-type of BackgroundTypeWallpaper +func (backgroundTypeWallpaper *BackgroundTypeWallpaper) MessageType() string { + return "backgroundTypeWallpaper" +} + +// NewBackgroundTypeWallpaper creates a new BackgroundTypeWallpaper +// +// @param isBlurred True, if the wallpaper must be downscaled to fit in 450x450 square and then box-blurred with radius 12 +// @param isMoving True, if the background needs to be slightly moved when device is tilted +func NewBackgroundTypeWallpaper(isBlurred bool, isMoving bool) *BackgroundTypeWallpaper { + backgroundTypeWallpaperTemp := BackgroundTypeWallpaper{ + tdCommon: tdCommon{Type: "backgroundTypeWallpaper"}, + IsBlurred: isBlurred, + IsMoving: isMoving, + } + + return &backgroundTypeWallpaperTemp +} + +// GetBackgroundTypeEnum return the enum type of this object +func (backgroundTypeWallpaper *BackgroundTypeWallpaper) GetBackgroundTypeEnum() BackgroundTypeEnum { + return BackgroundTypeWallpaperType +} + +// BackgroundTypePattern A PNG or TGV (gzipped subset of SVG with MIME type "application/x-tgwallpattern") pattern to be combined with the background fill chosen by the user +type BackgroundTypePattern struct { + tdCommon + Fill BackgroundFill `json:"fill"` // Description of the background fill + Intensity int32 `json:"intensity"` // Intensity of the pattern when it is shown above the filled background; 0-100. + IsInverted bool `json:"is_inverted"` // True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only + IsMoving bool `json:"is_moving"` // True, if the background needs to be slightly moved when device is tilted +} + +// MessageType return the string telegram-type of BackgroundTypePattern +func (backgroundTypePattern *BackgroundTypePattern) MessageType() string { + return "backgroundTypePattern" +} + +// NewBackgroundTypePattern creates a new BackgroundTypePattern +// +// @param fill Description of the background fill +// @param intensity Intensity of the pattern when it is shown above the filled background; 0-100. +// @param isInverted True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only +// @param isMoving True, if the background needs to be slightly moved when device is tilted +func NewBackgroundTypePattern(fill BackgroundFill, intensity int32, isInverted bool, isMoving bool) *BackgroundTypePattern { + backgroundTypePatternTemp := BackgroundTypePattern{ + tdCommon: tdCommon{Type: "backgroundTypePattern"}, + Fill: fill, + Intensity: intensity, + IsInverted: isInverted, + IsMoving: isMoving, + } + + return &backgroundTypePatternTemp +} + +// UnmarshalJSON unmarshal to json +func (backgroundTypePattern *BackgroundTypePattern) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Intensity int32 `json:"intensity"` // Intensity of the pattern when it is shown above the filled background; 0-100. + IsInverted bool `json:"is_inverted"` // True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only + IsMoving bool `json:"is_moving"` // True, if the background needs to be slightly moved when device is tilted + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + backgroundTypePattern.tdCommon = tempObj.tdCommon + backgroundTypePattern.Intensity = tempObj.Intensity + backgroundTypePattern.IsInverted = tempObj.IsInverted + backgroundTypePattern.IsMoving = tempObj.IsMoving + + fieldFill, _ := unmarshalBackgroundFill(objMap["fill"]) + backgroundTypePattern.Fill = fieldFill + + return nil +} + +// GetBackgroundTypeEnum return the enum type of this object +func (backgroundTypePattern *BackgroundTypePattern) GetBackgroundTypeEnum() BackgroundTypeEnum { + return BackgroundTypePatternType +} + +// BackgroundTypeFill A filled background +type BackgroundTypeFill struct { + tdCommon + Fill BackgroundFill `json:"fill"` // Description of the background fill +} + +// MessageType return the string telegram-type of BackgroundTypeFill +func (backgroundTypeFill *BackgroundTypeFill) MessageType() string { + return "backgroundTypeFill" +} + +// NewBackgroundTypeFill creates a new BackgroundTypeFill +// +// @param fill Description of the background fill +func NewBackgroundTypeFill(fill BackgroundFill) *BackgroundTypeFill { + backgroundTypeFillTemp := BackgroundTypeFill{ + tdCommon: tdCommon{Type: "backgroundTypeFill"}, + Fill: fill, + } + + return &backgroundTypeFillTemp +} + +// UnmarshalJSON unmarshal to json +func (backgroundTypeFill *BackgroundTypeFill) 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 + } + + backgroundTypeFill.tdCommon = tempObj.tdCommon + + fieldFill, _ := unmarshalBackgroundFill(objMap["fill"]) + backgroundTypeFill.Fill = fieldFill + + return nil +} + +// GetBackgroundTypeEnum return the enum type of this object +func (backgroundTypeFill *BackgroundTypeFill) GetBackgroundTypeEnum() BackgroundTypeEnum { + return BackgroundTypeFillType +} diff --git a/tdlib/backgrounds.go b/tdlib/backgrounds.go new file mode 100644 index 0000000..9519c82 --- /dev/null +++ b/tdlib/backgrounds.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Backgrounds Contains a list of backgrounds +type Backgrounds struct { + tdCommon + Backgrounds []Background `json:"backgrounds"` // A list of backgrounds +} + +// MessageType return the string telegram-type of Backgrounds +func (backgrounds *Backgrounds) MessageType() string { + return "backgrounds" +} + +// NewBackgrounds creates a new Backgrounds +// +// @param backgrounds A list of backgrounds +func NewBackgrounds(backgrounds []Background) *Backgrounds { + backgroundsTemp := Backgrounds{ + tdCommon: tdCommon{Type: "backgrounds"}, + Backgrounds: backgrounds, + } + + return &backgroundsTemp +} diff --git a/tdlib/bankCardActionOpenURL.go b/tdlib/bankCardActionOpenURL.go new file mode 100644 index 0000000..6de4434 --- /dev/null +++ b/tdlib/bankCardActionOpenURL.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// BankCardActionOpenURL Describes an action associated with a bank card number +type BankCardActionOpenURL struct { + tdCommon + Text string `json:"text"` // Action text + URL string `json:"url"` // The URL to be opened +} + +// MessageType return the string telegram-type of BankCardActionOpenURL +func (bankCardActionOpenURL *BankCardActionOpenURL) MessageType() string { + return "bankCardActionOpenUrl" +} + +// NewBankCardActionOpenURL creates a new BankCardActionOpenURL +// +// @param text Action text +// @param uRL The URL to be opened +func NewBankCardActionOpenURL(text string, uRL string) *BankCardActionOpenURL { + bankCardActionOpenURLTemp := BankCardActionOpenURL{ + tdCommon: tdCommon{Type: "bankCardActionOpenUrl"}, + Text: text, + URL: uRL, + } + + return &bankCardActionOpenURLTemp +} diff --git a/tdlib/bankCardInfo.go b/tdlib/bankCardInfo.go new file mode 100644 index 0000000..4f1d75c --- /dev/null +++ b/tdlib/bankCardInfo.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// BankCardInfo Information about a bank card +type BankCardInfo struct { + tdCommon + Title string `json:"title"` // Title of the bank card description + Actions []BankCardActionOpenURL `json:"actions"` // Actions that can be done with the bank card number +} + +// MessageType return the string telegram-type of BankCardInfo +func (bankCardInfo *BankCardInfo) MessageType() string { + return "bankCardInfo" +} + +// NewBankCardInfo creates a new BankCardInfo +// +// @param title Title of the bank card description +// @param actions Actions that can be done with the bank card number +func NewBankCardInfo(title string, actions []BankCardActionOpenURL) *BankCardInfo { + bankCardInfoTemp := BankCardInfo{ + tdCommon: tdCommon{Type: "bankCardInfo"}, + Title: title, + Actions: actions, + } + + return &bankCardInfoTemp +} diff --git a/tdlib/basicGroup.go b/tdlib/basicGroup.go new file mode 100644 index 0000000..61f8b96 --- /dev/null +++ b/tdlib/basicGroup.go @@ -0,0 +1,73 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 int64 `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 + IsActive bool `json:"is_active"` // True, if the group is active + UpgradedToSupergroupID int64 `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 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 int64, memberCount int32, status ChatMemberStatus, isActive bool, upgradedToSupergroupID int64) *BasicGroup { + basicGroupTemp := BasicGroup{ + tdCommon: tdCommon{Type: "basicGroup"}, + ID: iD, + MemberCount: memberCount, + Status: status, + 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 int64 `json:"id"` // Group identifier + MemberCount int32 `json:"member_count"` // Number of members in the group + IsActive bool `json:"is_active"` // True, if the group is active + UpgradedToSupergroupID int64 `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.IsActive = tempObj.IsActive + basicGroup.UpgradedToSupergroupID = tempObj.UpgradedToSupergroupID + + fieldStatus, _ := unmarshalChatMemberStatus(objMap["status"]) + basicGroup.Status = fieldStatus + + return nil +} diff --git a/tdlib/basicGroupFullInfo.go b/tdlib/basicGroupFullInfo.go new file mode 100644 index 0000000..627fcbc --- /dev/null +++ b/tdlib/basicGroupFullInfo.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// BasicGroupFullInfo Contains full information about a basic group +type BasicGroupFullInfo struct { + tdCommon + Photo *ChatPhoto `json:"photo"` // Chat photo; may be null + Description string `json:"description"` // Group description. Updated only after the basic group is opened + CreatorUserID int64 `json:"creator_user_id"` // User identifier of the creator of the group; 0 if unknown + Members []ChatMember `json:"members"` // Group members + InviteLink *ChatInviteLink `json:"invite_link"` // Primary invite link for this group; may be null. For chat administrators with can_invite_users right only. Updated only after the basic group is opened + BotCommands []BotCommands `json:"bot_commands"` // List of commands of bots in the group +} + +// MessageType return the string telegram-type of BasicGroupFullInfo +func (basicGroupFullInfo *BasicGroupFullInfo) MessageType() string { + return "basicGroupFullInfo" +} + +// NewBasicGroupFullInfo creates a new BasicGroupFullInfo +// +// @param photo Chat photo; may be null +// @param description Group description. Updated only after the basic group is opened +// @param creatorUserID User identifier of the creator of the group; 0 if unknown +// @param members Group members +// @param inviteLink Primary invite link for this group; may be null. For chat administrators with can_invite_users right only. Updated only after the basic group is opened +// @param botCommands List of commands of bots in the group +func NewBasicGroupFullInfo(photo *ChatPhoto, description string, creatorUserID int64, members []ChatMember, inviteLink *ChatInviteLink, botCommands []BotCommands) *BasicGroupFullInfo { + basicGroupFullInfoTemp := BasicGroupFullInfo{ + tdCommon: tdCommon{Type: "basicGroupFullInfo"}, + Photo: photo, + Description: description, + CreatorUserID: creatorUserID, + Members: members, + InviteLink: inviteLink, + BotCommands: botCommands, + } + + return &basicGroupFullInfoTemp +} diff --git a/tdlib/botCommand.go b/tdlib/botCommand.go new file mode 100644 index 0000000..a9a9f97 --- /dev/null +++ b/tdlib/botCommand.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// BotCommand Represents a command supported by a bot +type BotCommand struct { + tdCommon + Command string `json:"command"` // Text of the bot command + Description string `json:"description"` // Description of the bot command +} + +// 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 Description of the bot command +func NewBotCommand(command string, description string) *BotCommand { + botCommandTemp := BotCommand{ + tdCommon: tdCommon{Type: "botCommand"}, + Command: command, + Description: description, + } + + return &botCommandTemp +} diff --git a/tdlib/botCommandScope.go b/tdlib/botCommandScope.go new file mode 100644 index 0000000..c292fa1 --- /dev/null +++ b/tdlib/botCommandScope.go @@ -0,0 +1,266 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// BotCommandScope Represents the scope to which bot commands are relevant +type BotCommandScope interface { + GetBotCommandScopeEnum() BotCommandScopeEnum +} + +// BotCommandScopeEnum Alias for abstract BotCommandScope 'Sub-Classes', used as constant-enum here +type BotCommandScopeEnum string + +// BotCommandScope enums +const ( + BotCommandScopeDefaultType BotCommandScopeEnum = "botCommandScopeDefault" + BotCommandScopeAllPrivateChatsType BotCommandScopeEnum = "botCommandScopeAllPrivateChats" + BotCommandScopeAllGroupChatsType BotCommandScopeEnum = "botCommandScopeAllGroupChats" + BotCommandScopeAllChatAdministratorsType BotCommandScopeEnum = "botCommandScopeAllChatAdministrators" + BotCommandScopeChatType BotCommandScopeEnum = "botCommandScopeChat" + BotCommandScopeChatAdministratorsType BotCommandScopeEnum = "botCommandScopeChatAdministrators" + BotCommandScopeChatMemberType BotCommandScopeEnum = "botCommandScopeChatMember" +) + +func unmarshalBotCommandScope(rawMsg *json.RawMessage) (BotCommandScope, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch BotCommandScopeEnum(objMap["@type"].(string)) { + case BotCommandScopeDefaultType: + var botCommandScopeDefault BotCommandScopeDefault + err := json.Unmarshal(*rawMsg, &botCommandScopeDefault) + return &botCommandScopeDefault, err + + case BotCommandScopeAllPrivateChatsType: + var botCommandScopeAllPrivateChats BotCommandScopeAllPrivateChats + err := json.Unmarshal(*rawMsg, &botCommandScopeAllPrivateChats) + return &botCommandScopeAllPrivateChats, err + + case BotCommandScopeAllGroupChatsType: + var botCommandScopeAllGroupChats BotCommandScopeAllGroupChats + err := json.Unmarshal(*rawMsg, &botCommandScopeAllGroupChats) + return &botCommandScopeAllGroupChats, err + + case BotCommandScopeAllChatAdministratorsType: + var botCommandScopeAllChatAdministrators BotCommandScopeAllChatAdministrators + err := json.Unmarshal(*rawMsg, &botCommandScopeAllChatAdministrators) + return &botCommandScopeAllChatAdministrators, err + + case BotCommandScopeChatType: + var botCommandScopeChat BotCommandScopeChat + err := json.Unmarshal(*rawMsg, &botCommandScopeChat) + return &botCommandScopeChat, err + + case BotCommandScopeChatAdministratorsType: + var botCommandScopeChatAdministrators BotCommandScopeChatAdministrators + err := json.Unmarshal(*rawMsg, &botCommandScopeChatAdministrators) + return &botCommandScopeChatAdministrators, err + + case BotCommandScopeChatMemberType: + var botCommandScopeChatMember BotCommandScopeChatMember + err := json.Unmarshal(*rawMsg, &botCommandScopeChatMember) + return &botCommandScopeChatMember, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// BotCommandScopeDefault A scope covering all users +type BotCommandScopeDefault struct { + tdCommon +} + +// MessageType return the string telegram-type of BotCommandScopeDefault +func (botCommandScopeDefault *BotCommandScopeDefault) MessageType() string { + return "botCommandScopeDefault" +} + +// NewBotCommandScopeDefault creates a new BotCommandScopeDefault +// +func NewBotCommandScopeDefault() *BotCommandScopeDefault { + botCommandScopeDefaultTemp := BotCommandScopeDefault{ + tdCommon: tdCommon{Type: "botCommandScopeDefault"}, + } + + return &botCommandScopeDefaultTemp +} + +// GetBotCommandScopeEnum return the enum type of this object +func (botCommandScopeDefault *BotCommandScopeDefault) GetBotCommandScopeEnum() BotCommandScopeEnum { + return BotCommandScopeDefaultType +} + +// BotCommandScopeAllPrivateChats A scope covering all private chats +type BotCommandScopeAllPrivateChats struct { + tdCommon +} + +// MessageType return the string telegram-type of BotCommandScopeAllPrivateChats +func (botCommandScopeAllPrivateChats *BotCommandScopeAllPrivateChats) MessageType() string { + return "botCommandScopeAllPrivateChats" +} + +// NewBotCommandScopeAllPrivateChats creates a new BotCommandScopeAllPrivateChats +// +func NewBotCommandScopeAllPrivateChats() *BotCommandScopeAllPrivateChats { + botCommandScopeAllPrivateChatsTemp := BotCommandScopeAllPrivateChats{ + tdCommon: tdCommon{Type: "botCommandScopeAllPrivateChats"}, + } + + return &botCommandScopeAllPrivateChatsTemp +} + +// GetBotCommandScopeEnum return the enum type of this object +func (botCommandScopeAllPrivateChats *BotCommandScopeAllPrivateChats) GetBotCommandScopeEnum() BotCommandScopeEnum { + return BotCommandScopeAllPrivateChatsType +} + +// BotCommandScopeAllGroupChats A scope covering all group and supergroup chats +type BotCommandScopeAllGroupChats struct { + tdCommon +} + +// MessageType return the string telegram-type of BotCommandScopeAllGroupChats +func (botCommandScopeAllGroupChats *BotCommandScopeAllGroupChats) MessageType() string { + return "botCommandScopeAllGroupChats" +} + +// NewBotCommandScopeAllGroupChats creates a new BotCommandScopeAllGroupChats +// +func NewBotCommandScopeAllGroupChats() *BotCommandScopeAllGroupChats { + botCommandScopeAllGroupChatsTemp := BotCommandScopeAllGroupChats{ + tdCommon: tdCommon{Type: "botCommandScopeAllGroupChats"}, + } + + return &botCommandScopeAllGroupChatsTemp +} + +// GetBotCommandScopeEnum return the enum type of this object +func (botCommandScopeAllGroupChats *BotCommandScopeAllGroupChats) GetBotCommandScopeEnum() BotCommandScopeEnum { + return BotCommandScopeAllGroupChatsType +} + +// BotCommandScopeAllChatAdministrators A scope covering all group and supergroup chat administrators +type BotCommandScopeAllChatAdministrators struct { + tdCommon +} + +// MessageType return the string telegram-type of BotCommandScopeAllChatAdministrators +func (botCommandScopeAllChatAdministrators *BotCommandScopeAllChatAdministrators) MessageType() string { + return "botCommandScopeAllChatAdministrators" +} + +// NewBotCommandScopeAllChatAdministrators creates a new BotCommandScopeAllChatAdministrators +// +func NewBotCommandScopeAllChatAdministrators() *BotCommandScopeAllChatAdministrators { + botCommandScopeAllChatAdministratorsTemp := BotCommandScopeAllChatAdministrators{ + tdCommon: tdCommon{Type: "botCommandScopeAllChatAdministrators"}, + } + + return &botCommandScopeAllChatAdministratorsTemp +} + +// GetBotCommandScopeEnum return the enum type of this object +func (botCommandScopeAllChatAdministrators *BotCommandScopeAllChatAdministrators) GetBotCommandScopeEnum() BotCommandScopeEnum { + return BotCommandScopeAllChatAdministratorsType +} + +// BotCommandScopeChat A scope covering all members of a chat +type BotCommandScopeChat struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier +} + +// MessageType return the string telegram-type of BotCommandScopeChat +func (botCommandScopeChat *BotCommandScopeChat) MessageType() string { + return "botCommandScopeChat" +} + +// NewBotCommandScopeChat creates a new BotCommandScopeChat +// +// @param chatID Chat identifier +func NewBotCommandScopeChat(chatID int64) *BotCommandScopeChat { + botCommandScopeChatTemp := BotCommandScopeChat{ + tdCommon: tdCommon{Type: "botCommandScopeChat"}, + ChatID: chatID, + } + + return &botCommandScopeChatTemp +} + +// GetBotCommandScopeEnum return the enum type of this object +func (botCommandScopeChat *BotCommandScopeChat) GetBotCommandScopeEnum() BotCommandScopeEnum { + return BotCommandScopeChatType +} + +// BotCommandScopeChatAdministrators A scope covering all administrators of a chat +type BotCommandScopeChatAdministrators struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier +} + +// MessageType return the string telegram-type of BotCommandScopeChatAdministrators +func (botCommandScopeChatAdministrators *BotCommandScopeChatAdministrators) MessageType() string { + return "botCommandScopeChatAdministrators" +} + +// NewBotCommandScopeChatAdministrators creates a new BotCommandScopeChatAdministrators +// +// @param chatID Chat identifier +func NewBotCommandScopeChatAdministrators(chatID int64) *BotCommandScopeChatAdministrators { + botCommandScopeChatAdministratorsTemp := BotCommandScopeChatAdministrators{ + tdCommon: tdCommon{Type: "botCommandScopeChatAdministrators"}, + ChatID: chatID, + } + + return &botCommandScopeChatAdministratorsTemp +} + +// GetBotCommandScopeEnum return the enum type of this object +func (botCommandScopeChatAdministrators *BotCommandScopeChatAdministrators) GetBotCommandScopeEnum() BotCommandScopeEnum { + return BotCommandScopeChatAdministratorsType +} + +// BotCommandScopeChatMember A scope covering a member of a chat +type BotCommandScopeChatMember struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + UserID int64 `json:"user_id"` // User identifier +} + +// MessageType return the string telegram-type of BotCommandScopeChatMember +func (botCommandScopeChatMember *BotCommandScopeChatMember) MessageType() string { + return "botCommandScopeChatMember" +} + +// NewBotCommandScopeChatMember creates a new BotCommandScopeChatMember +// +// @param chatID Chat identifier +// @param userID User identifier +func NewBotCommandScopeChatMember(chatID int64, userID int64) *BotCommandScopeChatMember { + botCommandScopeChatMemberTemp := BotCommandScopeChatMember{ + tdCommon: tdCommon{Type: "botCommandScopeChatMember"}, + ChatID: chatID, + UserID: userID, + } + + return &botCommandScopeChatMemberTemp +} + +// GetBotCommandScopeEnum return the enum type of this object +func (botCommandScopeChatMember *BotCommandScopeChatMember) GetBotCommandScopeEnum() BotCommandScopeEnum { + return BotCommandScopeChatMemberType +} diff --git a/tdlib/botCommands.go b/tdlib/botCommands.go new file mode 100644 index 0000000..cbe0443 --- /dev/null +++ b/tdlib/botCommands.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// BotCommands Contains a list of bot commands +type BotCommands struct { + tdCommon + BotUserID int64 `json:"bot_user_id"` // Bot's user identifier + Commands []BotCommand `json:"commands"` // List of bot commands +} + +// MessageType return the string telegram-type of BotCommands +func (botCommands *BotCommands) MessageType() string { + return "botCommands" +} + +// NewBotCommands creates a new BotCommands +// +// @param botUserID Bot's user identifier +// @param commands List of bot commands +func NewBotCommands(botUserID int64, commands []BotCommand) *BotCommands { + botCommandsTemp := BotCommands{ + tdCommon: tdCommon{Type: "botCommands"}, + BotUserID: botUserID, + Commands: commands, + } + + return &botCommandsTemp +} diff --git a/tdlib/call.go b/tdlib/call.go new file mode 100644 index 0000000..8364230 --- /dev/null +++ b/tdlib/call.go @@ -0,0 +1,74 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// Call Describes a call +type Call struct { + tdCommon + ID int32 `json:"id"` // Call identifier, not persistent + UserID int64 `json:"user_id"` // Peer user identifier + IsOutgoing bool `json:"is_outgoing"` // True, if the call is outgoing + IsVideo bool `json:"is_video"` // True, if the call is a video call + 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 isVideo True, if the call is a video call +// @param state Call state +func NewCall(iD int32, userID int64, isOutgoing bool, isVideo bool, state CallState) *Call { + callTemp := Call{ + tdCommon: tdCommon{Type: "call"}, + ID: iD, + UserID: userID, + IsOutgoing: isOutgoing, + IsVideo: isVideo, + 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 int64 `json:"user_id"` // Peer user identifier + IsOutgoing bool `json:"is_outgoing"` // True, if the call is outgoing + IsVideo bool `json:"is_video"` // True, if the call is a video call + + }{} + 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 + call.IsVideo = tempObj.IsVideo + + fieldState, _ := unmarshalCallState(objMap["state"]) + call.State = fieldState + + return nil +} diff --git a/tdlib/callDiscardReason.go b/tdlib/callDiscardReason.go new file mode 100644 index 0000000..ff47ff7 --- /dev/null +++ b/tdlib/callDiscardReason.go @@ -0,0 +1,192 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CallDiscardReason Describes the reason why a call was discarded +type CallDiscardReason interface { + GetCallDiscardReasonEnum() CallDiscardReasonEnum +} + +// 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" +) + +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)) + } +} + +// 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 canceled 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 +} diff --git a/tdlib/callID.go b/tdlib/callID.go new file mode 100644 index 0000000..995e815 --- /dev/null +++ b/tdlib/callID.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/callProblem.go b/tdlib/callProblem.go new file mode 100644 index 0000000..3bd959a --- /dev/null +++ b/tdlib/callProblem.go @@ -0,0 +1,316 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CallProblem Describes the exact type of a problem with a call +type CallProblem interface { + GetCallProblemEnum() CallProblemEnum +} + +// CallProblemEnum Alias for abstract CallProblem 'Sub-Classes', used as constant-enum here +type CallProblemEnum string + +// CallProblem enums +const ( + CallProblemEchoType CallProblemEnum = "callProblemEcho" + CallProblemNoiseType CallProblemEnum = "callProblemNoise" + CallProblemInterruptionsType CallProblemEnum = "callProblemInterruptions" + CallProblemDistortedSpeechType CallProblemEnum = "callProblemDistortedSpeech" + CallProblemSilentLocalType CallProblemEnum = "callProblemSilentLocal" + CallProblemSilentRemoteType CallProblemEnum = "callProblemSilentRemote" + CallProblemDroppedType CallProblemEnum = "callProblemDropped" + CallProblemDistortedVideoType CallProblemEnum = "callProblemDistortedVideo" + CallProblemPixelatedVideoType CallProblemEnum = "callProblemPixelatedVideo" +) + +func unmarshalCallProblem(rawMsg *json.RawMessage) (CallProblem, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CallProblemEnum(objMap["@type"].(string)) { + case CallProblemEchoType: + var callProblemEcho CallProblemEcho + err := json.Unmarshal(*rawMsg, &callProblemEcho) + return &callProblemEcho, err + + case CallProblemNoiseType: + var callProblemNoise CallProblemNoise + err := json.Unmarshal(*rawMsg, &callProblemNoise) + return &callProblemNoise, err + + case CallProblemInterruptionsType: + var callProblemInterruptions CallProblemInterruptions + err := json.Unmarshal(*rawMsg, &callProblemInterruptions) + return &callProblemInterruptions, err + + case CallProblemDistortedSpeechType: + var callProblemDistortedSpeech CallProblemDistortedSpeech + err := json.Unmarshal(*rawMsg, &callProblemDistortedSpeech) + return &callProblemDistortedSpeech, err + + case CallProblemSilentLocalType: + var callProblemSilentLocal CallProblemSilentLocal + err := json.Unmarshal(*rawMsg, &callProblemSilentLocal) + return &callProblemSilentLocal, err + + case CallProblemSilentRemoteType: + var callProblemSilentRemote CallProblemSilentRemote + err := json.Unmarshal(*rawMsg, &callProblemSilentRemote) + return &callProblemSilentRemote, err + + case CallProblemDroppedType: + var callProblemDropped CallProblemDropped + err := json.Unmarshal(*rawMsg, &callProblemDropped) + return &callProblemDropped, err + + case CallProblemDistortedVideoType: + var callProblemDistortedVideo CallProblemDistortedVideo + err := json.Unmarshal(*rawMsg, &callProblemDistortedVideo) + return &callProblemDistortedVideo, err + + case CallProblemPixelatedVideoType: + var callProblemPixelatedVideo CallProblemPixelatedVideo + err := json.Unmarshal(*rawMsg, &callProblemPixelatedVideo) + return &callProblemPixelatedVideo, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// CallProblemEcho The user heard their own voice +type CallProblemEcho struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemEcho +func (callProblemEcho *CallProblemEcho) MessageType() string { + return "callProblemEcho" +} + +// NewCallProblemEcho creates a new CallProblemEcho +// +func NewCallProblemEcho() *CallProblemEcho { + callProblemEchoTemp := CallProblemEcho{ + tdCommon: tdCommon{Type: "callProblemEcho"}, + } + + return &callProblemEchoTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemEcho *CallProblemEcho) GetCallProblemEnum() CallProblemEnum { + return CallProblemEchoType +} + +// CallProblemNoise The user heard background noise +type CallProblemNoise struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemNoise +func (callProblemNoise *CallProblemNoise) MessageType() string { + return "callProblemNoise" +} + +// NewCallProblemNoise creates a new CallProblemNoise +// +func NewCallProblemNoise() *CallProblemNoise { + callProblemNoiseTemp := CallProblemNoise{ + tdCommon: tdCommon{Type: "callProblemNoise"}, + } + + return &callProblemNoiseTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemNoise *CallProblemNoise) GetCallProblemEnum() CallProblemEnum { + return CallProblemNoiseType +} + +// CallProblemInterruptions The other side kept disappearing +type CallProblemInterruptions struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemInterruptions +func (callProblemInterruptions *CallProblemInterruptions) MessageType() string { + return "callProblemInterruptions" +} + +// NewCallProblemInterruptions creates a new CallProblemInterruptions +// +func NewCallProblemInterruptions() *CallProblemInterruptions { + callProblemInterruptionsTemp := CallProblemInterruptions{ + tdCommon: tdCommon{Type: "callProblemInterruptions"}, + } + + return &callProblemInterruptionsTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemInterruptions *CallProblemInterruptions) GetCallProblemEnum() CallProblemEnum { + return CallProblemInterruptionsType +} + +// CallProblemDistortedSpeech The speech was distorted +type CallProblemDistortedSpeech struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemDistortedSpeech +func (callProblemDistortedSpeech *CallProblemDistortedSpeech) MessageType() string { + return "callProblemDistortedSpeech" +} + +// NewCallProblemDistortedSpeech creates a new CallProblemDistortedSpeech +// +func NewCallProblemDistortedSpeech() *CallProblemDistortedSpeech { + callProblemDistortedSpeechTemp := CallProblemDistortedSpeech{ + tdCommon: tdCommon{Type: "callProblemDistortedSpeech"}, + } + + return &callProblemDistortedSpeechTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemDistortedSpeech *CallProblemDistortedSpeech) GetCallProblemEnum() CallProblemEnum { + return CallProblemDistortedSpeechType +} + +// CallProblemSilentLocal The user couldn't hear the other side +type CallProblemSilentLocal struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemSilentLocal +func (callProblemSilentLocal *CallProblemSilentLocal) MessageType() string { + return "callProblemSilentLocal" +} + +// NewCallProblemSilentLocal creates a new CallProblemSilentLocal +// +func NewCallProblemSilentLocal() *CallProblemSilentLocal { + callProblemSilentLocalTemp := CallProblemSilentLocal{ + tdCommon: tdCommon{Type: "callProblemSilentLocal"}, + } + + return &callProblemSilentLocalTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemSilentLocal *CallProblemSilentLocal) GetCallProblemEnum() CallProblemEnum { + return CallProblemSilentLocalType +} + +// CallProblemSilentRemote The other side couldn't hear the user +type CallProblemSilentRemote struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemSilentRemote +func (callProblemSilentRemote *CallProblemSilentRemote) MessageType() string { + return "callProblemSilentRemote" +} + +// NewCallProblemSilentRemote creates a new CallProblemSilentRemote +// +func NewCallProblemSilentRemote() *CallProblemSilentRemote { + callProblemSilentRemoteTemp := CallProblemSilentRemote{ + tdCommon: tdCommon{Type: "callProblemSilentRemote"}, + } + + return &callProblemSilentRemoteTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemSilentRemote *CallProblemSilentRemote) GetCallProblemEnum() CallProblemEnum { + return CallProblemSilentRemoteType +} + +// CallProblemDropped The call ended unexpectedly +type CallProblemDropped struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemDropped +func (callProblemDropped *CallProblemDropped) MessageType() string { + return "callProblemDropped" +} + +// NewCallProblemDropped creates a new CallProblemDropped +// +func NewCallProblemDropped() *CallProblemDropped { + callProblemDroppedTemp := CallProblemDropped{ + tdCommon: tdCommon{Type: "callProblemDropped"}, + } + + return &callProblemDroppedTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemDropped *CallProblemDropped) GetCallProblemEnum() CallProblemEnum { + return CallProblemDroppedType +} + +// CallProblemDistortedVideo The video was distorted +type CallProblemDistortedVideo struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemDistortedVideo +func (callProblemDistortedVideo *CallProblemDistortedVideo) MessageType() string { + return "callProblemDistortedVideo" +} + +// NewCallProblemDistortedVideo creates a new CallProblemDistortedVideo +// +func NewCallProblemDistortedVideo() *CallProblemDistortedVideo { + callProblemDistortedVideoTemp := CallProblemDistortedVideo{ + tdCommon: tdCommon{Type: "callProblemDistortedVideo"}, + } + + return &callProblemDistortedVideoTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemDistortedVideo *CallProblemDistortedVideo) GetCallProblemEnum() CallProblemEnum { + return CallProblemDistortedVideoType +} + +// CallProblemPixelatedVideo The video was pixelated +type CallProblemPixelatedVideo struct { + tdCommon +} + +// MessageType return the string telegram-type of CallProblemPixelatedVideo +func (callProblemPixelatedVideo *CallProblemPixelatedVideo) MessageType() string { + return "callProblemPixelatedVideo" +} + +// NewCallProblemPixelatedVideo creates a new CallProblemPixelatedVideo +// +func NewCallProblemPixelatedVideo() *CallProblemPixelatedVideo { + callProblemPixelatedVideoTemp := CallProblemPixelatedVideo{ + tdCommon: tdCommon{Type: "callProblemPixelatedVideo"}, + } + + return &callProblemPixelatedVideoTemp +} + +// GetCallProblemEnum return the enum type of this object +func (callProblemPixelatedVideo *CallProblemPixelatedVideo) GetCallProblemEnum() CallProblemEnum { + return CallProblemPixelatedVideoType +} diff --git a/tdlib/callProtocol.go b/tdlib/callProtocol.go new file mode 100644 index 0000000..565da33 --- /dev/null +++ b/tdlib/callProtocol.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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"` // The minimum supported API layer; use 65 + MaxLayer int32 `json:"max_layer"` // The maximum supported API layer; use 65 + LibraryVersions []string `json:"library_versions"` // List of supported tgcalls versions +} + +// 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 The minimum supported API layer; use 65 +// @param maxLayer The maximum supported API layer; use 65 +// @param libraryVersions List of supported tgcalls versions +func NewCallProtocol(uDPP2p bool, uDPReflector bool, minLayer int32, maxLayer int32, libraryVersions []string) *CallProtocol { + callProtocolTemp := CallProtocol{ + tdCommon: tdCommon{Type: "callProtocol"}, + UDPP2p: uDPP2p, + UDPReflector: uDPReflector, + MinLayer: minLayer, + MaxLayer: maxLayer, + LibraryVersions: libraryVersions, + } + + return &callProtocolTemp +} diff --git a/tdlib/callServer.go b/tdlib/callServer.go new file mode 100644 index 0000000..b9419b4 --- /dev/null +++ b/tdlib/callServer.go @@ -0,0 +1,74 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// CallServer Describes a server for relaying call data +type CallServer struct { + tdCommon + ID JSONInt64 `json:"id"` // Server identifier + IPAddress string `json:"ip_address"` // Server IPv4 address + IPv6Address string `json:"ipv6_address"` // Server IPv6 address + Port int32 `json:"port"` // Server port number + Type CallServerType `json:"type"` // Server type +} + +// MessageType return the string telegram-type of CallServer +func (callServer *CallServer) MessageType() string { + return "callServer" +} + +// NewCallServer creates a new CallServer +// +// @param iD Server identifier +// @param iPAddress Server IPv4 address +// @param iPv6Address Server IPv6 address +// @param port Server port number +// @param typeParam Server type +func NewCallServer(iD JSONInt64, iPAddress string, iPv6Address string, port int32, typeParam CallServerType) *CallServer { + callServerTemp := CallServer{ + tdCommon: tdCommon{Type: "callServer"}, + ID: iD, + IPAddress: iPAddress, + IPv6Address: iPv6Address, + Port: port, + Type: typeParam, + } + + return &callServerTemp +} + +// UnmarshalJSON unmarshal to json +func (callServer *CallServer) 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"` // Server identifier + IPAddress string `json:"ip_address"` // Server IPv4 address + IPv6Address string `json:"ipv6_address"` // Server IPv6 address + Port int32 `json:"port"` // Server port number + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + callServer.tdCommon = tempObj.tdCommon + callServer.ID = tempObj.ID + callServer.IPAddress = tempObj.IPAddress + callServer.IPv6Address = tempObj.IPv6Address + callServer.Port = tempObj.Port + + fieldType, _ := unmarshalCallServerType(objMap["type"]) + callServer.Type = fieldType + + return nil +} diff --git a/tdlib/callServerType.go b/tdlib/callServerType.go new file mode 100644 index 0000000..9d2c11c --- /dev/null +++ b/tdlib/callServerType.go @@ -0,0 +1,114 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CallServerType Describes the type of a call server +type CallServerType interface { + GetCallServerTypeEnum() CallServerTypeEnum +} + +// CallServerTypeEnum Alias for abstract CallServerType 'Sub-Classes', used as constant-enum here +type CallServerTypeEnum string + +// CallServerType enums +const ( + CallServerTypeTelegramReflectorType CallServerTypeEnum = "callServerTypeTelegramReflector" + CallServerTypeWebrtcType CallServerTypeEnum = "callServerTypeWebrtc" +) + +func unmarshalCallServerType(rawMsg *json.RawMessage) (CallServerType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CallServerTypeEnum(objMap["@type"].(string)) { + case CallServerTypeTelegramReflectorType: + var callServerTypeTelegramReflector CallServerTypeTelegramReflector + err := json.Unmarshal(*rawMsg, &callServerTypeTelegramReflector) + return &callServerTypeTelegramReflector, err + + case CallServerTypeWebrtcType: + var callServerTypeWebrtc CallServerTypeWebrtc + err := json.Unmarshal(*rawMsg, &callServerTypeWebrtc) + return &callServerTypeWebrtc, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// CallServerTypeTelegramReflector A Telegram call reflector +type CallServerTypeTelegramReflector struct { + tdCommon + PeerTag []byte `json:"peer_tag"` // A peer tag to be used with the reflector +} + +// MessageType return the string telegram-type of CallServerTypeTelegramReflector +func (callServerTypeTelegramReflector *CallServerTypeTelegramReflector) MessageType() string { + return "callServerTypeTelegramReflector" +} + +// NewCallServerTypeTelegramReflector creates a new CallServerTypeTelegramReflector +// +// @param peerTag A peer tag to be used with the reflector +func NewCallServerTypeTelegramReflector(peerTag []byte) *CallServerTypeTelegramReflector { + callServerTypeTelegramReflectorTemp := CallServerTypeTelegramReflector{ + tdCommon: tdCommon{Type: "callServerTypeTelegramReflector"}, + PeerTag: peerTag, + } + + return &callServerTypeTelegramReflectorTemp +} + +// GetCallServerTypeEnum return the enum type of this object +func (callServerTypeTelegramReflector *CallServerTypeTelegramReflector) GetCallServerTypeEnum() CallServerTypeEnum { + return CallServerTypeTelegramReflectorType +} + +// CallServerTypeWebrtc A WebRTC server +type CallServerTypeWebrtc struct { + tdCommon + Username string `json:"username"` // Username to be used for authentication + Password string `json:"password"` // Authentication password + SupportsTurn bool `json:"supports_turn"` // True, if the server supports TURN + SupportsStun bool `json:"supports_stun"` // True, if the server supports STUN +} + +// MessageType return the string telegram-type of CallServerTypeWebrtc +func (callServerTypeWebrtc *CallServerTypeWebrtc) MessageType() string { + return "callServerTypeWebrtc" +} + +// NewCallServerTypeWebrtc creates a new CallServerTypeWebrtc +// +// @param username Username to be used for authentication +// @param password Authentication password +// @param supportsTurn True, if the server supports TURN +// @param supportsStun True, if the server supports STUN +func NewCallServerTypeWebrtc(username string, password string, supportsTurn bool, supportsStun bool) *CallServerTypeWebrtc { + callServerTypeWebrtcTemp := CallServerTypeWebrtc{ + tdCommon: tdCommon{Type: "callServerTypeWebrtc"}, + Username: username, + Password: password, + SupportsTurn: supportsTurn, + SupportsStun: supportsStun, + } + + return &callServerTypeWebrtcTemp +} + +// GetCallServerTypeEnum return the enum type of this object +func (callServerTypeWebrtc *CallServerTypeWebrtc) GetCallServerTypeEnum() CallServerTypeEnum { + return CallServerTypeWebrtcType +} diff --git a/tdlib/callState.go b/tdlib/callState.go new file mode 100644 index 0000000..088d303 --- /dev/null +++ b/tdlib/callState.go @@ -0,0 +1,286 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CallState Describes the current call state +type CallState interface { + GetCallStateEnum() CallStateEnum +} + +// 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" +) + +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)) + } +} + +// 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 + Servers []CallServer `json:"servers"` // List of available call servers + 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 + AllowP2p bool `json:"allow_p2p"` // True, if peer-to-peer connection is allowed by users privacy settings +} + +// 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 servers List of available call servers +// @param config A JSON-encoded call config +// @param encryptionKey Call encryption key +// @param emojis Encryption key emojis fingerprint +// @param allowP2p True, if peer-to-peer connection is allowed by users privacy settings +func NewCallStateReady(protocol *CallProtocol, servers []CallServer, config string, encryptionKey []byte, emojis []string, allowP2p bool) *CallStateReady { + callStateReadyTemp := CallStateReady{ + tdCommon: tdCommon{Type: "callStateReady"}, + Protocol: protocol, + Servers: servers, + Config: config, + EncryptionKey: encryptionKey, + Emojis: emojis, + AllowP2p: allowP2p, + } + + 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 +} diff --git a/tdlib/callbackQueryAnswer.go b/tdlib/callbackQueryAnswer.go new file mode 100644 index 0000000..3eb2aa0 --- /dev/null +++ b/tdlib/callbackQueryAnswer.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/callbackQueryPayload.go b/tdlib/callbackQueryPayload.go new file mode 100644 index 0000000..9af01ba --- /dev/null +++ b/tdlib/callbackQueryPayload.go @@ -0,0 +1,142 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CallbackQueryPayload Represents a payload of a callback query +type CallbackQueryPayload interface { + GetCallbackQueryPayloadEnum() CallbackQueryPayloadEnum +} + +// CallbackQueryPayloadEnum Alias for abstract CallbackQueryPayload 'Sub-Classes', used as constant-enum here +type CallbackQueryPayloadEnum string + +// CallbackQueryPayload enums +const ( + CallbackQueryPayloadDataType CallbackQueryPayloadEnum = "callbackQueryPayloadData" + CallbackQueryPayloadDataWithPasswordType CallbackQueryPayloadEnum = "callbackQueryPayloadDataWithPassword" + CallbackQueryPayloadGameType CallbackQueryPayloadEnum = "callbackQueryPayloadGame" +) + +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 CallbackQueryPayloadDataWithPasswordType: + var callbackQueryPayloadDataWithPassword CallbackQueryPayloadDataWithPassword + err := json.Unmarshal(*rawMsg, &callbackQueryPayloadDataWithPassword) + return &callbackQueryPayloadDataWithPassword, 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)) + } +} + +// CallbackQueryPayloadData The payload for 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 +} + +// CallbackQueryPayloadDataWithPassword The payload for a callback button requiring password +type CallbackQueryPayloadDataWithPassword struct { + tdCommon + Password string `json:"password"` // The password for the current user + Data []byte `json:"data"` // Data that was attached to the callback button +} + +// MessageType return the string telegram-type of CallbackQueryPayloadDataWithPassword +func (callbackQueryPayloadDataWithPassword *CallbackQueryPayloadDataWithPassword) MessageType() string { + return "callbackQueryPayloadDataWithPassword" +} + +// NewCallbackQueryPayloadDataWithPassword creates a new CallbackQueryPayloadDataWithPassword +// +// @param password The password for the current user +// @param data Data that was attached to the callback button +func NewCallbackQueryPayloadDataWithPassword(password string, data []byte) *CallbackQueryPayloadDataWithPassword { + callbackQueryPayloadDataWithPasswordTemp := CallbackQueryPayloadDataWithPassword{ + tdCommon: tdCommon{Type: "callbackQueryPayloadDataWithPassword"}, + Password: password, + Data: data, + } + + return &callbackQueryPayloadDataWithPasswordTemp +} + +// GetCallbackQueryPayloadEnum return the enum type of this object +func (callbackQueryPayloadDataWithPassword *CallbackQueryPayloadDataWithPassword) GetCallbackQueryPayloadEnum() CallbackQueryPayloadEnum { + return CallbackQueryPayloadDataWithPasswordType +} + +// CallbackQueryPayloadGame The payload for 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 +} diff --git a/tdlib/canTransferOwnershipResult.go b/tdlib/canTransferOwnershipResult.go new file mode 100644 index 0000000..27272fd --- /dev/null +++ b/tdlib/canTransferOwnershipResult.go @@ -0,0 +1,167 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CanTransferOwnershipResult Represents result of checking whether the current session can be used to transfer a chat ownership to another user +type CanTransferOwnershipResult interface { + GetCanTransferOwnershipResultEnum() CanTransferOwnershipResultEnum +} + +// CanTransferOwnershipResultEnum Alias for abstract CanTransferOwnershipResult 'Sub-Classes', used as constant-enum here +type CanTransferOwnershipResultEnum string + +// CanTransferOwnershipResult enums +const ( + CanTransferOwnershipResultOkType CanTransferOwnershipResultEnum = "canTransferOwnershipResultOk" + CanTransferOwnershipResultPasswordNeededType CanTransferOwnershipResultEnum = "canTransferOwnershipResultPasswordNeeded" + CanTransferOwnershipResultPasswordTooFreshType CanTransferOwnershipResultEnum = "canTransferOwnershipResultPasswordTooFresh" + CanTransferOwnershipResultSessionTooFreshType CanTransferOwnershipResultEnum = "canTransferOwnershipResultSessionTooFresh" +) + +func unmarshalCanTransferOwnershipResult(rawMsg *json.RawMessage) (CanTransferOwnershipResult, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CanTransferOwnershipResultEnum(objMap["@type"].(string)) { + case CanTransferOwnershipResultOkType: + var canTransferOwnershipResultOk CanTransferOwnershipResultOk + err := json.Unmarshal(*rawMsg, &canTransferOwnershipResultOk) + return &canTransferOwnershipResultOk, err + + case CanTransferOwnershipResultPasswordNeededType: + var canTransferOwnershipResultPasswordNeeded CanTransferOwnershipResultPasswordNeeded + err := json.Unmarshal(*rawMsg, &canTransferOwnershipResultPasswordNeeded) + return &canTransferOwnershipResultPasswordNeeded, err + + case CanTransferOwnershipResultPasswordTooFreshType: + var canTransferOwnershipResultPasswordTooFresh CanTransferOwnershipResultPasswordTooFresh + err := json.Unmarshal(*rawMsg, &canTransferOwnershipResultPasswordTooFresh) + return &canTransferOwnershipResultPasswordTooFresh, err + + case CanTransferOwnershipResultSessionTooFreshType: + var canTransferOwnershipResultSessionTooFresh CanTransferOwnershipResultSessionTooFresh + err := json.Unmarshal(*rawMsg, &canTransferOwnershipResultSessionTooFresh) + return &canTransferOwnershipResultSessionTooFresh, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// CanTransferOwnershipResultOk The session can be used +type CanTransferOwnershipResultOk struct { + tdCommon +} + +// MessageType return the string telegram-type of CanTransferOwnershipResultOk +func (canTransferOwnershipResultOk *CanTransferOwnershipResultOk) MessageType() string { + return "canTransferOwnershipResultOk" +} + +// NewCanTransferOwnershipResultOk creates a new CanTransferOwnershipResultOk +// +func NewCanTransferOwnershipResultOk() *CanTransferOwnershipResultOk { + canTransferOwnershipResultOkTemp := CanTransferOwnershipResultOk{ + tdCommon: tdCommon{Type: "canTransferOwnershipResultOk"}, + } + + return &canTransferOwnershipResultOkTemp +} + +// GetCanTransferOwnershipResultEnum return the enum type of this object +func (canTransferOwnershipResultOk *CanTransferOwnershipResultOk) GetCanTransferOwnershipResultEnum() CanTransferOwnershipResultEnum { + return CanTransferOwnershipResultOkType +} + +// CanTransferOwnershipResultPasswordNeeded The 2-step verification needs to be enabled first +type CanTransferOwnershipResultPasswordNeeded struct { + tdCommon +} + +// MessageType return the string telegram-type of CanTransferOwnershipResultPasswordNeeded +func (canTransferOwnershipResultPasswordNeeded *CanTransferOwnershipResultPasswordNeeded) MessageType() string { + return "canTransferOwnershipResultPasswordNeeded" +} + +// NewCanTransferOwnershipResultPasswordNeeded creates a new CanTransferOwnershipResultPasswordNeeded +// +func NewCanTransferOwnershipResultPasswordNeeded() *CanTransferOwnershipResultPasswordNeeded { + canTransferOwnershipResultPasswordNeededTemp := CanTransferOwnershipResultPasswordNeeded{ + tdCommon: tdCommon{Type: "canTransferOwnershipResultPasswordNeeded"}, + } + + return &canTransferOwnershipResultPasswordNeededTemp +} + +// GetCanTransferOwnershipResultEnum return the enum type of this object +func (canTransferOwnershipResultPasswordNeeded *CanTransferOwnershipResultPasswordNeeded) GetCanTransferOwnershipResultEnum() CanTransferOwnershipResultEnum { + return CanTransferOwnershipResultPasswordNeededType +} + +// CanTransferOwnershipResultPasswordTooFresh The 2-step verification was enabled recently, user needs to wait +type CanTransferOwnershipResultPasswordTooFresh struct { + tdCommon + RetryAfter int32 `json:"retry_after"` // Time left before the session can be used to transfer ownership of a chat, in seconds +} + +// MessageType return the string telegram-type of CanTransferOwnershipResultPasswordTooFresh +func (canTransferOwnershipResultPasswordTooFresh *CanTransferOwnershipResultPasswordTooFresh) MessageType() string { + return "canTransferOwnershipResultPasswordTooFresh" +} + +// NewCanTransferOwnershipResultPasswordTooFresh creates a new CanTransferOwnershipResultPasswordTooFresh +// +// @param retryAfter Time left before the session can be used to transfer ownership of a chat, in seconds +func NewCanTransferOwnershipResultPasswordTooFresh(retryAfter int32) *CanTransferOwnershipResultPasswordTooFresh { + canTransferOwnershipResultPasswordTooFreshTemp := CanTransferOwnershipResultPasswordTooFresh{ + tdCommon: tdCommon{Type: "canTransferOwnershipResultPasswordTooFresh"}, + RetryAfter: retryAfter, + } + + return &canTransferOwnershipResultPasswordTooFreshTemp +} + +// GetCanTransferOwnershipResultEnum return the enum type of this object +func (canTransferOwnershipResultPasswordTooFresh *CanTransferOwnershipResultPasswordTooFresh) GetCanTransferOwnershipResultEnum() CanTransferOwnershipResultEnum { + return CanTransferOwnershipResultPasswordTooFreshType +} + +// CanTransferOwnershipResultSessionTooFresh The session was created recently, user needs to wait +type CanTransferOwnershipResultSessionTooFresh struct { + tdCommon + RetryAfter int32 `json:"retry_after"` // Time left before the session can be used to transfer ownership of a chat, in seconds +} + +// MessageType return the string telegram-type of CanTransferOwnershipResultSessionTooFresh +func (canTransferOwnershipResultSessionTooFresh *CanTransferOwnershipResultSessionTooFresh) MessageType() string { + return "canTransferOwnershipResultSessionTooFresh" +} + +// NewCanTransferOwnershipResultSessionTooFresh creates a new CanTransferOwnershipResultSessionTooFresh +// +// @param retryAfter Time left before the session can be used to transfer ownership of a chat, in seconds +func NewCanTransferOwnershipResultSessionTooFresh(retryAfter int32) *CanTransferOwnershipResultSessionTooFresh { + canTransferOwnershipResultSessionTooFreshTemp := CanTransferOwnershipResultSessionTooFresh{ + tdCommon: tdCommon{Type: "canTransferOwnershipResultSessionTooFresh"}, + RetryAfter: retryAfter, + } + + return &canTransferOwnershipResultSessionTooFreshTemp +} + +// GetCanTransferOwnershipResultEnum return the enum type of this object +func (canTransferOwnershipResultSessionTooFresh *CanTransferOwnershipResultSessionTooFresh) GetCanTransferOwnershipResultEnum() CanTransferOwnershipResultEnum { + return CanTransferOwnershipResultSessionTooFreshType +} diff --git a/tdlib/chat.go b/tdlib/chat.go new file mode 100644 index 0000000..41d9e9c --- /dev/null +++ b/tdlib/chat.go @@ -0,0 +1,179 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 *ChatPhotoInfo `json:"photo"` // Chat photo; may be null + Permissions *ChatPermissions `json:"permissions"` // Actions that non-administrator chat members are allowed to take in the chat + LastMessage *Message `json:"last_message"` // Last message in the chat; may be null + Positions []ChatPosition `json:"positions"` // Positions of the chat in chat lists + IsMarkedAsUnread bool `json:"is_marked_as_unread"` // True, if the chat is marked as unread + IsBlocked bool `json:"is_blocked"` // True, if the chat is blocked by the current user and private messages from the chat can't be received + HasScheduledMessages bool `json:"has_scheduled_messages"` // True, if the chat has scheduled messages + CanBeDeletedOnlyForSelf bool `json:"can_be_deleted_only_for_self"` // True, if the chat messages can be deleted only for the current user while other users will continue to see the messages + CanBeDeletedForAllUsers bool `json:"can_be_deleted_for_all_users"` // True, if the chat messages can be deleted for all users + CanBeReported bool `json:"can_be_reported"` // True, if the chat can be reported to Telegram moderators through reportChat or reportChatPhoto + 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 + MessageTTLSetting int32 `json:"message_ttl_setting"` // Current message Time To Live setting (self-destruct timer) for the chat; 0 if not defined. TTL is counted from the time message or its content is viewed in secret chats and from the send date in other chats + ThemeName string `json:"theme_name"` // If non-empty, name of a theme set for the chat + ActionBar ChatActionBar `json:"action_bar"` // Describes actions which should be possible to do through a chat action bar; may be null + VoiceChat *VoiceChat `json:"voice_chat"` // Contains information about voice chat of the 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 application-specific data associated with the chat. (For example, the chat scroll position or local chat notification settings can be stored here.) Persistent if the 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 permissions Actions that non-administrator chat members are allowed to take in the chat +// @param lastMessage Last message in the chat; may be null +// @param positions Positions of the chat in chat lists +// @param isMarkedAsUnread True, if the chat is marked as unread +// @param isBlocked True, if the chat is blocked by the current user and private messages from the chat can't be received +// @param hasScheduledMessages True, if the chat has scheduled messages +// @param canBeDeletedOnlyForSelf True, if the chat messages can be deleted only for the current user while other users will continue to see the messages +// @param canBeDeletedForAllUsers True, if the chat messages can be deleted for all users +// @param canBeReported True, if the chat can be reported to Telegram moderators through reportChat or reportChatPhoto +// @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 messageTTLSetting Current message Time To Live setting (self-destruct timer) for the chat; 0 if not defined. TTL is counted from the time message or its content is viewed in secret chats and from the send date in other chats +// @param themeName If non-empty, name of a theme set for the chat +// @param actionBar Describes actions which should be possible to do through a chat action bar; may be null +// @param voiceChat Contains information about voice chat of the 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 application-specific data associated with the chat. (For example, the chat scroll position or local chat notification settings can be stored here.) Persistent if the message database is used +func NewChat(iD int64, typeParam ChatType, title string, photo *ChatPhotoInfo, permissions *ChatPermissions, lastMessage *Message, positions []ChatPosition, isMarkedAsUnread bool, isBlocked bool, hasScheduledMessages bool, canBeDeletedOnlyForSelf bool, canBeDeletedForAllUsers bool, canBeReported bool, defaultDisableNotification bool, unreadCount int32, lastReadInboxMessageID int64, lastReadOutboxMessageID int64, unreadMentionCount int32, notificationSettings *ChatNotificationSettings, messageTTLSetting int32, themeName string, actionBar ChatActionBar, voiceChat *VoiceChat, replyMarkupMessageID int64, draftMessage *DraftMessage, clientData string) *Chat { + chatTemp := Chat{ + tdCommon: tdCommon{Type: "chat"}, + ID: iD, + Type: typeParam, + Title: title, + Photo: photo, + Permissions: permissions, + LastMessage: lastMessage, + Positions: positions, + IsMarkedAsUnread: isMarkedAsUnread, + IsBlocked: isBlocked, + HasScheduledMessages: hasScheduledMessages, + CanBeDeletedOnlyForSelf: canBeDeletedOnlyForSelf, + CanBeDeletedForAllUsers: canBeDeletedForAllUsers, + CanBeReported: canBeReported, + DefaultDisableNotification: defaultDisableNotification, + UnreadCount: unreadCount, + LastReadInboxMessageID: lastReadInboxMessageID, + LastReadOutboxMessageID: lastReadOutboxMessageID, + UnreadMentionCount: unreadMentionCount, + NotificationSettings: notificationSettings, + MessageTTLSetting: messageTTLSetting, + ThemeName: themeName, + ActionBar: actionBar, + VoiceChat: voiceChat, + 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 *ChatPhotoInfo `json:"photo"` // Chat photo; may be null + Permissions *ChatPermissions `json:"permissions"` // Actions that non-administrator chat members are allowed to take in the chat + LastMessage *Message `json:"last_message"` // Last message in the chat; may be null + Positions []ChatPosition `json:"positions"` // Positions of the chat in chat lists + IsMarkedAsUnread bool `json:"is_marked_as_unread"` // True, if the chat is marked as unread + IsBlocked bool `json:"is_blocked"` // True, if the chat is blocked by the current user and private messages from the chat can't be received + HasScheduledMessages bool `json:"has_scheduled_messages"` // True, if the chat has scheduled messages + CanBeDeletedOnlyForSelf bool `json:"can_be_deleted_only_for_self"` // True, if the chat messages can be deleted only for the current user while other users will continue to see the messages + CanBeDeletedForAllUsers bool `json:"can_be_deleted_for_all_users"` // True, if the chat messages can be deleted for all users + CanBeReported bool `json:"can_be_reported"` // True, if the chat can be reported to Telegram moderators through reportChat or reportChatPhoto + 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 + MessageTTLSetting int32 `json:"message_ttl_setting"` // Current message Time To Live setting (self-destruct timer) for the chat; 0 if not defined. TTL is counted from the time message or its content is viewed in secret chats and from the send date in other chats + ThemeName string `json:"theme_name"` // If non-empty, name of a theme set for the chat + VoiceChat *VoiceChat `json:"voice_chat"` // Contains information about voice chat of the 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 application-specific data associated with the chat. (For example, the chat scroll position or local chat notification settings can be stored here.) Persistent if the 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.Permissions = tempObj.Permissions + chat.LastMessage = tempObj.LastMessage + chat.Positions = tempObj.Positions + chat.IsMarkedAsUnread = tempObj.IsMarkedAsUnread + chat.IsBlocked = tempObj.IsBlocked + chat.HasScheduledMessages = tempObj.HasScheduledMessages + chat.CanBeDeletedOnlyForSelf = tempObj.CanBeDeletedOnlyForSelf + chat.CanBeDeletedForAllUsers = tempObj.CanBeDeletedForAllUsers + 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.MessageTTLSetting = tempObj.MessageTTLSetting + chat.ThemeName = tempObj.ThemeName + chat.VoiceChat = tempObj.VoiceChat + chat.ReplyMarkupMessageID = tempObj.ReplyMarkupMessageID + chat.DraftMessage = tempObj.DraftMessage + chat.ClientData = tempObj.ClientData + + fieldType, _ := unmarshalChatType(objMap["type"]) + chat.Type = fieldType + + fieldActionBar, _ := unmarshalChatActionBar(objMap["action_bar"]) + chat.ActionBar = fieldActionBar + + return nil +} diff --git a/tdlib/chatAction.go b/tdlib/chatAction.go new file mode 100644 index 0000000..13dc82c --- /dev/null +++ b/tdlib/chatAction.go @@ -0,0 +1,486 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatAction Describes the different types of activity in a chat +type ChatAction interface { + GetChatActionEnum() ChatActionEnum +} + +// 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" + ChatActionChoosingStickerType ChatActionEnum = "chatActionChoosingSticker" + ChatActionChoosingLocationType ChatActionEnum = "chatActionChoosingLocation" + ChatActionChoosingContactType ChatActionEnum = "chatActionChoosingContact" + ChatActionStartPlayingGameType ChatActionEnum = "chatActionStartPlayingGame" + ChatActionRecordingVideoNoteType ChatActionEnum = "chatActionRecordingVideoNote" + ChatActionUploadingVideoNoteType ChatActionEnum = "chatActionUploadingVideoNote" + ChatActionCancelType ChatActionEnum = "chatActionCancel" +) + +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 ChatActionChoosingStickerType: + var chatActionChoosingSticker ChatActionChoosingSticker + err := json.Unmarshal(*rawMsg, &chatActionChoosingSticker) + return &chatActionChoosingSticker, 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)) + } +} + +// 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 +} + +// ChatActionChoosingSticker The user is picking a sticker to send +type ChatActionChoosingSticker struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionChoosingSticker +func (chatActionChoosingSticker *ChatActionChoosingSticker) MessageType() string { + return "chatActionChoosingSticker" +} + +// NewChatActionChoosingSticker creates a new ChatActionChoosingSticker +// +func NewChatActionChoosingSticker() *ChatActionChoosingSticker { + chatActionChoosingStickerTemp := ChatActionChoosingSticker{ + tdCommon: tdCommon{Type: "chatActionChoosingSticker"}, + } + + return &chatActionChoosingStickerTemp +} + +// GetChatActionEnum return the enum type of this object +func (chatActionChoosingSticker *ChatActionChoosingSticker) GetChatActionEnum() ChatActionEnum { + return ChatActionChoosingStickerType +} + +// 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 canceled 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 +} diff --git a/tdlib/chatActionBar.go b/tdlib/chatActionBar.go new file mode 100644 index 0000000..f6c8b3f --- /dev/null +++ b/tdlib/chatActionBar.go @@ -0,0 +1,232 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatActionBar Describes actions which should be possible to do through a chat action bar +type ChatActionBar interface { + GetChatActionBarEnum() ChatActionBarEnum +} + +// ChatActionBarEnum Alias for abstract ChatActionBar 'Sub-Classes', used as constant-enum here +type ChatActionBarEnum string + +// ChatActionBar enums +const ( + ChatActionBarReportSpamType ChatActionBarEnum = "chatActionBarReportSpam" + ChatActionBarReportUnrelatedLocationType ChatActionBarEnum = "chatActionBarReportUnrelatedLocation" + ChatActionBarInviteMembersType ChatActionBarEnum = "chatActionBarInviteMembers" + ChatActionBarReportAddBlockType ChatActionBarEnum = "chatActionBarReportAddBlock" + ChatActionBarAddContactType ChatActionBarEnum = "chatActionBarAddContact" + ChatActionBarSharePhoneNumberType ChatActionBarEnum = "chatActionBarSharePhoneNumber" +) + +func unmarshalChatActionBar(rawMsg *json.RawMessage) (ChatActionBar, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatActionBarEnum(objMap["@type"].(string)) { + case ChatActionBarReportSpamType: + var chatActionBarReportSpam ChatActionBarReportSpam + err := json.Unmarshal(*rawMsg, &chatActionBarReportSpam) + return &chatActionBarReportSpam, err + + case ChatActionBarReportUnrelatedLocationType: + var chatActionBarReportUnrelatedLocation ChatActionBarReportUnrelatedLocation + err := json.Unmarshal(*rawMsg, &chatActionBarReportUnrelatedLocation) + return &chatActionBarReportUnrelatedLocation, err + + case ChatActionBarInviteMembersType: + var chatActionBarInviteMembers ChatActionBarInviteMembers + err := json.Unmarshal(*rawMsg, &chatActionBarInviteMembers) + return &chatActionBarInviteMembers, err + + case ChatActionBarReportAddBlockType: + var chatActionBarReportAddBlock ChatActionBarReportAddBlock + err := json.Unmarshal(*rawMsg, &chatActionBarReportAddBlock) + return &chatActionBarReportAddBlock, err + + case ChatActionBarAddContactType: + var chatActionBarAddContact ChatActionBarAddContact + err := json.Unmarshal(*rawMsg, &chatActionBarAddContact) + return &chatActionBarAddContact, err + + case ChatActionBarSharePhoneNumberType: + var chatActionBarSharePhoneNumber ChatActionBarSharePhoneNumber + err := json.Unmarshal(*rawMsg, &chatActionBarSharePhoneNumber) + return &chatActionBarSharePhoneNumber, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// ChatActionBarReportSpam The chat can be reported as spam using the method reportChat with the reason chatReportReasonSpam +type ChatActionBarReportSpam struct { + tdCommon + CanUnarchive bool `json:"can_unarchive"` // If true, the chat was automatically archived and can be moved back to the main chat list using addChatToList simultaneously with setting chat notification settings to default using setChatNotificationSettings +} + +// MessageType return the string telegram-type of ChatActionBarReportSpam +func (chatActionBarReportSpam *ChatActionBarReportSpam) MessageType() string { + return "chatActionBarReportSpam" +} + +// NewChatActionBarReportSpam creates a new ChatActionBarReportSpam +// +// @param canUnarchive If true, the chat was automatically archived and can be moved back to the main chat list using addChatToList simultaneously with setting chat notification settings to default using setChatNotificationSettings +func NewChatActionBarReportSpam(canUnarchive bool) *ChatActionBarReportSpam { + chatActionBarReportSpamTemp := ChatActionBarReportSpam{ + tdCommon: tdCommon{Type: "chatActionBarReportSpam"}, + CanUnarchive: canUnarchive, + } + + return &chatActionBarReportSpamTemp +} + +// GetChatActionBarEnum return the enum type of this object +func (chatActionBarReportSpam *ChatActionBarReportSpam) GetChatActionBarEnum() ChatActionBarEnum { + return ChatActionBarReportSpamType +} + +// ChatActionBarReportUnrelatedLocation The chat is a location-based supergroup, which can be reported as having unrelated location using the method reportChat with the reason chatReportReasonUnrelatedLocation +type ChatActionBarReportUnrelatedLocation struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionBarReportUnrelatedLocation +func (chatActionBarReportUnrelatedLocation *ChatActionBarReportUnrelatedLocation) MessageType() string { + return "chatActionBarReportUnrelatedLocation" +} + +// NewChatActionBarReportUnrelatedLocation creates a new ChatActionBarReportUnrelatedLocation +// +func NewChatActionBarReportUnrelatedLocation() *ChatActionBarReportUnrelatedLocation { + chatActionBarReportUnrelatedLocationTemp := ChatActionBarReportUnrelatedLocation{ + tdCommon: tdCommon{Type: "chatActionBarReportUnrelatedLocation"}, + } + + return &chatActionBarReportUnrelatedLocationTemp +} + +// GetChatActionBarEnum return the enum type of this object +func (chatActionBarReportUnrelatedLocation *ChatActionBarReportUnrelatedLocation) GetChatActionBarEnum() ChatActionBarEnum { + return ChatActionBarReportUnrelatedLocationType +} + +// ChatActionBarInviteMembers The chat is a recently created group chat, to which new members can be invited +type ChatActionBarInviteMembers struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionBarInviteMembers +func (chatActionBarInviteMembers *ChatActionBarInviteMembers) MessageType() string { + return "chatActionBarInviteMembers" +} + +// NewChatActionBarInviteMembers creates a new ChatActionBarInviteMembers +// +func NewChatActionBarInviteMembers() *ChatActionBarInviteMembers { + chatActionBarInviteMembersTemp := ChatActionBarInviteMembers{ + tdCommon: tdCommon{Type: "chatActionBarInviteMembers"}, + } + + return &chatActionBarInviteMembersTemp +} + +// GetChatActionBarEnum return the enum type of this object +func (chatActionBarInviteMembers *ChatActionBarInviteMembers) GetChatActionBarEnum() ChatActionBarEnum { + return ChatActionBarInviteMembersType +} + +// ChatActionBarReportAddBlock The chat is a private or secret chat, which can be reported using the method reportChat, or the other user can be blocked using the method blockUser, or the other user can be added to the contact list using the method addContact +type ChatActionBarReportAddBlock struct { + tdCommon + CanUnarchive bool `json:"can_unarchive"` // If true, the chat was automatically archived and can be moved back to the main chat list using addChatToList simultaneously with setting chat notification settings to default using setChatNotificationSettings + Distance int32 `json:"distance"` // If non-negative, the current user was found by the peer through searchChatsNearby and this is the distance between the users +} + +// MessageType return the string telegram-type of ChatActionBarReportAddBlock +func (chatActionBarReportAddBlock *ChatActionBarReportAddBlock) MessageType() string { + return "chatActionBarReportAddBlock" +} + +// NewChatActionBarReportAddBlock creates a new ChatActionBarReportAddBlock +// +// @param canUnarchive If true, the chat was automatically archived and can be moved back to the main chat list using addChatToList simultaneously with setting chat notification settings to default using setChatNotificationSettings +// @param distance If non-negative, the current user was found by the peer through searchChatsNearby and this is the distance between the users +func NewChatActionBarReportAddBlock(canUnarchive bool, distance int32) *ChatActionBarReportAddBlock { + chatActionBarReportAddBlockTemp := ChatActionBarReportAddBlock{ + tdCommon: tdCommon{Type: "chatActionBarReportAddBlock"}, + CanUnarchive: canUnarchive, + Distance: distance, + } + + return &chatActionBarReportAddBlockTemp +} + +// GetChatActionBarEnum return the enum type of this object +func (chatActionBarReportAddBlock *ChatActionBarReportAddBlock) GetChatActionBarEnum() ChatActionBarEnum { + return ChatActionBarReportAddBlockType +} + +// ChatActionBarAddContact The chat is a private or secret chat and the other user can be added to the contact list using the method addContact +type ChatActionBarAddContact struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionBarAddContact +func (chatActionBarAddContact *ChatActionBarAddContact) MessageType() string { + return "chatActionBarAddContact" +} + +// NewChatActionBarAddContact creates a new ChatActionBarAddContact +// +func NewChatActionBarAddContact() *ChatActionBarAddContact { + chatActionBarAddContactTemp := ChatActionBarAddContact{ + tdCommon: tdCommon{Type: "chatActionBarAddContact"}, + } + + return &chatActionBarAddContactTemp +} + +// GetChatActionBarEnum return the enum type of this object +func (chatActionBarAddContact *ChatActionBarAddContact) GetChatActionBarEnum() ChatActionBarEnum { + return ChatActionBarAddContactType +} + +// ChatActionBarSharePhoneNumber The chat is a private or secret chat with a mutual contact and the user's phone number can be shared with the other user using the method sharePhoneNumber +type ChatActionBarSharePhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatActionBarSharePhoneNumber +func (chatActionBarSharePhoneNumber *ChatActionBarSharePhoneNumber) MessageType() string { + return "chatActionBarSharePhoneNumber" +} + +// NewChatActionBarSharePhoneNumber creates a new ChatActionBarSharePhoneNumber +// +func NewChatActionBarSharePhoneNumber() *ChatActionBarSharePhoneNumber { + chatActionBarSharePhoneNumberTemp := ChatActionBarSharePhoneNumber{ + tdCommon: tdCommon{Type: "chatActionBarSharePhoneNumber"}, + } + + return &chatActionBarSharePhoneNumberTemp +} + +// GetChatActionBarEnum return the enum type of this object +func (chatActionBarSharePhoneNumber *ChatActionBarSharePhoneNumber) GetChatActionBarEnum() ChatActionBarEnum { + return ChatActionBarSharePhoneNumberType +} diff --git a/tdlib/chatAdministrator.go b/tdlib/chatAdministrator.go new file mode 100644 index 0000000..4d6deb0 --- /dev/null +++ b/tdlib/chatAdministrator.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatAdministrator Contains information about a chat administrator +type ChatAdministrator struct { + tdCommon + UserID int64 `json:"user_id"` // User identifier of the administrator + CustomTitle string `json:"custom_title"` // Custom title of the administrator + IsOwner bool `json:"is_owner"` // True, if the user is the owner of the chat +} + +// MessageType return the string telegram-type of ChatAdministrator +func (chatAdministrator *ChatAdministrator) MessageType() string { + return "chatAdministrator" +} + +// NewChatAdministrator creates a new ChatAdministrator +// +// @param userID User identifier of the administrator +// @param customTitle Custom title of the administrator +// @param isOwner True, if the user is the owner of the chat +func NewChatAdministrator(userID int64, customTitle string, isOwner bool) *ChatAdministrator { + chatAdministratorTemp := ChatAdministrator{ + tdCommon: tdCommon{Type: "chatAdministrator"}, + UserID: userID, + CustomTitle: customTitle, + IsOwner: isOwner, + } + + return &chatAdministratorTemp +} diff --git a/tdlib/chatAdministrators.go b/tdlib/chatAdministrators.go new file mode 100644 index 0000000..3cf2db0 --- /dev/null +++ b/tdlib/chatAdministrators.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatAdministrators Represents a list of chat administrators +type ChatAdministrators struct { + tdCommon + Administrators []ChatAdministrator `json:"administrators"` // A list of chat administrators +} + +// MessageType return the string telegram-type of ChatAdministrators +func (chatAdministrators *ChatAdministrators) MessageType() string { + return "chatAdministrators" +} + +// NewChatAdministrators creates a new ChatAdministrators +// +// @param administrators A list of chat administrators +func NewChatAdministrators(administrators []ChatAdministrator) *ChatAdministrators { + chatAdministratorsTemp := ChatAdministrators{ + tdCommon: tdCommon{Type: "chatAdministrators"}, + Administrators: administrators, + } + + return &chatAdministratorsTemp +} diff --git a/tdlib/chatEvent.go b/tdlib/chatEvent.go new file mode 100644 index 0000000..c9f5b0d --- /dev/null +++ b/tdlib/chatEvent.go @@ -0,0 +1,69 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 int64 `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 int64, 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 int64 `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 +} diff --git a/tdlib/chatEventAction.go b/tdlib/chatEventAction.go new file mode 100644 index 0000000..09a9453 --- /dev/null +++ b/tdlib/chatEventAction.go @@ -0,0 +1,1310 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatEventAction Represents a chat event +type ChatEventAction interface { + GetChatEventActionEnum() ChatEventActionEnum +} + +// ChatEventActionEnum Alias for abstract ChatEventAction 'Sub-Classes', used as constant-enum here +type ChatEventActionEnum string + +// ChatEventAction enums +const ( + ChatEventMessageEditedType ChatEventActionEnum = "chatEventMessageEdited" + ChatEventMessageDeletedType ChatEventActionEnum = "chatEventMessageDeleted" + ChatEventPollStoppedType ChatEventActionEnum = "chatEventPollStopped" + ChatEventMessagePinnedType ChatEventActionEnum = "chatEventMessagePinned" + ChatEventMessageUnpinnedType ChatEventActionEnum = "chatEventMessageUnpinned" + ChatEventMemberJoinedType ChatEventActionEnum = "chatEventMemberJoined" + ChatEventMemberJoinedByInviteLinkType ChatEventActionEnum = "chatEventMemberJoinedByInviteLink" + ChatEventMemberLeftType ChatEventActionEnum = "chatEventMemberLeft" + ChatEventMemberInvitedType ChatEventActionEnum = "chatEventMemberInvited" + ChatEventMemberPromotedType ChatEventActionEnum = "chatEventMemberPromoted" + ChatEventMemberRestrictedType ChatEventActionEnum = "chatEventMemberRestricted" + ChatEventTitleChangedType ChatEventActionEnum = "chatEventTitleChanged" + ChatEventPermissionsChangedType ChatEventActionEnum = "chatEventPermissionsChanged" + ChatEventDescriptionChangedType ChatEventActionEnum = "chatEventDescriptionChanged" + ChatEventUsernameChangedType ChatEventActionEnum = "chatEventUsernameChanged" + ChatEventPhotoChangedType ChatEventActionEnum = "chatEventPhotoChanged" + ChatEventInvitesToggledType ChatEventActionEnum = "chatEventInvitesToggled" + ChatEventLinkedChatChangedType ChatEventActionEnum = "chatEventLinkedChatChanged" + ChatEventSlowModeDelayChangedType ChatEventActionEnum = "chatEventSlowModeDelayChanged" + ChatEventMessageTTLSettingChangedType ChatEventActionEnum = "chatEventMessageTtlSettingChanged" + ChatEventSignMessagesToggledType ChatEventActionEnum = "chatEventSignMessagesToggled" + ChatEventStickerSetChangedType ChatEventActionEnum = "chatEventStickerSetChanged" + ChatEventLocationChangedType ChatEventActionEnum = "chatEventLocationChanged" + ChatEventIsAllHistoryAvailableToggledType ChatEventActionEnum = "chatEventIsAllHistoryAvailableToggled" + ChatEventInviteLinkEditedType ChatEventActionEnum = "chatEventInviteLinkEdited" + ChatEventInviteLinkRevokedType ChatEventActionEnum = "chatEventInviteLinkRevoked" + ChatEventInviteLinkDeletedType ChatEventActionEnum = "chatEventInviteLinkDeleted" + ChatEventVoiceChatCreatedType ChatEventActionEnum = "chatEventVoiceChatCreated" + ChatEventVoiceChatDiscardedType ChatEventActionEnum = "chatEventVoiceChatDiscarded" + ChatEventVoiceChatParticipantIsMutedToggledType ChatEventActionEnum = "chatEventVoiceChatParticipantIsMutedToggled" + ChatEventVoiceChatParticipantVolumeLevelChangedType ChatEventActionEnum = "chatEventVoiceChatParticipantVolumeLevelChanged" + ChatEventVoiceChatMuteNewParticipantsToggledType ChatEventActionEnum = "chatEventVoiceChatMuteNewParticipantsToggled" +) + +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 ChatEventPollStoppedType: + var chatEventPollStopped ChatEventPollStopped + err := json.Unmarshal(*rawMsg, &chatEventPollStopped) + return &chatEventPollStopped, 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 ChatEventMemberJoinedByInviteLinkType: + var chatEventMemberJoinedByInviteLink ChatEventMemberJoinedByInviteLink + err := json.Unmarshal(*rawMsg, &chatEventMemberJoinedByInviteLink) + return &chatEventMemberJoinedByInviteLink, 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 ChatEventPermissionsChangedType: + var chatEventPermissionsChanged ChatEventPermissionsChanged + err := json.Unmarshal(*rawMsg, &chatEventPermissionsChanged) + return &chatEventPermissionsChanged, 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 ChatEventLinkedChatChangedType: + var chatEventLinkedChatChanged ChatEventLinkedChatChanged + err := json.Unmarshal(*rawMsg, &chatEventLinkedChatChanged) + return &chatEventLinkedChatChanged, err + + case ChatEventSlowModeDelayChangedType: + var chatEventSlowModeDelayChanged ChatEventSlowModeDelayChanged + err := json.Unmarshal(*rawMsg, &chatEventSlowModeDelayChanged) + return &chatEventSlowModeDelayChanged, err + + case ChatEventMessageTTLSettingChangedType: + var chatEventMessageTTLSettingChanged ChatEventMessageTTLSettingChanged + err := json.Unmarshal(*rawMsg, &chatEventMessageTTLSettingChanged) + return &chatEventMessageTTLSettingChanged, 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 ChatEventLocationChangedType: + var chatEventLocationChanged ChatEventLocationChanged + err := json.Unmarshal(*rawMsg, &chatEventLocationChanged) + return &chatEventLocationChanged, err + + case ChatEventIsAllHistoryAvailableToggledType: + var chatEventIsAllHistoryAvailableToggled ChatEventIsAllHistoryAvailableToggled + err := json.Unmarshal(*rawMsg, &chatEventIsAllHistoryAvailableToggled) + return &chatEventIsAllHistoryAvailableToggled, err + + case ChatEventInviteLinkEditedType: + var chatEventInviteLinkEdited ChatEventInviteLinkEdited + err := json.Unmarshal(*rawMsg, &chatEventInviteLinkEdited) + return &chatEventInviteLinkEdited, err + + case ChatEventInviteLinkRevokedType: + var chatEventInviteLinkRevoked ChatEventInviteLinkRevoked + err := json.Unmarshal(*rawMsg, &chatEventInviteLinkRevoked) + return &chatEventInviteLinkRevoked, err + + case ChatEventInviteLinkDeletedType: + var chatEventInviteLinkDeleted ChatEventInviteLinkDeleted + err := json.Unmarshal(*rawMsg, &chatEventInviteLinkDeleted) + return &chatEventInviteLinkDeleted, err + + case ChatEventVoiceChatCreatedType: + var chatEventVoiceChatCreated ChatEventVoiceChatCreated + err := json.Unmarshal(*rawMsg, &chatEventVoiceChatCreated) + return &chatEventVoiceChatCreated, err + + case ChatEventVoiceChatDiscardedType: + var chatEventVoiceChatDiscarded ChatEventVoiceChatDiscarded + err := json.Unmarshal(*rawMsg, &chatEventVoiceChatDiscarded) + return &chatEventVoiceChatDiscarded, err + + case ChatEventVoiceChatParticipantIsMutedToggledType: + var chatEventVoiceChatParticipantIsMutedToggled ChatEventVoiceChatParticipantIsMutedToggled + err := json.Unmarshal(*rawMsg, &chatEventVoiceChatParticipantIsMutedToggled) + return &chatEventVoiceChatParticipantIsMutedToggled, err + + case ChatEventVoiceChatParticipantVolumeLevelChangedType: + var chatEventVoiceChatParticipantVolumeLevelChanged ChatEventVoiceChatParticipantVolumeLevelChanged + err := json.Unmarshal(*rawMsg, &chatEventVoiceChatParticipantVolumeLevelChanged) + return &chatEventVoiceChatParticipantVolumeLevelChanged, err + + case ChatEventVoiceChatMuteNewParticipantsToggledType: + var chatEventVoiceChatMuteNewParticipantsToggled ChatEventVoiceChatMuteNewParticipantsToggled + err := json.Unmarshal(*rawMsg, &chatEventVoiceChatMuteNewParticipantsToggled) + return &chatEventVoiceChatMuteNewParticipantsToggled, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 +} + +// ChatEventPollStopped A poll in a message was stopped +type ChatEventPollStopped struct { + tdCommon + Message *Message `json:"message"` // The message with the poll +} + +// MessageType return the string telegram-type of ChatEventPollStopped +func (chatEventPollStopped *ChatEventPollStopped) MessageType() string { + return "chatEventPollStopped" +} + +// NewChatEventPollStopped creates a new ChatEventPollStopped +// +// @param message The message with the poll +func NewChatEventPollStopped(message *Message) *ChatEventPollStopped { + chatEventPollStoppedTemp := ChatEventPollStopped{ + tdCommon: tdCommon{Type: "chatEventPollStopped"}, + Message: message, + } + + return &chatEventPollStoppedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventPollStopped *ChatEventPollStopped) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventPollStoppedType +} + +// 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 + Message *Message `json:"message"` // Unpinned message +} + +// MessageType return the string telegram-type of ChatEventMessageUnpinned +func (chatEventMessageUnpinned *ChatEventMessageUnpinned) MessageType() string { + return "chatEventMessageUnpinned" +} + +// NewChatEventMessageUnpinned creates a new ChatEventMessageUnpinned +// +// @param message Unpinned message +func NewChatEventMessageUnpinned(message *Message) *ChatEventMessageUnpinned { + chatEventMessageUnpinnedTemp := ChatEventMessageUnpinned{ + tdCommon: tdCommon{Type: "chatEventMessageUnpinned"}, + Message: message, + } + + 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 +} + +// ChatEventMemberJoinedByInviteLink A new member joined the chat by an invite link +type ChatEventMemberJoinedByInviteLink struct { + tdCommon + InviteLink *ChatInviteLink `json:"invite_link"` // Invite link used to join the chat +} + +// MessageType return the string telegram-type of ChatEventMemberJoinedByInviteLink +func (chatEventMemberJoinedByInviteLink *ChatEventMemberJoinedByInviteLink) MessageType() string { + return "chatEventMemberJoinedByInviteLink" +} + +// NewChatEventMemberJoinedByInviteLink creates a new ChatEventMemberJoinedByInviteLink +// +// @param inviteLink Invite link used to join the chat +func NewChatEventMemberJoinedByInviteLink(inviteLink *ChatInviteLink) *ChatEventMemberJoinedByInviteLink { + chatEventMemberJoinedByInviteLinkTemp := ChatEventMemberJoinedByInviteLink{ + tdCommon: tdCommon{Type: "chatEventMemberJoinedByInviteLink"}, + InviteLink: inviteLink, + } + + return &chatEventMemberJoinedByInviteLinkTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMemberJoinedByInviteLink *ChatEventMemberJoinedByInviteLink) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMemberJoinedByInviteLinkType +} + +// 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 int64 `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 int64, 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 int64 `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 int64 `json:"user_id"` // Affected 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 Affected chat member user identifier +// @param oldStatus Previous status of the chat member +// @param newStatus New status of the chat member +func NewChatEventMemberPromoted(userID int64, 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 int64 `json:"user_id"` // Affected 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 + MemberID MessageSender `json:"member_id"` // Affected chat member 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 memberID Affected chat member identifier +// @param oldStatus Previous status of the chat member +// @param newStatus New status of the chat member +func NewChatEventMemberRestricted(memberID MessageSender, oldStatus ChatMemberStatus, newStatus ChatMemberStatus) *ChatEventMemberRestricted { + chatEventMemberRestrictedTemp := ChatEventMemberRestricted{ + tdCommon: tdCommon{Type: "chatEventMemberRestricted"}, + MemberID: memberID, + 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 + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatEventMemberRestricted.tdCommon = tempObj.tdCommon + + fieldMemberID, _ := unmarshalMessageSender(objMap["member_id"]) + chatEventMemberRestricted.MemberID = fieldMemberID + + 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 +} + +// ChatEventPermissionsChanged The chat permissions was changed +type ChatEventPermissionsChanged struct { + tdCommon + OldPermissions *ChatPermissions `json:"old_permissions"` // Previous chat permissions + NewPermissions *ChatPermissions `json:"new_permissions"` // New chat permissions +} + +// MessageType return the string telegram-type of ChatEventPermissionsChanged +func (chatEventPermissionsChanged *ChatEventPermissionsChanged) MessageType() string { + return "chatEventPermissionsChanged" +} + +// NewChatEventPermissionsChanged creates a new ChatEventPermissionsChanged +// +// @param oldPermissions Previous chat permissions +// @param newPermissions New chat permissions +func NewChatEventPermissionsChanged(oldPermissions *ChatPermissions, newPermissions *ChatPermissions) *ChatEventPermissionsChanged { + chatEventPermissionsChangedTemp := ChatEventPermissionsChanged{ + tdCommon: tdCommon{Type: "chatEventPermissionsChanged"}, + OldPermissions: oldPermissions, + NewPermissions: newPermissions, + } + + return &chatEventPermissionsChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventPermissionsChanged *ChatEventPermissionsChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventPermissionsChangedType +} + +// 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 can_invite_users permission of a supergroup chat was toggled +type ChatEventInvitesToggled struct { + tdCommon + CanInviteUsers bool `json:"can_invite_users"` // New value of can_invite_users permission +} + +// MessageType return the string telegram-type of ChatEventInvitesToggled +func (chatEventInvitesToggled *ChatEventInvitesToggled) MessageType() string { + return "chatEventInvitesToggled" +} + +// NewChatEventInvitesToggled creates a new ChatEventInvitesToggled +// +// @param canInviteUsers New value of can_invite_users permission +func NewChatEventInvitesToggled(canInviteUsers bool) *ChatEventInvitesToggled { + chatEventInvitesToggledTemp := ChatEventInvitesToggled{ + tdCommon: tdCommon{Type: "chatEventInvitesToggled"}, + CanInviteUsers: canInviteUsers, + } + + return &chatEventInvitesToggledTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventInvitesToggled *ChatEventInvitesToggled) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventInvitesToggledType +} + +// ChatEventLinkedChatChanged The linked chat of a supergroup was changed +type ChatEventLinkedChatChanged struct { + tdCommon + OldLinkedChatID int64 `json:"old_linked_chat_id"` // Previous supergroup linked chat identifier + NewLinkedChatID int64 `json:"new_linked_chat_id"` // New supergroup linked chat identifier +} + +// MessageType return the string telegram-type of ChatEventLinkedChatChanged +func (chatEventLinkedChatChanged *ChatEventLinkedChatChanged) MessageType() string { + return "chatEventLinkedChatChanged" +} + +// NewChatEventLinkedChatChanged creates a new ChatEventLinkedChatChanged +// +// @param oldLinkedChatID Previous supergroup linked chat identifier +// @param newLinkedChatID New supergroup linked chat identifier +func NewChatEventLinkedChatChanged(oldLinkedChatID int64, newLinkedChatID int64) *ChatEventLinkedChatChanged { + chatEventLinkedChatChangedTemp := ChatEventLinkedChatChanged{ + tdCommon: tdCommon{Type: "chatEventLinkedChatChanged"}, + OldLinkedChatID: oldLinkedChatID, + NewLinkedChatID: newLinkedChatID, + } + + return &chatEventLinkedChatChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventLinkedChatChanged *ChatEventLinkedChatChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventLinkedChatChangedType +} + +// ChatEventSlowModeDelayChanged The slow_mode_delay setting of a supergroup was changed +type ChatEventSlowModeDelayChanged struct { + tdCommon + OldSlowModeDelay int32 `json:"old_slow_mode_delay"` // Previous value of slow_mode_delay + NewSlowModeDelay int32 `json:"new_slow_mode_delay"` // New value of slow_mode_delay +} + +// MessageType return the string telegram-type of ChatEventSlowModeDelayChanged +func (chatEventSlowModeDelayChanged *ChatEventSlowModeDelayChanged) MessageType() string { + return "chatEventSlowModeDelayChanged" +} + +// NewChatEventSlowModeDelayChanged creates a new ChatEventSlowModeDelayChanged +// +// @param oldSlowModeDelay Previous value of slow_mode_delay +// @param newSlowModeDelay New value of slow_mode_delay +func NewChatEventSlowModeDelayChanged(oldSlowModeDelay int32, newSlowModeDelay int32) *ChatEventSlowModeDelayChanged { + chatEventSlowModeDelayChangedTemp := ChatEventSlowModeDelayChanged{ + tdCommon: tdCommon{Type: "chatEventSlowModeDelayChanged"}, + OldSlowModeDelay: oldSlowModeDelay, + NewSlowModeDelay: newSlowModeDelay, + } + + return &chatEventSlowModeDelayChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventSlowModeDelayChanged *ChatEventSlowModeDelayChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventSlowModeDelayChangedType +} + +// ChatEventMessageTTLSettingChanged The message TTL setting was changed +type ChatEventMessageTTLSettingChanged struct { + tdCommon + OldMessageTTLSetting int32 `json:"old_message_ttl_setting"` // Previous value of message_ttl_setting + NewMessageTTLSetting int32 `json:"new_message_ttl_setting"` // New value of message_ttl_setting +} + +// MessageType return the string telegram-type of ChatEventMessageTTLSettingChanged +func (chatEventMessageTTLSettingChanged *ChatEventMessageTTLSettingChanged) MessageType() string { + return "chatEventMessageTtlSettingChanged" +} + +// NewChatEventMessageTTLSettingChanged creates a new ChatEventMessageTTLSettingChanged +// +// @param oldMessageTTLSetting Previous value of message_ttl_setting +// @param newMessageTTLSetting New value of message_ttl_setting +func NewChatEventMessageTTLSettingChanged(oldMessageTTLSetting int32, newMessageTTLSetting int32) *ChatEventMessageTTLSettingChanged { + chatEventMessageTTLSettingChangedTemp := ChatEventMessageTTLSettingChanged{ + tdCommon: tdCommon{Type: "chatEventMessageTtlSettingChanged"}, + OldMessageTTLSetting: oldMessageTTLSetting, + NewMessageTTLSetting: newMessageTTLSetting, + } + + return &chatEventMessageTTLSettingChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventMessageTTLSettingChanged *ChatEventMessageTTLSettingChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventMessageTTLSettingChangedType +} + +// 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 +} + +// ChatEventLocationChanged The supergroup location was changed +type ChatEventLocationChanged struct { + tdCommon + OldLocation *ChatLocation `json:"old_location"` // Previous location; may be null + NewLocation *ChatLocation `json:"new_location"` // New location; may be null +} + +// MessageType return the string telegram-type of ChatEventLocationChanged +func (chatEventLocationChanged *ChatEventLocationChanged) MessageType() string { + return "chatEventLocationChanged" +} + +// NewChatEventLocationChanged creates a new ChatEventLocationChanged +// +// @param oldLocation Previous location; may be null +// @param newLocation New location; may be null +func NewChatEventLocationChanged(oldLocation *ChatLocation, newLocation *ChatLocation) *ChatEventLocationChanged { + chatEventLocationChangedTemp := ChatEventLocationChanged{ + tdCommon: tdCommon{Type: "chatEventLocationChanged"}, + OldLocation: oldLocation, + NewLocation: newLocation, + } + + return &chatEventLocationChangedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventLocationChanged *ChatEventLocationChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventLocationChangedType +} + +// 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 +} + +// ChatEventInviteLinkEdited A chat invite link was edited +type ChatEventInviteLinkEdited struct { + tdCommon + OldInviteLink *ChatInviteLink `json:"old_invite_link"` // Previous information about the invite link + NewInviteLink *ChatInviteLink `json:"new_invite_link"` // New information about the invite link +} + +// MessageType return the string telegram-type of ChatEventInviteLinkEdited +func (chatEventInviteLinkEdited *ChatEventInviteLinkEdited) MessageType() string { + return "chatEventInviteLinkEdited" +} + +// NewChatEventInviteLinkEdited creates a new ChatEventInviteLinkEdited +// +// @param oldInviteLink Previous information about the invite link +// @param newInviteLink New information about the invite link +func NewChatEventInviteLinkEdited(oldInviteLink *ChatInviteLink, newInviteLink *ChatInviteLink) *ChatEventInviteLinkEdited { + chatEventInviteLinkEditedTemp := ChatEventInviteLinkEdited{ + tdCommon: tdCommon{Type: "chatEventInviteLinkEdited"}, + OldInviteLink: oldInviteLink, + NewInviteLink: newInviteLink, + } + + return &chatEventInviteLinkEditedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventInviteLinkEdited *ChatEventInviteLinkEdited) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventInviteLinkEditedType +} + +// ChatEventInviteLinkRevoked A chat invite link was revoked +type ChatEventInviteLinkRevoked struct { + tdCommon + InviteLink *ChatInviteLink `json:"invite_link"` // The invite link +} + +// MessageType return the string telegram-type of ChatEventInviteLinkRevoked +func (chatEventInviteLinkRevoked *ChatEventInviteLinkRevoked) MessageType() string { + return "chatEventInviteLinkRevoked" +} + +// NewChatEventInviteLinkRevoked creates a new ChatEventInviteLinkRevoked +// +// @param inviteLink The invite link +func NewChatEventInviteLinkRevoked(inviteLink *ChatInviteLink) *ChatEventInviteLinkRevoked { + chatEventInviteLinkRevokedTemp := ChatEventInviteLinkRevoked{ + tdCommon: tdCommon{Type: "chatEventInviteLinkRevoked"}, + InviteLink: inviteLink, + } + + return &chatEventInviteLinkRevokedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventInviteLinkRevoked *ChatEventInviteLinkRevoked) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventInviteLinkRevokedType +} + +// ChatEventInviteLinkDeleted A revoked chat invite link was deleted +type ChatEventInviteLinkDeleted struct { + tdCommon + InviteLink *ChatInviteLink `json:"invite_link"` // The invite link +} + +// MessageType return the string telegram-type of ChatEventInviteLinkDeleted +func (chatEventInviteLinkDeleted *ChatEventInviteLinkDeleted) MessageType() string { + return "chatEventInviteLinkDeleted" +} + +// NewChatEventInviteLinkDeleted creates a new ChatEventInviteLinkDeleted +// +// @param inviteLink The invite link +func NewChatEventInviteLinkDeleted(inviteLink *ChatInviteLink) *ChatEventInviteLinkDeleted { + chatEventInviteLinkDeletedTemp := ChatEventInviteLinkDeleted{ + tdCommon: tdCommon{Type: "chatEventInviteLinkDeleted"}, + InviteLink: inviteLink, + } + + return &chatEventInviteLinkDeletedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventInviteLinkDeleted *ChatEventInviteLinkDeleted) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventInviteLinkDeletedType +} + +// ChatEventVoiceChatCreated A voice chat was created +type ChatEventVoiceChatCreated struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Identifier of the voice chat. The voice chat can be received through the method getGroupCall +} + +// MessageType return the string telegram-type of ChatEventVoiceChatCreated +func (chatEventVoiceChatCreated *ChatEventVoiceChatCreated) MessageType() string { + return "chatEventVoiceChatCreated" +} + +// NewChatEventVoiceChatCreated creates a new ChatEventVoiceChatCreated +// +// @param groupCallID Identifier of the voice chat. The voice chat can be received through the method getGroupCall +func NewChatEventVoiceChatCreated(groupCallID int32) *ChatEventVoiceChatCreated { + chatEventVoiceChatCreatedTemp := ChatEventVoiceChatCreated{ + tdCommon: tdCommon{Type: "chatEventVoiceChatCreated"}, + GroupCallID: groupCallID, + } + + return &chatEventVoiceChatCreatedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventVoiceChatCreated *ChatEventVoiceChatCreated) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventVoiceChatCreatedType +} + +// ChatEventVoiceChatDiscarded A voice chat was discarded +type ChatEventVoiceChatDiscarded struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Identifier of the voice chat. The voice chat can be received through the method getGroupCall +} + +// MessageType return the string telegram-type of ChatEventVoiceChatDiscarded +func (chatEventVoiceChatDiscarded *ChatEventVoiceChatDiscarded) MessageType() string { + return "chatEventVoiceChatDiscarded" +} + +// NewChatEventVoiceChatDiscarded creates a new ChatEventVoiceChatDiscarded +// +// @param groupCallID Identifier of the voice chat. The voice chat can be received through the method getGroupCall +func NewChatEventVoiceChatDiscarded(groupCallID int32) *ChatEventVoiceChatDiscarded { + chatEventVoiceChatDiscardedTemp := ChatEventVoiceChatDiscarded{ + tdCommon: tdCommon{Type: "chatEventVoiceChatDiscarded"}, + GroupCallID: groupCallID, + } + + return &chatEventVoiceChatDiscardedTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventVoiceChatDiscarded *ChatEventVoiceChatDiscarded) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventVoiceChatDiscardedType +} + +// ChatEventVoiceChatParticipantIsMutedToggled A voice chat participant was muted or unmuted +type ChatEventVoiceChatParticipantIsMutedToggled struct { + tdCommon + ParticipantID MessageSender `json:"participant_id"` // Identifier of the affected group call participant + IsMuted bool `json:"is_muted"` // New value of is_muted +} + +// MessageType return the string telegram-type of ChatEventVoiceChatParticipantIsMutedToggled +func (chatEventVoiceChatParticipantIsMutedToggled *ChatEventVoiceChatParticipantIsMutedToggled) MessageType() string { + return "chatEventVoiceChatParticipantIsMutedToggled" +} + +// NewChatEventVoiceChatParticipantIsMutedToggled creates a new ChatEventVoiceChatParticipantIsMutedToggled +// +// @param participantID Identifier of the affected group call participant +// @param isMuted New value of is_muted +func NewChatEventVoiceChatParticipantIsMutedToggled(participantID MessageSender, isMuted bool) *ChatEventVoiceChatParticipantIsMutedToggled { + chatEventVoiceChatParticipantIsMutedToggledTemp := ChatEventVoiceChatParticipantIsMutedToggled{ + tdCommon: tdCommon{Type: "chatEventVoiceChatParticipantIsMutedToggled"}, + ParticipantID: participantID, + IsMuted: isMuted, + } + + return &chatEventVoiceChatParticipantIsMutedToggledTemp +} + +// UnmarshalJSON unmarshal to json +func (chatEventVoiceChatParticipantIsMutedToggled *ChatEventVoiceChatParticipantIsMutedToggled) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + IsMuted bool `json:"is_muted"` // New value of is_muted + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatEventVoiceChatParticipantIsMutedToggled.tdCommon = tempObj.tdCommon + chatEventVoiceChatParticipantIsMutedToggled.IsMuted = tempObj.IsMuted + + fieldParticipantID, _ := unmarshalMessageSender(objMap["participant_id"]) + chatEventVoiceChatParticipantIsMutedToggled.ParticipantID = fieldParticipantID + + return nil +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventVoiceChatParticipantIsMutedToggled *ChatEventVoiceChatParticipantIsMutedToggled) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventVoiceChatParticipantIsMutedToggledType +} + +// ChatEventVoiceChatParticipantVolumeLevelChanged A voice chat participant volume level was changed +type ChatEventVoiceChatParticipantVolumeLevelChanged struct { + tdCommon + ParticipantID MessageSender `json:"participant_id"` // Identifier of the affected group call participant + VolumeLevel int32 `json:"volume_level"` // New value of volume_level; 1-20000 in hundreds of percents +} + +// MessageType return the string telegram-type of ChatEventVoiceChatParticipantVolumeLevelChanged +func (chatEventVoiceChatParticipantVolumeLevelChanged *ChatEventVoiceChatParticipantVolumeLevelChanged) MessageType() string { + return "chatEventVoiceChatParticipantVolumeLevelChanged" +} + +// NewChatEventVoiceChatParticipantVolumeLevelChanged creates a new ChatEventVoiceChatParticipantVolumeLevelChanged +// +// @param participantID Identifier of the affected group call participant +// @param volumeLevel New value of volume_level; 1-20000 in hundreds of percents +func NewChatEventVoiceChatParticipantVolumeLevelChanged(participantID MessageSender, volumeLevel int32) *ChatEventVoiceChatParticipantVolumeLevelChanged { + chatEventVoiceChatParticipantVolumeLevelChangedTemp := ChatEventVoiceChatParticipantVolumeLevelChanged{ + tdCommon: tdCommon{Type: "chatEventVoiceChatParticipantVolumeLevelChanged"}, + ParticipantID: participantID, + VolumeLevel: volumeLevel, + } + + return &chatEventVoiceChatParticipantVolumeLevelChangedTemp +} + +// UnmarshalJSON unmarshal to json +func (chatEventVoiceChatParticipantVolumeLevelChanged *ChatEventVoiceChatParticipantVolumeLevelChanged) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + VolumeLevel int32 `json:"volume_level"` // New value of volume_level; 1-20000 in hundreds of percents + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatEventVoiceChatParticipantVolumeLevelChanged.tdCommon = tempObj.tdCommon + chatEventVoiceChatParticipantVolumeLevelChanged.VolumeLevel = tempObj.VolumeLevel + + fieldParticipantID, _ := unmarshalMessageSender(objMap["participant_id"]) + chatEventVoiceChatParticipantVolumeLevelChanged.ParticipantID = fieldParticipantID + + return nil +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventVoiceChatParticipantVolumeLevelChanged *ChatEventVoiceChatParticipantVolumeLevelChanged) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventVoiceChatParticipantVolumeLevelChangedType +} + +// ChatEventVoiceChatMuteNewParticipantsToggled The mute_new_participants setting of a voice chat was toggled +type ChatEventVoiceChatMuteNewParticipantsToggled struct { + tdCommon + MuteNewParticipants bool `json:"mute_new_participants"` // New value of the mute_new_participants setting +} + +// MessageType return the string telegram-type of ChatEventVoiceChatMuteNewParticipantsToggled +func (chatEventVoiceChatMuteNewParticipantsToggled *ChatEventVoiceChatMuteNewParticipantsToggled) MessageType() string { + return "chatEventVoiceChatMuteNewParticipantsToggled" +} + +// NewChatEventVoiceChatMuteNewParticipantsToggled creates a new ChatEventVoiceChatMuteNewParticipantsToggled +// +// @param muteNewParticipants New value of the mute_new_participants setting +func NewChatEventVoiceChatMuteNewParticipantsToggled(muteNewParticipants bool) *ChatEventVoiceChatMuteNewParticipantsToggled { + chatEventVoiceChatMuteNewParticipantsToggledTemp := ChatEventVoiceChatMuteNewParticipantsToggled{ + tdCommon: tdCommon{Type: "chatEventVoiceChatMuteNewParticipantsToggled"}, + MuteNewParticipants: muteNewParticipants, + } + + return &chatEventVoiceChatMuteNewParticipantsToggledTemp +} + +// GetChatEventActionEnum return the enum type of this object +func (chatEventVoiceChatMuteNewParticipantsToggled *ChatEventVoiceChatMuteNewParticipantsToggled) GetChatEventActionEnum() ChatEventActionEnum { + return ChatEventVoiceChatMuteNewParticipantsToggledType +} diff --git a/tdlib/chatEventLogFilters.go b/tdlib/chatEventLogFilters.go new file mode 100644 index 0000000..9c14d46 --- /dev/null +++ b/tdlib/chatEventLogFilters.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + InviteLinkChanges bool `json:"invite_link_changes"` // True, if changes to invite links should be returned + VoiceChatChanges bool `json:"voice_chat_changes"` // True, if voice chat actions 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 +// @param inviteLinkChanges True, if changes to invite links should be returned +// @param voiceChatChanges True, if voice chat actions 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, inviteLinkChanges bool, voiceChatChanges 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, + InviteLinkChanges: inviteLinkChanges, + VoiceChatChanges: voiceChatChanges, + } + + return &chatEventLogFiltersTemp +} diff --git a/tdlib/chatEvents.go b/tdlib/chatEvents.go new file mode 100644 index 0000000..92a427d --- /dev/null +++ b/tdlib/chatEvents.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/chatFilter.go b/tdlib/chatFilter.go new file mode 100644 index 0000000..02cc63d --- /dev/null +++ b/tdlib/chatFilter.go @@ -0,0 +1,62 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatFilter Represents a filter of user chats +type ChatFilter struct { + tdCommon + Title string `json:"title"` // The title of the filter; 1-12 characters without line feeds + IconName string `json:"icon_name"` // The icon name for short filter representation. If non-empty, must be one of "All", "Unread", "Unmuted", "Bots", "Channels", "Groups", "Private", "Custom", "Setup", "Cat", "Crown", "Favorite", "Flower", "Game", "Home", "Love", "Mask", "Party", "Sport", "Study", "Trade", "Travel", "Work". If empty, use getChatFilterDefaultIconName to get default icon name for the filter + PinnedChatIDs []int64 `json:"pinned_chat_ids"` // The chat identifiers of pinned chats in the filtered chat list + IncludedChatIDs []int64 `json:"included_chat_ids"` // The chat identifiers of always included chats in the filtered chat list + ExcludedChatIDs []int64 `json:"excluded_chat_ids"` // The chat identifiers of always excluded chats in the filtered chat list + ExcludeMuted bool `json:"exclude_muted"` // True, if muted chats need to be excluded + ExcludeRead bool `json:"exclude_read"` // True, if read chats need to be excluded + ExcludeArchived bool `json:"exclude_archived"` // True, if archived chats need to be excluded + IncludeContacts bool `json:"include_contacts"` // True, if contacts need to be included + IncludeNonContacts bool `json:"include_non_contacts"` // True, if non-contact users need to be included + IncludeBots bool `json:"include_bots"` // True, if bots need to be included + IncludeGroups bool `json:"include_groups"` // True, if basic groups and supergroups need to be included + IncludeChannels bool `json:"include_channels"` // True, if channels need to be included +} + +// MessageType return the string telegram-type of ChatFilter +func (chatFilter *ChatFilter) MessageType() string { + return "chatFilter" +} + +// NewChatFilter creates a new ChatFilter +// +// @param title The title of the filter; 1-12 characters without line feeds +// @param iconName The icon name for short filter representation. If non-empty, must be one of "All", "Unread", "Unmuted", "Bots", "Channels", "Groups", "Private", "Custom", "Setup", "Cat", "Crown", "Favorite", "Flower", "Game", "Home", "Love", "Mask", "Party", "Sport", "Study", "Trade", "Travel", "Work". If empty, use getChatFilterDefaultIconName to get default icon name for the filter +// @param pinnedChatIDs The chat identifiers of pinned chats in the filtered chat list +// @param includedChatIDs The chat identifiers of always included chats in the filtered chat list +// @param excludedChatIDs The chat identifiers of always excluded chats in the filtered chat list +// @param excludeMuted True, if muted chats need to be excluded +// @param excludeRead True, if read chats need to be excluded +// @param excludeArchived True, if archived chats need to be excluded +// @param includeContacts True, if contacts need to be included +// @param includeNonContacts True, if non-contact users need to be included +// @param includeBots True, if bots need to be included +// @param includeGroups True, if basic groups and supergroups need to be included +// @param includeChannels True, if channels need to be included +func NewChatFilter(title string, iconName string, pinnedChatIDs []int64, includedChatIDs []int64, excludedChatIDs []int64, excludeMuted bool, excludeRead bool, excludeArchived bool, includeContacts bool, includeNonContacts bool, includeBots bool, includeGroups bool, includeChannels bool) *ChatFilter { + chatFilterTemp := ChatFilter{ + tdCommon: tdCommon{Type: "chatFilter"}, + Title: title, + IconName: iconName, + PinnedChatIDs: pinnedChatIDs, + IncludedChatIDs: includedChatIDs, + ExcludedChatIDs: excludedChatIDs, + ExcludeMuted: excludeMuted, + ExcludeRead: excludeRead, + ExcludeArchived: excludeArchived, + IncludeContacts: includeContacts, + IncludeNonContacts: includeNonContacts, + IncludeBots: includeBots, + IncludeGroups: includeGroups, + IncludeChannels: includeChannels, + } + + return &chatFilterTemp +} diff --git a/tdlib/chatFilterInfo.go b/tdlib/chatFilterInfo.go new file mode 100644 index 0000000..8b03468 --- /dev/null +++ b/tdlib/chatFilterInfo.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatFilterInfo Contains basic information about a chat filter +type ChatFilterInfo struct { + tdCommon + ID int32 `json:"id"` // Unique chat filter identifier + Title string `json:"title"` // The title of the filter; 1-12 characters without line feeds + IconName string `json:"icon_name"` // The icon name for short filter representation. One of "All", "Unread", "Unmuted", "Bots", "Channels", "Groups", "Private", "Custom", "Setup", "Cat", "Crown", "Favorite", "Flower", "Game", "Home", "Love", "Mask", "Party", "Sport", "Study", "Trade", "Travel", "Work" +} + +// MessageType return the string telegram-type of ChatFilterInfo +func (chatFilterInfo *ChatFilterInfo) MessageType() string { + return "chatFilterInfo" +} + +// NewChatFilterInfo creates a new ChatFilterInfo +// +// @param iD Unique chat filter identifier +// @param title The title of the filter; 1-12 characters without line feeds +// @param iconName The icon name for short filter representation. One of "All", "Unread", "Unmuted", "Bots", "Channels", "Groups", "Private", "Custom", "Setup", "Cat", "Crown", "Favorite", "Flower", "Game", "Home", "Love", "Mask", "Party", "Sport", "Study", "Trade", "Travel", "Work" +func NewChatFilterInfo(iD int32, title string, iconName string) *ChatFilterInfo { + chatFilterInfoTemp := ChatFilterInfo{ + tdCommon: tdCommon{Type: "chatFilterInfo"}, + ID: iD, + Title: title, + IconName: iconName, + } + + return &chatFilterInfoTemp +} diff --git a/tdlib/chatInviteLink.go b/tdlib/chatInviteLink.go new file mode 100644 index 0000000..a9cac17 --- /dev/null +++ b/tdlib/chatInviteLink.go @@ -0,0 +1,50 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatInviteLink Contains a chat invite link +type ChatInviteLink struct { + tdCommon + InviteLink string `json:"invite_link"` // Chat invite link + CreatorUserID int64 `json:"creator_user_id"` // User identifier of an administrator created the link + Date int32 `json:"date"` // Point in time (Unix timestamp) when the link was created + EditDate int32 `json:"edit_date"` // Point in time (Unix timestamp) when the link was last edited; 0 if never or unknown + ExpireDate int32 `json:"expire_date"` // Point in time (Unix timestamp) when the link will expire; 0 if never + MemberLimit int32 `json:"member_limit"` // The maximum number of members, which can join the chat using the link simultaneously; 0 if not limited + MemberCount int32 `json:"member_count"` // Number of chat members, which joined the chat using the link + IsPrimary bool `json:"is_primary"` // True, if the link is primary. Primary invite link can't have expire date or usage limit. There is exactly one primary invite link for each administrator with can_invite_users right at a given time + IsRevoked bool `json:"is_revoked"` // True, if the link was revoked +} + +// 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 +// @param creatorUserID User identifier of an administrator created the link +// @param date Point in time (Unix timestamp) when the link was created +// @param editDate Point in time (Unix timestamp) when the link was last edited; 0 if never or unknown +// @param expireDate Point in time (Unix timestamp) when the link will expire; 0 if never +// @param memberLimit The maximum number of members, which can join the chat using the link simultaneously; 0 if not limited +// @param memberCount Number of chat members, which joined the chat using the link +// @param isPrimary True, if the link is primary. Primary invite link can't have expire date or usage limit. There is exactly one primary invite link for each administrator with can_invite_users right at a given time +// @param isRevoked True, if the link was revoked +func NewChatInviteLink(inviteLink string, creatorUserID int64, date int32, editDate int32, expireDate int32, memberLimit int32, memberCount int32, isPrimary bool, isRevoked bool) *ChatInviteLink { + chatInviteLinkTemp := ChatInviteLink{ + tdCommon: tdCommon{Type: "chatInviteLink"}, + InviteLink: inviteLink, + CreatorUserID: creatorUserID, + Date: date, + EditDate: editDate, + ExpireDate: expireDate, + MemberLimit: memberLimit, + MemberCount: memberCount, + IsPrimary: isPrimary, + IsRevoked: isRevoked, + } + + return &chatInviteLinkTemp +} diff --git a/tdlib/chatInviteLinkCount.go b/tdlib/chatInviteLinkCount.go new file mode 100644 index 0000000..4d7307d --- /dev/null +++ b/tdlib/chatInviteLinkCount.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatInviteLinkCount Describes a chat administrator with a number of active and revoked chat invite links +type ChatInviteLinkCount struct { + tdCommon + UserID int64 `json:"user_id"` // Administrator's user identifier + InviteLinkCount int32 `json:"invite_link_count"` // Number of active invite links + RevokedInviteLinkCount int32 `json:"revoked_invite_link_count"` // Number of revoked invite links +} + +// MessageType return the string telegram-type of ChatInviteLinkCount +func (chatInviteLinkCount *ChatInviteLinkCount) MessageType() string { + return "chatInviteLinkCount" +} + +// NewChatInviteLinkCount creates a new ChatInviteLinkCount +// +// @param userID Administrator's user identifier +// @param inviteLinkCount Number of active invite links +// @param revokedInviteLinkCount Number of revoked invite links +func NewChatInviteLinkCount(userID int64, inviteLinkCount int32, revokedInviteLinkCount int32) *ChatInviteLinkCount { + chatInviteLinkCountTemp := ChatInviteLinkCount{ + tdCommon: tdCommon{Type: "chatInviteLinkCount"}, + UserID: userID, + InviteLinkCount: inviteLinkCount, + RevokedInviteLinkCount: revokedInviteLinkCount, + } + + return &chatInviteLinkCountTemp +} diff --git a/tdlib/chatInviteLinkCounts.go b/tdlib/chatInviteLinkCounts.go new file mode 100644 index 0000000..7f6a8f2 --- /dev/null +++ b/tdlib/chatInviteLinkCounts.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatInviteLinkCounts Contains a list of chat invite link counts +type ChatInviteLinkCounts struct { + tdCommon + InviteLinkCounts []ChatInviteLinkCount `json:"invite_link_counts"` // List of invite linkcounts +} + +// MessageType return the string telegram-type of ChatInviteLinkCounts +func (chatInviteLinkCounts *ChatInviteLinkCounts) MessageType() string { + return "chatInviteLinkCounts" +} + +// NewChatInviteLinkCounts creates a new ChatInviteLinkCounts +// +// @param inviteLinkCounts List of invite linkcounts +func NewChatInviteLinkCounts(inviteLinkCounts []ChatInviteLinkCount) *ChatInviteLinkCounts { + chatInviteLinkCountsTemp := ChatInviteLinkCounts{ + tdCommon: tdCommon{Type: "chatInviteLinkCounts"}, + InviteLinkCounts: inviteLinkCounts, + } + + return &chatInviteLinkCountsTemp +} diff --git a/tdlib/chatInviteLinkInfo.go b/tdlib/chatInviteLinkInfo.go new file mode 100644 index 0000000..276421e --- /dev/null +++ b/tdlib/chatInviteLinkInfo.go @@ -0,0 +1,88 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 has no access to the chat before joining + AccessibleFor int32 `json:"accessible_for"` // If non-zero, the amount of time for which read access to the chat will remain available, in seconds + Type ChatType `json:"type"` // Contains information about the type of the chat + Title string `json:"title"` // Title of the chat + Photo *ChatPhotoInfo `json:"photo"` // Chat photo; may be null + MemberCount int32 `json:"member_count"` // Number of members in the chat + MemberUserIDs []int64 `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, i.e. it has a username or it is a location-based supergroup +} + +// 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 has no access to the chat before joining +// @param accessibleFor If non-zero, the amount of time for which read access to the chat will remain available, in seconds +// @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 in the chat +// @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, i.e. it has a username or it is a location-based supergroup +func NewChatInviteLinkInfo(chatID int64, accessibleFor int32, typeParam ChatType, title string, photo *ChatPhotoInfo, memberCount int32, memberUserIDs []int64, isPublic bool) *ChatInviteLinkInfo { + chatInviteLinkInfoTemp := ChatInviteLinkInfo{ + tdCommon: tdCommon{Type: "chatInviteLinkInfo"}, + ChatID: chatID, + AccessibleFor: accessibleFor, + 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 has no access to the chat before joining + AccessibleFor int32 `json:"accessible_for"` // If non-zero, the amount of time for which read access to the chat will remain available, in seconds + Title string `json:"title"` // Title of the chat + Photo *ChatPhotoInfo `json:"photo"` // Chat photo; may be null + MemberCount int32 `json:"member_count"` // Number of members in the chat + MemberUserIDs []int64 `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, i.e. it has a username or it is a location-based supergroup + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatInviteLinkInfo.tdCommon = tempObj.tdCommon + chatInviteLinkInfo.ChatID = tempObj.ChatID + chatInviteLinkInfo.AccessibleFor = tempObj.AccessibleFor + 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 +} diff --git a/tdlib/chatInviteLinkMember.go b/tdlib/chatInviteLinkMember.go new file mode 100644 index 0000000..7d6c930 --- /dev/null +++ b/tdlib/chatInviteLinkMember.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatInviteLinkMember Describes a chat member joined a chat by an invite link +type ChatInviteLinkMember struct { + tdCommon + UserID int64 `json:"user_id"` // User identifier + JoinedChatDate int32 `json:"joined_chat_date"` // Point in time (Unix timestamp) when the user joined the chat +} + +// MessageType return the string telegram-type of ChatInviteLinkMember +func (chatInviteLinkMember *ChatInviteLinkMember) MessageType() string { + return "chatInviteLinkMember" +} + +// NewChatInviteLinkMember creates a new ChatInviteLinkMember +// +// @param userID User identifier +// @param joinedChatDate Point in time (Unix timestamp) when the user joined the chat +func NewChatInviteLinkMember(userID int64, joinedChatDate int32) *ChatInviteLinkMember { + chatInviteLinkMemberTemp := ChatInviteLinkMember{ + tdCommon: tdCommon{Type: "chatInviteLinkMember"}, + UserID: userID, + JoinedChatDate: joinedChatDate, + } + + return &chatInviteLinkMemberTemp +} diff --git a/tdlib/chatInviteLinkMembers.go b/tdlib/chatInviteLinkMembers.go new file mode 100644 index 0000000..9326e0c --- /dev/null +++ b/tdlib/chatInviteLinkMembers.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatInviteLinkMembers Contains a list of chat members joined a chat by an invite link +type ChatInviteLinkMembers struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of chat members found + Members []ChatInviteLinkMember `json:"members"` // List of chat members, joined a chat by an invite link +} + +// MessageType return the string telegram-type of ChatInviteLinkMembers +func (chatInviteLinkMembers *ChatInviteLinkMembers) MessageType() string { + return "chatInviteLinkMembers" +} + +// NewChatInviteLinkMembers creates a new ChatInviteLinkMembers +// +// @param totalCount Approximate total count of chat members found +// @param members List of chat members, joined a chat by an invite link +func NewChatInviteLinkMembers(totalCount int32, members []ChatInviteLinkMember) *ChatInviteLinkMembers { + chatInviteLinkMembersTemp := ChatInviteLinkMembers{ + tdCommon: tdCommon{Type: "chatInviteLinkMembers"}, + TotalCount: totalCount, + Members: members, + } + + return &chatInviteLinkMembersTemp +} diff --git a/tdlib/chatInviteLinks.go b/tdlib/chatInviteLinks.go new file mode 100644 index 0000000..c092d0c --- /dev/null +++ b/tdlib/chatInviteLinks.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatInviteLinks Contains a list of chat invite links +type ChatInviteLinks struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of chat invite links found + InviteLinks []ChatInviteLink `json:"invite_links"` // List of invite links +} + +// MessageType return the string telegram-type of ChatInviteLinks +func (chatInviteLinks *ChatInviteLinks) MessageType() string { + return "chatInviteLinks" +} + +// NewChatInviteLinks creates a new ChatInviteLinks +// +// @param totalCount Approximate total count of chat invite links found +// @param inviteLinks List of invite links +func NewChatInviteLinks(totalCount int32, inviteLinks []ChatInviteLink) *ChatInviteLinks { + chatInviteLinksTemp := ChatInviteLinks{ + tdCommon: tdCommon{Type: "chatInviteLinks"}, + TotalCount: totalCount, + InviteLinks: inviteLinks, + } + + return &chatInviteLinksTemp +} diff --git a/tdlib/chatList.go b/tdlib/chatList.go new file mode 100644 index 0000000..9f912a1 --- /dev/null +++ b/tdlib/chatList.go @@ -0,0 +1,133 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatList Describes a list of chats +type ChatList interface { + GetChatListEnum() ChatListEnum +} + +// ChatListEnum Alias for abstract ChatList 'Sub-Classes', used as constant-enum here +type ChatListEnum string + +// ChatList enums +const ( + ChatListMainType ChatListEnum = "chatListMain" + ChatListArchiveType ChatListEnum = "chatListArchive" + ChatListFilterType ChatListEnum = "chatListFilter" +) + +func unmarshalChatList(rawMsg *json.RawMessage) (ChatList, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatListEnum(objMap["@type"].(string)) { + case ChatListMainType: + var chatListMain ChatListMain + err := json.Unmarshal(*rawMsg, &chatListMain) + return &chatListMain, err + + case ChatListArchiveType: + var chatListArchive ChatListArchive + err := json.Unmarshal(*rawMsg, &chatListArchive) + return &chatListArchive, err + + case ChatListFilterType: + var chatListFilter ChatListFilter + err := json.Unmarshal(*rawMsg, &chatListFilter) + return &chatListFilter, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// ChatListMain A main list of chats +type ChatListMain struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatListMain +func (chatListMain *ChatListMain) MessageType() string { + return "chatListMain" +} + +// NewChatListMain creates a new ChatListMain +// +func NewChatListMain() *ChatListMain { + chatListMainTemp := ChatListMain{ + tdCommon: tdCommon{Type: "chatListMain"}, + } + + return &chatListMainTemp +} + +// GetChatListEnum return the enum type of this object +func (chatListMain *ChatListMain) GetChatListEnum() ChatListEnum { + return ChatListMainType +} + +// ChatListArchive A list of chats usually located at the top of the main chat list. Unmuted chats are automatically moved from the Archive to the Main chat list when a new message arrives +type ChatListArchive struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatListArchive +func (chatListArchive *ChatListArchive) MessageType() string { + return "chatListArchive" +} + +// NewChatListArchive creates a new ChatListArchive +// +func NewChatListArchive() *ChatListArchive { + chatListArchiveTemp := ChatListArchive{ + tdCommon: tdCommon{Type: "chatListArchive"}, + } + + return &chatListArchiveTemp +} + +// GetChatListEnum return the enum type of this object +func (chatListArchive *ChatListArchive) GetChatListEnum() ChatListEnum { + return ChatListArchiveType +} + +// ChatListFilter A list of chats belonging to a chat filter +type ChatListFilter struct { + tdCommon + ChatFilterID int32 `json:"chat_filter_id"` // Chat filter identifier +} + +// MessageType return the string telegram-type of ChatListFilter +func (chatListFilter *ChatListFilter) MessageType() string { + return "chatListFilter" +} + +// NewChatListFilter creates a new ChatListFilter +// +// @param chatFilterID Chat filter identifier +func NewChatListFilter(chatFilterID int32) *ChatListFilter { + chatListFilterTemp := ChatListFilter{ + tdCommon: tdCommon{Type: "chatListFilter"}, + ChatFilterID: chatFilterID, + } + + return &chatListFilterTemp +} + +// GetChatListEnum return the enum type of this object +func (chatListFilter *ChatListFilter) GetChatListEnum() ChatListEnum { + return ChatListFilterType +} diff --git a/tdlib/chatLists.go b/tdlib/chatLists.go new file mode 100644 index 0000000..94bd1bb --- /dev/null +++ b/tdlib/chatLists.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatLists Contains a list of chat lists +type ChatLists struct { + tdCommon + ChatLists []ChatList `json:"chat_lists"` // List of chat lists +} + +// MessageType return the string telegram-type of ChatLists +func (chatLists *ChatLists) MessageType() string { + return "chatLists" +} + +// NewChatLists creates a new ChatLists +// +// @param chatLists List of chat lists +func NewChatLists(chatLists []ChatList) *ChatLists { + chatListsTemp := ChatLists{ + tdCommon: tdCommon{Type: "chatLists"}, + ChatLists: chatLists, + } + + return &chatListsTemp +} diff --git a/tdlib/chatLocation.go b/tdlib/chatLocation.go new file mode 100644 index 0000000..2bea9c1 --- /dev/null +++ b/tdlib/chatLocation.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatLocation Represents a location to which a chat is connected +type ChatLocation struct { + tdCommon + Location *Location `json:"location"` // The location + Address string `json:"address"` // Location address; 1-64 characters, as defined by the chat owner +} + +// MessageType return the string telegram-type of ChatLocation +func (chatLocation *ChatLocation) MessageType() string { + return "chatLocation" +} + +// NewChatLocation creates a new ChatLocation +// +// @param location The location +// @param address Location address; 1-64 characters, as defined by the chat owner +func NewChatLocation(location *Location, address string) *ChatLocation { + chatLocationTemp := ChatLocation{ + tdCommon: tdCommon{Type: "chatLocation"}, + Location: location, + Address: address, + } + + return &chatLocationTemp +} diff --git a/tdlib/chatMember.go b/tdlib/chatMember.go new file mode 100644 index 0000000..d364d6b --- /dev/null +++ b/tdlib/chatMember.go @@ -0,0 +1,70 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// ChatMember Information about a user or a chat as a member of another chat +type ChatMember struct { + tdCommon + MemberID MessageSender `json:"member_id"` // Identifier of the chat member. Currently, other chats can be only Left or Banned. Only supergroups and channels can have other chats as Left or Banned members and these chats must be supergroups or channels + InviterUserID int64 `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 the chat + Status ChatMemberStatus `json:"status"` // Status of the member in the chat +} + +// MessageType return the string telegram-type of ChatMember +func (chatMember *ChatMember) MessageType() string { + return "chatMember" +} + +// NewChatMember creates a new ChatMember +// +// @param memberID Identifier of the chat member. Currently, other chats can be only Left or Banned. Only supergroups and channels can have other chats as Left or Banned members and these chats must be supergroups or channels +// @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 the chat +// @param status Status of the member in the chat +func NewChatMember(memberID MessageSender, inviterUserID int64, joinedChatDate int32, status ChatMemberStatus) *ChatMember { + chatMemberTemp := ChatMember{ + tdCommon: tdCommon{Type: "chatMember"}, + MemberID: memberID, + InviterUserID: inviterUserID, + JoinedChatDate: joinedChatDate, + Status: status, + } + + 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 + InviterUserID int64 `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 the chat + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatMember.tdCommon = tempObj.tdCommon + chatMember.InviterUserID = tempObj.InviterUserID + chatMember.JoinedChatDate = tempObj.JoinedChatDate + + fieldMemberID, _ := unmarshalMessageSender(objMap["member_id"]) + chatMember.MemberID = fieldMemberID + + fieldStatus, _ := unmarshalChatMemberStatus(objMap["status"]) + chatMember.Status = fieldStatus + + return nil +} diff --git a/tdlib/chatMemberStatus.go b/tdlib/chatMemberStatus.go new file mode 100644 index 0000000..51db79a --- /dev/null +++ b/tdlib/chatMemberStatus.go @@ -0,0 +1,283 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatMemberStatus Provides information about the status of a member in a chat +type ChatMemberStatus interface { + GetChatMemberStatusEnum() ChatMemberStatusEnum +} + +// 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" +) + +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)) + } +} + +// ChatMemberStatusCreator The user is the owner of the chat and has all the administrator privileges +type ChatMemberStatusCreator struct { + tdCommon + CustomTitle string `json:"custom_title"` // A custom title of the owner; 0-16 characters without emojis; applicable to supergroups only + IsAnonymous bool `json:"is_anonymous"` // True, if the creator isn't shown in the chat member list and sends messages anonymously; applicable to supergroups only + 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 customTitle A custom title of the owner; 0-16 characters without emojis; applicable to supergroups only +// @param isAnonymous True, if the creator isn't shown in the chat member list and sends messages anonymously; applicable to supergroups only +// @param isMember True, if the user is a member of the chat +func NewChatMemberStatusCreator(customTitle string, isAnonymous bool, isMember bool) *ChatMemberStatusCreator { + chatMemberStatusCreatorTemp := ChatMemberStatusCreator{ + tdCommon: tdCommon{Type: "chatMemberStatusCreator"}, + CustomTitle: customTitle, + IsAnonymous: isAnonymous, + 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 the chat and has some additional privileges. In basic groups, administrators can edit and delete messages sent by others, add new members, ban unprivileged members, and manage voice chats. In supergroups and channels, there are more detailed options for administrator privileges +type ChatMemberStatusAdministrator struct { + tdCommon + CustomTitle string `json:"custom_title"` // A custom title of the administrator; 0-16 characters without emojis; applicable to supergroups only + CanBeEdited bool `json:"can_be_edited"` // True, if the current user can edit the administrator privileges for the called user + CanManageChat bool `json:"can_manage_chat"` // True, if the administrator can get chat event log, get chat statistics, get message statistics in channels, get channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other privilege; applicable to supergroups and channels only + 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; always true for channels + CanPinMessages bool `json:"can_pin_messages"` // True, if the administrator can pin messages; applicable to basic groups and supergroups only + CanPromoteMembers bool `json:"can_promote_members"` // True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that were directly or indirectly promoted by them + CanManageVoiceChats bool `json:"can_manage_voice_chats"` // True, if the administrator can manage voice chats + IsAnonymous bool `json:"is_anonymous"` // True, if the administrator isn't shown in the chat member list and sends messages anonymously; applicable to supergroups only +} + +// MessageType return the string telegram-type of ChatMemberStatusAdministrator +func (chatMemberStatusAdministrator *ChatMemberStatusAdministrator) MessageType() string { + return "chatMemberStatusAdministrator" +} + +// NewChatMemberStatusAdministrator creates a new ChatMemberStatusAdministrator +// +// @param customTitle A custom title of the administrator; 0-16 characters without emojis; applicable to supergroups only +// @param canBeEdited True, if the current user can edit the administrator privileges for the called user +// @param canManageChat True, if the administrator can get chat event log, get chat statistics, get message statistics in channels, get channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other privilege; applicable to supergroups and channels only +// @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; always true for channels +// @param canPinMessages True, if the administrator can pin messages; applicable to basic groups and supergroups only +// @param canPromoteMembers True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that were directly or indirectly promoted by them +// @param canManageVoiceChats True, if the administrator can manage voice chats +// @param isAnonymous True, if the administrator isn't shown in the chat member list and sends messages anonymously; applicable to supergroups only +func NewChatMemberStatusAdministrator(customTitle string, canBeEdited bool, canManageChat bool, canChangeInfo bool, canPostMessages bool, canEditMessages bool, canDeleteMessages bool, canInviteUsers bool, canRestrictMembers bool, canPinMessages bool, canPromoteMembers bool, canManageVoiceChats bool, isAnonymous bool) *ChatMemberStatusAdministrator { + chatMemberStatusAdministratorTemp := ChatMemberStatusAdministrator{ + tdCommon: tdCommon{Type: "chatMemberStatusAdministrator"}, + CustomTitle: customTitle, + CanBeEdited: canBeEdited, + CanManageChat: canManageChat, + CanChangeInfo: canChangeInfo, + CanPostMessages: canPostMessages, + CanEditMessages: canEditMessages, + CanDeleteMessages: canDeleteMessages, + CanInviteUsers: canInviteUsers, + CanRestrictMembers: canRestrictMembers, + CanPinMessages: canPinMessages, + CanPromoteMembers: canPromoteMembers, + CanManageVoiceChats: canManageVoiceChats, + IsAnonymous: isAnonymous, + } + + return &chatMemberStatusAdministratorTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusAdministrator *ChatMemberStatusAdministrator) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusAdministratorType +} + +// ChatMemberStatusMember The user is a member of the 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 + Permissions *ChatPermissions `json:"permissions"` // User permissions in the chat +} + +// 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 permissions User permissions in the chat +func NewChatMemberStatusRestricted(isMember bool, restrictedUntilDate int32, permissions *ChatPermissions) *ChatMemberStatusRestricted { + chatMemberStatusRestrictedTemp := ChatMemberStatusRestricted{ + tdCommon: tdCommon{Type: "chatMemberStatusRestricted"}, + IsMember: isMember, + RestrictedUntilDate: restrictedUntilDate, + Permissions: permissions, + } + + return &chatMemberStatusRestrictedTemp +} + +// GetChatMemberStatusEnum return the enum type of this object +func (chatMemberStatusRestricted *ChatMemberStatusRestricted) GetChatMemberStatusEnum() ChatMemberStatusEnum { + return ChatMemberStatusRestrictedType +} + +// ChatMemberStatusLeft The user or the chat 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 or the chat was banned (and hence is not a member of the chat). Implies the user can't return to the chat, view messages, or be used as a participant identifier to join a voice chat of the chat +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. Always 0 in basic groups +} + +// 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. Always 0 in basic groups +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 +} diff --git a/tdlib/chatMembers.go b/tdlib/chatMembers.go new file mode 100644 index 0000000..d3bd2cf --- /dev/null +++ b/tdlib/chatMembers.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/chatMembersFilter.go b/tdlib/chatMembersFilter.go new file mode 100644 index 0000000..6f212d2 --- /dev/null +++ b/tdlib/chatMembersFilter.go @@ -0,0 +1,257 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatMembersFilter Specifies the kind of chat members to return in searchChatMembers +type ChatMembersFilter interface { + GetChatMembersFilterEnum() ChatMembersFilterEnum +} + +// ChatMembersFilterEnum Alias for abstract ChatMembersFilter 'Sub-Classes', used as constant-enum here +type ChatMembersFilterEnum string + +// ChatMembersFilter enums +const ( + ChatMembersFilterContactsType ChatMembersFilterEnum = "chatMembersFilterContacts" + ChatMembersFilterAdministratorsType ChatMembersFilterEnum = "chatMembersFilterAdministrators" + ChatMembersFilterMembersType ChatMembersFilterEnum = "chatMembersFilterMembers" + ChatMembersFilterMentionType ChatMembersFilterEnum = "chatMembersFilterMention" + ChatMembersFilterRestrictedType ChatMembersFilterEnum = "chatMembersFilterRestricted" + ChatMembersFilterBannedType ChatMembersFilterEnum = "chatMembersFilterBanned" + ChatMembersFilterBotsType ChatMembersFilterEnum = "chatMembersFilterBots" +) + +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 ChatMembersFilterContactsType: + var chatMembersFilterContacts ChatMembersFilterContacts + err := json.Unmarshal(*rawMsg, &chatMembersFilterContacts) + return &chatMembersFilterContacts, err + + 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 ChatMembersFilterMentionType: + var chatMembersFilterMention ChatMembersFilterMention + err := json.Unmarshal(*rawMsg, &chatMembersFilterMention) + return &chatMembersFilterMention, 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)) + } +} + +// ChatMembersFilterContacts Returns contacts of the user +type ChatMembersFilterContacts struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatMembersFilterContacts +func (chatMembersFilterContacts *ChatMembersFilterContacts) MessageType() string { + return "chatMembersFilterContacts" +} + +// NewChatMembersFilterContacts creates a new ChatMembersFilterContacts +// +func NewChatMembersFilterContacts() *ChatMembersFilterContacts { + chatMembersFilterContactsTemp := ChatMembersFilterContacts{ + tdCommon: tdCommon{Type: "chatMembersFilterContacts"}, + } + + return &chatMembersFilterContactsTemp +} + +// GetChatMembersFilterEnum return the enum type of this object +func (chatMembersFilterContacts *ChatMembersFilterContacts) GetChatMembersFilterEnum() ChatMembersFilterEnum { + return ChatMembersFilterContactsType +} + +// ChatMembersFilterAdministrators Returns the owner 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 +} + +// ChatMembersFilterMention Returns users which can be mentioned in the chat +type ChatMembersFilterMention struct { + tdCommon + MessageThreadID int64 `json:"message_thread_id"` // If non-zero, the identifier of the current message thread +} + +// MessageType return the string telegram-type of ChatMembersFilterMention +func (chatMembersFilterMention *ChatMembersFilterMention) MessageType() string { + return "chatMembersFilterMention" +} + +// NewChatMembersFilterMention creates a new ChatMembersFilterMention +// +// @param messageThreadID If non-zero, the identifier of the current message thread +func NewChatMembersFilterMention(messageThreadID int64) *ChatMembersFilterMention { + chatMembersFilterMentionTemp := ChatMembersFilterMention{ + tdCommon: tdCommon{Type: "chatMembersFilterMention"}, + MessageThreadID: messageThreadID, + } + + return &chatMembersFilterMentionTemp +} + +// GetChatMembersFilterEnum return the enum type of this object +func (chatMembersFilterMention *ChatMembersFilterMention) GetChatMembersFilterEnum() ChatMembersFilterEnum { + return ChatMembersFilterMentionType +} + +// 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 +} diff --git a/tdlib/chatNearby.go b/tdlib/chatNearby.go new file mode 100644 index 0000000..e251a9c --- /dev/null +++ b/tdlib/chatNearby.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatNearby Describes a chat located nearby +type ChatNearby struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + Distance int32 `json:"distance"` // Distance to the chat location, in meters +} + +// MessageType return the string telegram-type of ChatNearby +func (chatNearby *ChatNearby) MessageType() string { + return "chatNearby" +} + +// NewChatNearby creates a new ChatNearby +// +// @param chatID Chat identifier +// @param distance Distance to the chat location, in meters +func NewChatNearby(chatID int64, distance int32) *ChatNearby { + chatNearbyTemp := ChatNearby{ + tdCommon: tdCommon{Type: "chatNearby"}, + ChatID: chatID, + Distance: distance, + } + + return &chatNearbyTemp +} diff --git a/tdlib/chatNotificationSettings.go b/tdlib/chatNotificationSettings.go new file mode 100644 index 0000000..671f3f3 --- /dev/null +++ b/tdlib/chatNotificationSettings.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + UseDefaultDisablePinnedMessageNotifications bool `json:"use_default_disable_pinned_message_notifications"` // If true, disable_pinned_message_notifications is ignored and the value for the relevant type of chat is used instead + DisablePinnedMessageNotifications bool `json:"disable_pinned_message_notifications"` // If true, notifications for incoming pinned messages will be created as for an ordinary unread message + UseDefaultDisableMentionNotifications bool `json:"use_default_disable_mention_notifications"` // If true, disable_mention_notifications is ignored and the value for the relevant type of chat is used instead + DisableMentionNotifications bool `json:"disable_mention_notifications"` // If true, notifications for messages with mentions will be created as for an ordinary unread message +} + +// 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 +// @param useDefaultDisablePinnedMessageNotifications If true, disable_pinned_message_notifications is ignored and the value for the relevant type of chat is used instead +// @param disablePinnedMessageNotifications If true, notifications for incoming pinned messages will be created as for an ordinary unread message +// @param useDefaultDisableMentionNotifications If true, disable_mention_notifications is ignored and the value for the relevant type of chat is used instead +// @param disableMentionNotifications If true, notifications for messages with mentions will be created as for an ordinary unread message +func NewChatNotificationSettings(useDefaultMuteFor bool, muteFor int32, useDefaultSound bool, sound string, useDefaultShowPreview bool, showPreview bool, useDefaultDisablePinnedMessageNotifications bool, disablePinnedMessageNotifications bool, useDefaultDisableMentionNotifications bool, disableMentionNotifications bool) *ChatNotificationSettings { + chatNotificationSettingsTemp := ChatNotificationSettings{ + tdCommon: tdCommon{Type: "chatNotificationSettings"}, + UseDefaultMuteFor: useDefaultMuteFor, + MuteFor: muteFor, + UseDefaultSound: useDefaultSound, + Sound: sound, + UseDefaultShowPreview: useDefaultShowPreview, + ShowPreview: showPreview, + UseDefaultDisablePinnedMessageNotifications: useDefaultDisablePinnedMessageNotifications, + DisablePinnedMessageNotifications: disablePinnedMessageNotifications, + UseDefaultDisableMentionNotifications: useDefaultDisableMentionNotifications, + DisableMentionNotifications: disableMentionNotifications, + } + + return &chatNotificationSettingsTemp +} diff --git a/tdlib/chatPermissions.go b/tdlib/chatPermissions.go new file mode 100644 index 0000000..6024855 --- /dev/null +++ b/tdlib/chatPermissions.go @@ -0,0 +1,47 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatPermissions Describes actions that a user is allowed to take in a chat +type ChatPermissions struct { + tdCommon + 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 + CanSendPolls bool `json:"can_send_polls"` // True, if the user can send polls. Implies can_send_messages permissions + CanSendOtherMessages bool `json:"can_send_other_messages"` // True, if the user can send animations, games, stickers, and dice and use inline bots. Implies can_send_messages permissions + CanAddWebPagePreviews bool `json:"can_add_web_page_previews"` // True, if the user may add a web page preview to their messages. Implies can_send_messages permissions + CanChangeInfo bool `json:"can_change_info"` // True, if the user can change the chat title, photo, and other settings + CanInviteUsers bool `json:"can_invite_users"` // True, if the user can invite new users to the chat + CanPinMessages bool `json:"can_pin_messages"` // True, if the user can pin messages +} + +// MessageType return the string telegram-type of ChatPermissions +func (chatPermissions *ChatPermissions) MessageType() string { + return "chatPermissions" +} + +// NewChatPermissions creates a new ChatPermissions +// +// @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 canSendPolls True, if the user can send polls. Implies can_send_messages permissions +// @param canSendOtherMessages True, if the user can send animations, games, stickers, and dice and use inline bots. Implies can_send_messages permissions +// @param canAddWebPagePreviews True, if the user may add a web page preview to their messages. Implies can_send_messages permissions +// @param canChangeInfo True, if the user can change the chat title, photo, and other settings +// @param canInviteUsers True, if the user can invite new users to the chat +// @param canPinMessages True, if the user can pin messages +func NewChatPermissions(canSendMessages bool, canSendMediaMessages bool, canSendPolls bool, canSendOtherMessages bool, canAddWebPagePreviews bool, canChangeInfo bool, canInviteUsers bool, canPinMessages bool) *ChatPermissions { + chatPermissionsTemp := ChatPermissions{ + tdCommon: tdCommon{Type: "chatPermissions"}, + CanSendMessages: canSendMessages, + CanSendMediaMessages: canSendMediaMessages, + CanSendPolls: canSendPolls, + CanSendOtherMessages: canSendOtherMessages, + CanAddWebPagePreviews: canAddWebPagePreviews, + CanChangeInfo: canChangeInfo, + CanInviteUsers: canInviteUsers, + CanPinMessages: canPinMessages, + } + + return &chatPermissionsTemp +} diff --git a/tdlib/chatPhoto.go b/tdlib/chatPhoto.go new file mode 100644 index 0000000..78a46ef --- /dev/null +++ b/tdlib/chatPhoto.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatPhoto Describes a chat or user profile photo +type ChatPhoto struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique photo identifier + AddedDate int32 `json:"added_date"` // Point in time (Unix timestamp) when the photo has been added + Minithumbnail *Minithumbnail `json:"minithumbnail"` // Photo minithumbnail; may be null + Sizes []PhotoSize `json:"sizes"` // Available variants of the photo in JPEG format, in different size + Animation *AnimatedChatPhoto `json:"animation"` // Animated variant of the photo in MPEG4 format; may be null +} + +// MessageType return the string telegram-type of ChatPhoto +func (chatPhoto *ChatPhoto) MessageType() string { + return "chatPhoto" +} + +// NewChatPhoto creates a new ChatPhoto +// +// @param iD Unique photo identifier +// @param addedDate Point in time (Unix timestamp) when the photo has been added +// @param minithumbnail Photo minithumbnail; may be null +// @param sizes Available variants of the photo in JPEG format, in different size +// @param animation Animated variant of the photo in MPEG4 format; may be null +func NewChatPhoto(iD JSONInt64, addedDate int32, minithumbnail *Minithumbnail, sizes []PhotoSize, animation *AnimatedChatPhoto) *ChatPhoto { + chatPhotoTemp := ChatPhoto{ + tdCommon: tdCommon{Type: "chatPhoto"}, + ID: iD, + AddedDate: addedDate, + Minithumbnail: minithumbnail, + Sizes: sizes, + Animation: animation, + } + + return &chatPhotoTemp +} diff --git a/tdlib/chatPhotoInfo.go b/tdlib/chatPhotoInfo.go new file mode 100644 index 0000000..d6bc5e9 --- /dev/null +++ b/tdlib/chatPhotoInfo.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatPhotoInfo Contains basic information about the photo of a chat +type ChatPhotoInfo struct { + tdCommon + Small *File `json:"small"` // A small (160x160) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed + Big *File `json:"big"` // A big (640x640) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed + Minithumbnail *Minithumbnail `json:"minithumbnail"` // Chat photo minithumbnail; may be null + HasAnimation bool `json:"has_animation"` // True, if the photo has animated variant +} + +// MessageType return the string telegram-type of ChatPhotoInfo +func (chatPhotoInfo *ChatPhotoInfo) MessageType() string { + return "chatPhotoInfo" +} + +// NewChatPhotoInfo creates a new ChatPhotoInfo +// +// @param small A small (160x160) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed +// @param big A big (640x640) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed +// @param minithumbnail Chat photo minithumbnail; may be null +// @param hasAnimation True, if the photo has animated variant +func NewChatPhotoInfo(small *File, big *File, minithumbnail *Minithumbnail, hasAnimation bool) *ChatPhotoInfo { + chatPhotoInfoTemp := ChatPhotoInfo{ + tdCommon: tdCommon{Type: "chatPhotoInfo"}, + Small: small, + Big: big, + Minithumbnail: minithumbnail, + HasAnimation: hasAnimation, + } + + return &chatPhotoInfoTemp +} diff --git a/tdlib/chatPhotos.go b/tdlib/chatPhotos.go new file mode 100644 index 0000000..675fc4e --- /dev/null +++ b/tdlib/chatPhotos.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatPhotos Contains a list of chat or user profile photos +type ChatPhotos struct { + tdCommon + TotalCount int32 `json:"total_count"` // Total number of photos + Photos []ChatPhoto `json:"photos"` // List of photos +} + +// MessageType return the string telegram-type of ChatPhotos +func (chatPhotos *ChatPhotos) MessageType() string { + return "chatPhotos" +} + +// NewChatPhotos creates a new ChatPhotos +// +// @param totalCount Total number of photos +// @param photos List of photos +func NewChatPhotos(totalCount int32, photos []ChatPhoto) *ChatPhotos { + chatPhotosTemp := ChatPhotos{ + tdCommon: tdCommon{Type: "chatPhotos"}, + TotalCount: totalCount, + Photos: photos, + } + + return &chatPhotosTemp +} diff --git a/tdlib/chatPosition.go b/tdlib/chatPosition.go new file mode 100644 index 0000000..37fe98a --- /dev/null +++ b/tdlib/chatPosition.go @@ -0,0 +1,70 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// ChatPosition Describes a position of a chat in a chat list +type ChatPosition struct { + tdCommon + List ChatList `json:"list"` // The chat list + Order JSONInt64 `json:"order"` // A parameter used to determine order of the chat in the chat list. Chats must be sorted by the pair (order, chat.id) in descending order + IsPinned bool `json:"is_pinned"` // True, if the chat is pinned in the chat list + Source ChatSource `json:"source"` // Source of the chat in the chat list; may be null +} + +// MessageType return the string telegram-type of ChatPosition +func (chatPosition *ChatPosition) MessageType() string { + return "chatPosition" +} + +// NewChatPosition creates a new ChatPosition +// +// @param list The chat list +// @param order A parameter used to determine order of the chat in the chat list. Chats must be sorted by the pair (order, chat.id) in descending order +// @param isPinned True, if the chat is pinned in the chat list +// @param source Source of the chat in the chat list; may be null +func NewChatPosition(list ChatList, order JSONInt64, isPinned bool, source ChatSource) *ChatPosition { + chatPositionTemp := ChatPosition{ + tdCommon: tdCommon{Type: "chatPosition"}, + List: list, + Order: order, + IsPinned: isPinned, + Source: source, + } + + return &chatPositionTemp +} + +// UnmarshalJSON unmarshal to json +func (chatPosition *ChatPosition) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Order JSONInt64 `json:"order"` // A parameter used to determine order of the chat in the chat list. Chats must be sorted by the pair (order, chat.id) in descending order + IsPinned bool `json:"is_pinned"` // True, if the chat is pinned in the chat list + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatPosition.tdCommon = tempObj.tdCommon + chatPosition.Order = tempObj.Order + chatPosition.IsPinned = tempObj.IsPinned + + fieldList, _ := unmarshalChatList(objMap["list"]) + chatPosition.List = fieldList + + fieldSource, _ := unmarshalChatSource(objMap["source"]) + chatPosition.Source = fieldSource + + return nil +} diff --git a/tdlib/chatReportReason.go b/tdlib/chatReportReason.go new file mode 100644 index 0000000..4eaad37 --- /dev/null +++ b/tdlib/chatReportReason.go @@ -0,0 +1,285 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatReportReason Describes the reason why a chat is reported +type ChatReportReason interface { + GetChatReportReasonEnum() ChatReportReasonEnum +} + +// 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" + ChatReportReasonChildAbuseType ChatReportReasonEnum = "chatReportReasonChildAbuse" + ChatReportReasonCopyrightType ChatReportReasonEnum = "chatReportReasonCopyright" + ChatReportReasonUnrelatedLocationType ChatReportReasonEnum = "chatReportReasonUnrelatedLocation" + ChatReportReasonFakeType ChatReportReasonEnum = "chatReportReasonFake" + ChatReportReasonCustomType ChatReportReasonEnum = "chatReportReasonCustom" +) + +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 ChatReportReasonChildAbuseType: + var chatReportReasonChildAbuse ChatReportReasonChildAbuse + err := json.Unmarshal(*rawMsg, &chatReportReasonChildAbuse) + return &chatReportReasonChildAbuse, err + + case ChatReportReasonCopyrightType: + var chatReportReasonCopyright ChatReportReasonCopyright + err := json.Unmarshal(*rawMsg, &chatReportReasonCopyright) + return &chatReportReasonCopyright, err + + case ChatReportReasonUnrelatedLocationType: + var chatReportReasonUnrelatedLocation ChatReportReasonUnrelatedLocation + err := json.Unmarshal(*rawMsg, &chatReportReasonUnrelatedLocation) + return &chatReportReasonUnrelatedLocation, err + + case ChatReportReasonFakeType: + var chatReportReasonFake ChatReportReasonFake + err := json.Unmarshal(*rawMsg, &chatReportReasonFake) + return &chatReportReasonFake, 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)) + } +} + +// 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 +} + +// ChatReportReasonChildAbuse The chat has child abuse related content +type ChatReportReasonChildAbuse struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonChildAbuse +func (chatReportReasonChildAbuse *ChatReportReasonChildAbuse) MessageType() string { + return "chatReportReasonChildAbuse" +} + +// NewChatReportReasonChildAbuse creates a new ChatReportReasonChildAbuse +// +func NewChatReportReasonChildAbuse() *ChatReportReasonChildAbuse { + chatReportReasonChildAbuseTemp := ChatReportReasonChildAbuse{ + tdCommon: tdCommon{Type: "chatReportReasonChildAbuse"}, + } + + return &chatReportReasonChildAbuseTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonChildAbuse *ChatReportReasonChildAbuse) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonChildAbuseType +} + +// 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 +} + +// ChatReportReasonUnrelatedLocation The location-based chat is unrelated to its stated location +type ChatReportReasonUnrelatedLocation struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonUnrelatedLocation +func (chatReportReasonUnrelatedLocation *ChatReportReasonUnrelatedLocation) MessageType() string { + return "chatReportReasonUnrelatedLocation" +} + +// NewChatReportReasonUnrelatedLocation creates a new ChatReportReasonUnrelatedLocation +// +func NewChatReportReasonUnrelatedLocation() *ChatReportReasonUnrelatedLocation { + chatReportReasonUnrelatedLocationTemp := ChatReportReasonUnrelatedLocation{ + tdCommon: tdCommon{Type: "chatReportReasonUnrelatedLocation"}, + } + + return &chatReportReasonUnrelatedLocationTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonUnrelatedLocation *ChatReportReasonUnrelatedLocation) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonUnrelatedLocationType +} + +// ChatReportReasonFake The chat represents a fake account +type ChatReportReasonFake struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonFake +func (chatReportReasonFake *ChatReportReasonFake) MessageType() string { + return "chatReportReasonFake" +} + +// NewChatReportReasonFake creates a new ChatReportReasonFake +// +func NewChatReportReasonFake() *ChatReportReasonFake { + chatReportReasonFakeTemp := ChatReportReasonFake{ + tdCommon: tdCommon{Type: "chatReportReasonFake"}, + } + + return &chatReportReasonFakeTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonFake *ChatReportReasonFake) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonFakeType +} + +// ChatReportReasonCustom A custom reason provided by the user +type ChatReportReasonCustom struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatReportReasonCustom +func (chatReportReasonCustom *ChatReportReasonCustom) MessageType() string { + return "chatReportReasonCustom" +} + +// NewChatReportReasonCustom creates a new ChatReportReasonCustom +// +func NewChatReportReasonCustom() *ChatReportReasonCustom { + chatReportReasonCustomTemp := ChatReportReasonCustom{ + tdCommon: tdCommon{Type: "chatReportReasonCustom"}, + } + + return &chatReportReasonCustomTemp +} + +// GetChatReportReasonEnum return the enum type of this object +func (chatReportReasonCustom *ChatReportReasonCustom) GetChatReportReasonEnum() ChatReportReasonEnum { + return ChatReportReasonCustomType +} diff --git a/tdlib/chatSource.go b/tdlib/chatSource.go new file mode 100644 index 0000000..c167be3 --- /dev/null +++ b/tdlib/chatSource.go @@ -0,0 +1,105 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatSource Describes a reason why an external chat is shown in a chat list +type ChatSource interface { + GetChatSourceEnum() ChatSourceEnum +} + +// ChatSourceEnum Alias for abstract ChatSource 'Sub-Classes', used as constant-enum here +type ChatSourceEnum string + +// ChatSource enums +const ( + ChatSourceMtprotoProxyType ChatSourceEnum = "chatSourceMtprotoProxy" + ChatSourcePublicServiceAnnouncementType ChatSourceEnum = "chatSourcePublicServiceAnnouncement" +) + +func unmarshalChatSource(rawMsg *json.RawMessage) (ChatSource, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatSourceEnum(objMap["@type"].(string)) { + case ChatSourceMtprotoProxyType: + var chatSourceMtprotoProxy ChatSourceMtprotoProxy + err := json.Unmarshal(*rawMsg, &chatSourceMtprotoProxy) + return &chatSourceMtprotoProxy, err + + case ChatSourcePublicServiceAnnouncementType: + var chatSourcePublicServiceAnnouncement ChatSourcePublicServiceAnnouncement + err := json.Unmarshal(*rawMsg, &chatSourcePublicServiceAnnouncement) + return &chatSourcePublicServiceAnnouncement, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// ChatSourceMtprotoProxy The chat is sponsored by the user's MTProxy server +type ChatSourceMtprotoProxy struct { + tdCommon +} + +// MessageType return the string telegram-type of ChatSourceMtprotoProxy +func (chatSourceMtprotoProxy *ChatSourceMtprotoProxy) MessageType() string { + return "chatSourceMtprotoProxy" +} + +// NewChatSourceMtprotoProxy creates a new ChatSourceMtprotoProxy +// +func NewChatSourceMtprotoProxy() *ChatSourceMtprotoProxy { + chatSourceMtprotoProxyTemp := ChatSourceMtprotoProxy{ + tdCommon: tdCommon{Type: "chatSourceMtprotoProxy"}, + } + + return &chatSourceMtprotoProxyTemp +} + +// GetChatSourceEnum return the enum type of this object +func (chatSourceMtprotoProxy *ChatSourceMtprotoProxy) GetChatSourceEnum() ChatSourceEnum { + return ChatSourceMtprotoProxyType +} + +// ChatSourcePublicServiceAnnouncement The chat contains a public service announcement +type ChatSourcePublicServiceAnnouncement struct { + tdCommon + Type string `json:"type"` // The type of the announcement + Text string `json:"text"` // The text of the announcement +} + +// MessageType return the string telegram-type of ChatSourcePublicServiceAnnouncement +func (chatSourcePublicServiceAnnouncement *ChatSourcePublicServiceAnnouncement) MessageType() string { + return "chatSourcePublicServiceAnnouncement" +} + +// NewChatSourcePublicServiceAnnouncement creates a new ChatSourcePublicServiceAnnouncement +// +// @param typeParam The type of the announcement +// @param text The text of the announcement +func NewChatSourcePublicServiceAnnouncement(typeParam string, text string) *ChatSourcePublicServiceAnnouncement { + chatSourcePublicServiceAnnouncementTemp := ChatSourcePublicServiceAnnouncement{ + tdCommon: tdCommon{Type: "chatSourcePublicServiceAnnouncement"}, + Type: typeParam, + Text: text, + } + + return &chatSourcePublicServiceAnnouncementTemp +} + +// GetChatSourceEnum return the enum type of this object +func (chatSourcePublicServiceAnnouncement *ChatSourcePublicServiceAnnouncement) GetChatSourceEnum() ChatSourceEnum { + return ChatSourcePublicServiceAnnouncementType +} diff --git a/tdlib/chatStatistics.go b/tdlib/chatStatistics.go new file mode 100644 index 0000000..796ef08 --- /dev/null +++ b/tdlib/chatStatistics.go @@ -0,0 +1,311 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatStatistics Contains a detailed statistics about a chat +type ChatStatistics interface { + GetChatStatisticsEnum() ChatStatisticsEnum +} + +// ChatStatisticsEnum Alias for abstract ChatStatistics 'Sub-Classes', used as constant-enum here +type ChatStatisticsEnum string + +// ChatStatistics enums +const ( + ChatStatisticsSupergroupType ChatStatisticsEnum = "chatStatisticsSupergroup" + ChatStatisticsChannelType ChatStatisticsEnum = "chatStatisticsChannel" +) + +func unmarshalChatStatistics(rawMsg *json.RawMessage) (ChatStatistics, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ChatStatisticsEnum(objMap["@type"].(string)) { + case ChatStatisticsSupergroupType: + var chatStatisticsSupergroup ChatStatisticsSupergroup + err := json.Unmarshal(*rawMsg, &chatStatisticsSupergroup) + return &chatStatisticsSupergroup, err + + case ChatStatisticsChannelType: + var chatStatisticsChannel ChatStatisticsChannel + err := json.Unmarshal(*rawMsg, &chatStatisticsChannel) + return &chatStatisticsChannel, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// ChatStatisticsSupergroup A detailed statistics about a supergroup chat +type ChatStatisticsSupergroup struct { + tdCommon + Period *DateRange `json:"period"` // A period to which the statistics applies + MemberCount *StatisticalValue `json:"member_count"` // Number of members in the chat + MessageCount *StatisticalValue `json:"message_count"` // Number of messages sent to the chat + ViewerCount *StatisticalValue `json:"viewer_count"` // Number of users who viewed messages in the chat + SenderCount *StatisticalValue `json:"sender_count"` // Number of users who sent messages to the chat + MemberCountGraph StatisticalGraph `json:"member_count_graph"` // A graph containing number of members in the chat + JoinGraph StatisticalGraph `json:"join_graph"` // A graph containing number of members joined and left the chat + JoinBySourceGraph StatisticalGraph `json:"join_by_source_graph"` // A graph containing number of new member joins per source + LanguageGraph StatisticalGraph `json:"language_graph"` // A graph containing distribution of active users per language + MessageContentGraph StatisticalGraph `json:"message_content_graph"` // A graph containing distribution of sent messages by content type + ActionGraph StatisticalGraph `json:"action_graph"` // A graph containing number of different actions in the chat + DayGraph StatisticalGraph `json:"day_graph"` // A graph containing distribution of message views per hour + WeekGraph StatisticalGraph `json:"week_graph"` // A graph containing distribution of message views per day of week + TopSenders []ChatStatisticsMessageSenderInfo `json:"top_senders"` // List of users sent most messages in the last week + TopAdministrators []ChatStatisticsAdministratorActionsInfo `json:"top_administrators"` // List of most active administrators in the last week + TopInviters []ChatStatisticsInviterInfo `json:"top_inviters"` // List of most active inviters of new members in the last week +} + +// MessageType return the string telegram-type of ChatStatisticsSupergroup +func (chatStatisticsSupergroup *ChatStatisticsSupergroup) MessageType() string { + return "chatStatisticsSupergroup" +} + +// NewChatStatisticsSupergroup creates a new ChatStatisticsSupergroup +// +// @param period A period to which the statistics applies +// @param memberCount Number of members in the chat +// @param messageCount Number of messages sent to the chat +// @param viewerCount Number of users who viewed messages in the chat +// @param senderCount Number of users who sent messages to the chat +// @param memberCountGraph A graph containing number of members in the chat +// @param joinGraph A graph containing number of members joined and left the chat +// @param joinBySourceGraph A graph containing number of new member joins per source +// @param languageGraph A graph containing distribution of active users per language +// @param messageContentGraph A graph containing distribution of sent messages by content type +// @param actionGraph A graph containing number of different actions in the chat +// @param dayGraph A graph containing distribution of message views per hour +// @param weekGraph A graph containing distribution of message views per day of week +// @param topSenders List of users sent most messages in the last week +// @param topAdministrators List of most active administrators in the last week +// @param topInviters List of most active inviters of new members in the last week +func NewChatStatisticsSupergroup(period *DateRange, memberCount *StatisticalValue, messageCount *StatisticalValue, viewerCount *StatisticalValue, senderCount *StatisticalValue, memberCountGraph StatisticalGraph, joinGraph StatisticalGraph, joinBySourceGraph StatisticalGraph, languageGraph StatisticalGraph, messageContentGraph StatisticalGraph, actionGraph StatisticalGraph, dayGraph StatisticalGraph, weekGraph StatisticalGraph, topSenders []ChatStatisticsMessageSenderInfo, topAdministrators []ChatStatisticsAdministratorActionsInfo, topInviters []ChatStatisticsInviterInfo) *ChatStatisticsSupergroup { + chatStatisticsSupergroupTemp := ChatStatisticsSupergroup{ + tdCommon: tdCommon{Type: "chatStatisticsSupergroup"}, + Period: period, + MemberCount: memberCount, + MessageCount: messageCount, + ViewerCount: viewerCount, + SenderCount: senderCount, + MemberCountGraph: memberCountGraph, + JoinGraph: joinGraph, + JoinBySourceGraph: joinBySourceGraph, + LanguageGraph: languageGraph, + MessageContentGraph: messageContentGraph, + ActionGraph: actionGraph, + DayGraph: dayGraph, + WeekGraph: weekGraph, + TopSenders: topSenders, + TopAdministrators: topAdministrators, + TopInviters: topInviters, + } + + return &chatStatisticsSupergroupTemp +} + +// UnmarshalJSON unmarshal to json +func (chatStatisticsSupergroup *ChatStatisticsSupergroup) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Period *DateRange `json:"period"` // A period to which the statistics applies + MemberCount *StatisticalValue `json:"member_count"` // Number of members in the chat + MessageCount *StatisticalValue `json:"message_count"` // Number of messages sent to the chat + ViewerCount *StatisticalValue `json:"viewer_count"` // Number of users who viewed messages in the chat + SenderCount *StatisticalValue `json:"sender_count"` // Number of users who sent messages to the chat + TopSenders []ChatStatisticsMessageSenderInfo `json:"top_senders"` // List of users sent most messages in the last week + TopAdministrators []ChatStatisticsAdministratorActionsInfo `json:"top_administrators"` // List of most active administrators in the last week + TopInviters []ChatStatisticsInviterInfo `json:"top_inviters"` // List of most active inviters of new members in the last week + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatStatisticsSupergroup.tdCommon = tempObj.tdCommon + chatStatisticsSupergroup.Period = tempObj.Period + chatStatisticsSupergroup.MemberCount = tempObj.MemberCount + chatStatisticsSupergroup.MessageCount = tempObj.MessageCount + chatStatisticsSupergroup.ViewerCount = tempObj.ViewerCount + chatStatisticsSupergroup.SenderCount = tempObj.SenderCount + chatStatisticsSupergroup.TopSenders = tempObj.TopSenders + chatStatisticsSupergroup.TopAdministrators = tempObj.TopAdministrators + chatStatisticsSupergroup.TopInviters = tempObj.TopInviters + + fieldMemberCountGraph, _ := unmarshalStatisticalGraph(objMap["member_count_graph"]) + chatStatisticsSupergroup.MemberCountGraph = fieldMemberCountGraph + + fieldJoinGraph, _ := unmarshalStatisticalGraph(objMap["join_graph"]) + chatStatisticsSupergroup.JoinGraph = fieldJoinGraph + + fieldJoinBySourceGraph, _ := unmarshalStatisticalGraph(objMap["join_by_source_graph"]) + chatStatisticsSupergroup.JoinBySourceGraph = fieldJoinBySourceGraph + + fieldLanguageGraph, _ := unmarshalStatisticalGraph(objMap["language_graph"]) + chatStatisticsSupergroup.LanguageGraph = fieldLanguageGraph + + fieldMessageContentGraph, _ := unmarshalStatisticalGraph(objMap["message_content_graph"]) + chatStatisticsSupergroup.MessageContentGraph = fieldMessageContentGraph + + fieldActionGraph, _ := unmarshalStatisticalGraph(objMap["action_graph"]) + chatStatisticsSupergroup.ActionGraph = fieldActionGraph + + fieldDayGraph, _ := unmarshalStatisticalGraph(objMap["day_graph"]) + chatStatisticsSupergroup.DayGraph = fieldDayGraph + + fieldWeekGraph, _ := unmarshalStatisticalGraph(objMap["week_graph"]) + chatStatisticsSupergroup.WeekGraph = fieldWeekGraph + + return nil +} + +// GetChatStatisticsEnum return the enum type of this object +func (chatStatisticsSupergroup *ChatStatisticsSupergroup) GetChatStatisticsEnum() ChatStatisticsEnum { + return ChatStatisticsSupergroupType +} + +// ChatStatisticsChannel A detailed statistics about a channel chat +type ChatStatisticsChannel struct { + tdCommon + Period *DateRange `json:"period"` // A period to which the statistics applies + MemberCount *StatisticalValue `json:"member_count"` // Number of members in the chat + MeanViewCount *StatisticalValue `json:"mean_view_count"` // Mean number of times the recently sent messages was viewed + MeanShareCount *StatisticalValue `json:"mean_share_count"` // Mean number of times the recently sent messages was shared + EnabledNotificationsPercentage float64 `json:"enabled_notifications_percentage"` // A percentage of users with enabled notifications for the chat + MemberCountGraph StatisticalGraph `json:"member_count_graph"` // A graph containing number of members in the chat + JoinGraph StatisticalGraph `json:"join_graph"` // A graph containing number of members joined and left the chat + MuteGraph StatisticalGraph `json:"mute_graph"` // A graph containing number of members muted and unmuted the chat + ViewCountByHourGraph StatisticalGraph `json:"view_count_by_hour_graph"` // A graph containing number of message views in a given hour in the last two weeks + ViewCountBySourceGraph StatisticalGraph `json:"view_count_by_source_graph"` // A graph containing number of message views per source + JoinBySourceGraph StatisticalGraph `json:"join_by_source_graph"` // A graph containing number of new member joins per source + LanguageGraph StatisticalGraph `json:"language_graph"` // A graph containing number of users viewed chat messages per language + MessageInteractionGraph StatisticalGraph `json:"message_interaction_graph"` // A graph containing number of chat message views and shares + InstantViewInteractionGraph StatisticalGraph `json:"instant_view_interaction_graph"` // A graph containing number of views of associated with the chat instant views + RecentMessageInteractions []ChatStatisticsMessageInteractionInfo `json:"recent_message_interactions"` // Detailed statistics about number of views and shares of recently sent messages +} + +// MessageType return the string telegram-type of ChatStatisticsChannel +func (chatStatisticsChannel *ChatStatisticsChannel) MessageType() string { + return "chatStatisticsChannel" +} + +// NewChatStatisticsChannel creates a new ChatStatisticsChannel +// +// @param period A period to which the statistics applies +// @param memberCount Number of members in the chat +// @param meanViewCount Mean number of times the recently sent messages was viewed +// @param meanShareCount Mean number of times the recently sent messages was shared +// @param enabledNotificationsPercentage A percentage of users with enabled notifications for the chat +// @param memberCountGraph A graph containing number of members in the chat +// @param joinGraph A graph containing number of members joined and left the chat +// @param muteGraph A graph containing number of members muted and unmuted the chat +// @param viewCountByHourGraph A graph containing number of message views in a given hour in the last two weeks +// @param viewCountBySourceGraph A graph containing number of message views per source +// @param joinBySourceGraph A graph containing number of new member joins per source +// @param languageGraph A graph containing number of users viewed chat messages per language +// @param messageInteractionGraph A graph containing number of chat message views and shares +// @param instantViewInteractionGraph A graph containing number of views of associated with the chat instant views +// @param recentMessageInteractions Detailed statistics about number of views and shares of recently sent messages +func NewChatStatisticsChannel(period *DateRange, memberCount *StatisticalValue, meanViewCount *StatisticalValue, meanShareCount *StatisticalValue, enabledNotificationsPercentage float64, memberCountGraph StatisticalGraph, joinGraph StatisticalGraph, muteGraph StatisticalGraph, viewCountByHourGraph StatisticalGraph, viewCountBySourceGraph StatisticalGraph, joinBySourceGraph StatisticalGraph, languageGraph StatisticalGraph, messageInteractionGraph StatisticalGraph, instantViewInteractionGraph StatisticalGraph, recentMessageInteractions []ChatStatisticsMessageInteractionInfo) *ChatStatisticsChannel { + chatStatisticsChannelTemp := ChatStatisticsChannel{ + tdCommon: tdCommon{Type: "chatStatisticsChannel"}, + Period: period, + MemberCount: memberCount, + MeanViewCount: meanViewCount, + MeanShareCount: meanShareCount, + EnabledNotificationsPercentage: enabledNotificationsPercentage, + MemberCountGraph: memberCountGraph, + JoinGraph: joinGraph, + MuteGraph: muteGraph, + ViewCountByHourGraph: viewCountByHourGraph, + ViewCountBySourceGraph: viewCountBySourceGraph, + JoinBySourceGraph: joinBySourceGraph, + LanguageGraph: languageGraph, + MessageInteractionGraph: messageInteractionGraph, + InstantViewInteractionGraph: instantViewInteractionGraph, + RecentMessageInteractions: recentMessageInteractions, + } + + return &chatStatisticsChannelTemp +} + +// UnmarshalJSON unmarshal to json +func (chatStatisticsChannel *ChatStatisticsChannel) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Period *DateRange `json:"period"` // A period to which the statistics applies + MemberCount *StatisticalValue `json:"member_count"` // Number of members in the chat + MeanViewCount *StatisticalValue `json:"mean_view_count"` // Mean number of times the recently sent messages was viewed + MeanShareCount *StatisticalValue `json:"mean_share_count"` // Mean number of times the recently sent messages was shared + EnabledNotificationsPercentage float64 `json:"enabled_notifications_percentage"` // A percentage of users with enabled notifications for the chat + RecentMessageInteractions []ChatStatisticsMessageInteractionInfo `json:"recent_message_interactions"` // Detailed statistics about number of views and shares of recently sent messages + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + chatStatisticsChannel.tdCommon = tempObj.tdCommon + chatStatisticsChannel.Period = tempObj.Period + chatStatisticsChannel.MemberCount = tempObj.MemberCount + chatStatisticsChannel.MeanViewCount = tempObj.MeanViewCount + chatStatisticsChannel.MeanShareCount = tempObj.MeanShareCount + chatStatisticsChannel.EnabledNotificationsPercentage = tempObj.EnabledNotificationsPercentage + chatStatisticsChannel.RecentMessageInteractions = tempObj.RecentMessageInteractions + + fieldMemberCountGraph, _ := unmarshalStatisticalGraph(objMap["member_count_graph"]) + chatStatisticsChannel.MemberCountGraph = fieldMemberCountGraph + + fieldJoinGraph, _ := unmarshalStatisticalGraph(objMap["join_graph"]) + chatStatisticsChannel.JoinGraph = fieldJoinGraph + + fieldMuteGraph, _ := unmarshalStatisticalGraph(objMap["mute_graph"]) + chatStatisticsChannel.MuteGraph = fieldMuteGraph + + fieldViewCountByHourGraph, _ := unmarshalStatisticalGraph(objMap["view_count_by_hour_graph"]) + chatStatisticsChannel.ViewCountByHourGraph = fieldViewCountByHourGraph + + fieldViewCountBySourceGraph, _ := unmarshalStatisticalGraph(objMap["view_count_by_source_graph"]) + chatStatisticsChannel.ViewCountBySourceGraph = fieldViewCountBySourceGraph + + fieldJoinBySourceGraph, _ := unmarshalStatisticalGraph(objMap["join_by_source_graph"]) + chatStatisticsChannel.JoinBySourceGraph = fieldJoinBySourceGraph + + fieldLanguageGraph, _ := unmarshalStatisticalGraph(objMap["language_graph"]) + chatStatisticsChannel.LanguageGraph = fieldLanguageGraph + + fieldMessageInteractionGraph, _ := unmarshalStatisticalGraph(objMap["message_interaction_graph"]) + chatStatisticsChannel.MessageInteractionGraph = fieldMessageInteractionGraph + + fieldInstantViewInteractionGraph, _ := unmarshalStatisticalGraph(objMap["instant_view_interaction_graph"]) + chatStatisticsChannel.InstantViewInteractionGraph = fieldInstantViewInteractionGraph + + return nil +} + +// GetChatStatisticsEnum return the enum type of this object +func (chatStatisticsChannel *ChatStatisticsChannel) GetChatStatisticsEnum() ChatStatisticsEnum { + return ChatStatisticsChannelType +} diff --git a/tdlib/chatStatisticsAdministratorActionsInfo.go b/tdlib/chatStatisticsAdministratorActionsInfo.go new file mode 100644 index 0000000..69c8e9c --- /dev/null +++ b/tdlib/chatStatisticsAdministratorActionsInfo.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatStatisticsAdministratorActionsInfo Contains statistics about administrator actions done by a user +type ChatStatisticsAdministratorActionsInfo struct { + tdCommon + UserID int64 `json:"user_id"` // Administrator user identifier + DeletedMessageCount int32 `json:"deleted_message_count"` // Number of messages deleted by the administrator + BannedUserCount int32 `json:"banned_user_count"` // Number of users banned by the administrator + RestrictedUserCount int32 `json:"restricted_user_count"` // Number of users restricted by the administrator +} + +// MessageType return the string telegram-type of ChatStatisticsAdministratorActionsInfo +func (chatStatisticsAdministratorActionsInfo *ChatStatisticsAdministratorActionsInfo) MessageType() string { + return "chatStatisticsAdministratorActionsInfo" +} + +// NewChatStatisticsAdministratorActionsInfo creates a new ChatStatisticsAdministratorActionsInfo +// +// @param userID Administrator user identifier +// @param deletedMessageCount Number of messages deleted by the administrator +// @param bannedUserCount Number of users banned by the administrator +// @param restrictedUserCount Number of users restricted by the administrator +func NewChatStatisticsAdministratorActionsInfo(userID int64, deletedMessageCount int32, bannedUserCount int32, restrictedUserCount int32) *ChatStatisticsAdministratorActionsInfo { + chatStatisticsAdministratorActionsInfoTemp := ChatStatisticsAdministratorActionsInfo{ + tdCommon: tdCommon{Type: "chatStatisticsAdministratorActionsInfo"}, + UserID: userID, + DeletedMessageCount: deletedMessageCount, + BannedUserCount: bannedUserCount, + RestrictedUserCount: restrictedUserCount, + } + + return &chatStatisticsAdministratorActionsInfoTemp +} diff --git a/tdlib/chatStatisticsInviterInfo.go b/tdlib/chatStatisticsInviterInfo.go new file mode 100644 index 0000000..5ed7ea9 --- /dev/null +++ b/tdlib/chatStatisticsInviterInfo.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatStatisticsInviterInfo Contains statistics about number of new members invited by a user +type ChatStatisticsInviterInfo struct { + tdCommon + UserID int64 `json:"user_id"` // User identifier + AddedMemberCount int32 `json:"added_member_count"` // Number of new members invited by the user +} + +// MessageType return the string telegram-type of ChatStatisticsInviterInfo +func (chatStatisticsInviterInfo *ChatStatisticsInviterInfo) MessageType() string { + return "chatStatisticsInviterInfo" +} + +// NewChatStatisticsInviterInfo creates a new ChatStatisticsInviterInfo +// +// @param userID User identifier +// @param addedMemberCount Number of new members invited by the user +func NewChatStatisticsInviterInfo(userID int64, addedMemberCount int32) *ChatStatisticsInviterInfo { + chatStatisticsInviterInfoTemp := ChatStatisticsInviterInfo{ + tdCommon: tdCommon{Type: "chatStatisticsInviterInfo"}, + UserID: userID, + AddedMemberCount: addedMemberCount, + } + + return &chatStatisticsInviterInfoTemp +} diff --git a/tdlib/chatStatisticsMessageInteractionInfo.go b/tdlib/chatStatisticsMessageInteractionInfo.go new file mode 100644 index 0000000..e2f769f --- /dev/null +++ b/tdlib/chatStatisticsMessageInteractionInfo.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatStatisticsMessageInteractionInfo Contains statistics about interactions with a message +type ChatStatisticsMessageInteractionInfo struct { + tdCommon + MessageID int64 `json:"message_id"` // Message identifier + ViewCount int32 `json:"view_count"` // Number of times the message was viewed + ForwardCount int32 `json:"forward_count"` // Number of times the message was forwarded +} + +// MessageType return the string telegram-type of ChatStatisticsMessageInteractionInfo +func (chatStatisticsMessageInteractionInfo *ChatStatisticsMessageInteractionInfo) MessageType() string { + return "chatStatisticsMessageInteractionInfo" +} + +// NewChatStatisticsMessageInteractionInfo creates a new ChatStatisticsMessageInteractionInfo +// +// @param messageID Message identifier +// @param viewCount Number of times the message was viewed +// @param forwardCount Number of times the message was forwarded +func NewChatStatisticsMessageInteractionInfo(messageID int64, viewCount int32, forwardCount int32) *ChatStatisticsMessageInteractionInfo { + chatStatisticsMessageInteractionInfoTemp := ChatStatisticsMessageInteractionInfo{ + tdCommon: tdCommon{Type: "chatStatisticsMessageInteractionInfo"}, + MessageID: messageID, + ViewCount: viewCount, + ForwardCount: forwardCount, + } + + return &chatStatisticsMessageInteractionInfoTemp +} diff --git a/tdlib/chatStatisticsMessageSenderInfo.go b/tdlib/chatStatisticsMessageSenderInfo.go new file mode 100644 index 0000000..7a8cb41 --- /dev/null +++ b/tdlib/chatStatisticsMessageSenderInfo.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatStatisticsMessageSenderInfo Contains statistics about messages sent by a user +type ChatStatisticsMessageSenderInfo struct { + tdCommon + UserID int64 `json:"user_id"` // User identifier + SentMessageCount int32 `json:"sent_message_count"` // Number of sent messages + AverageCharacterCount int32 `json:"average_character_count"` // Average number of characters in sent messages; 0 if unknown +} + +// MessageType return the string telegram-type of ChatStatisticsMessageSenderInfo +func (chatStatisticsMessageSenderInfo *ChatStatisticsMessageSenderInfo) MessageType() string { + return "chatStatisticsMessageSenderInfo" +} + +// NewChatStatisticsMessageSenderInfo creates a new ChatStatisticsMessageSenderInfo +// +// @param userID User identifier +// @param sentMessageCount Number of sent messages +// @param averageCharacterCount Average number of characters in sent messages; 0 if unknown +func NewChatStatisticsMessageSenderInfo(userID int64, sentMessageCount int32, averageCharacterCount int32) *ChatStatisticsMessageSenderInfo { + chatStatisticsMessageSenderInfoTemp := ChatStatisticsMessageSenderInfo{ + tdCommon: tdCommon{Type: "chatStatisticsMessageSenderInfo"}, + UserID: userID, + SentMessageCount: sentMessageCount, + AverageCharacterCount: averageCharacterCount, + } + + return &chatStatisticsMessageSenderInfoTemp +} diff --git a/tdlib/chatTheme.go b/tdlib/chatTheme.go new file mode 100644 index 0000000..af0fa48 --- /dev/null +++ b/tdlib/chatTheme.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatTheme Describes a chat theme +type ChatTheme struct { + tdCommon + Name string `json:"name"` // Theme name + LightSettings *ThemeSettings `json:"light_settings"` // Theme settings for a light chat theme + DarkSettings *ThemeSettings `json:"dark_settings"` // Theme settings for a dark chat theme +} + +// MessageType return the string telegram-type of ChatTheme +func (chatTheme *ChatTheme) MessageType() string { + return "chatTheme" +} + +// NewChatTheme creates a new ChatTheme +// +// @param name Theme name +// @param lightSettings Theme settings for a light chat theme +// @param darkSettings Theme settings for a dark chat theme +func NewChatTheme(name string, lightSettings *ThemeSettings, darkSettings *ThemeSettings) *ChatTheme { + chatThemeTemp := ChatTheme{ + tdCommon: tdCommon{Type: "chatTheme"}, + Name: name, + LightSettings: lightSettings, + DarkSettings: darkSettings, + } + + return &chatThemeTemp +} diff --git a/tdlib/chatType.go b/tdlib/chatType.go new file mode 100644 index 0000000..2dcac7a --- /dev/null +++ b/tdlib/chatType.go @@ -0,0 +1,179 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ChatType Describes the type of a chat +type ChatType interface { + GetChatTypeEnum() ChatTypeEnum +} + +// 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" +) + +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)) + } +} + +// ChatTypePrivate An ordinary chat with a user +type ChatTypePrivate struct { + tdCommon + UserID int64 `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 int64) *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 int64 `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 int64) *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 int64 `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 int64, 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 int64 `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 int64) *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 +} diff --git a/tdlib/chats.go b/tdlib/chats.go new file mode 100644 index 0000000..2bc11d6 --- /dev/null +++ b/tdlib/chats.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Chats Represents a list of chats +type Chats struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of chats found + 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 totalCount Approximate total count of chats found +// @param chatIDs List of chat identifiers +func NewChats(totalCount int32, chatIDs []int64) *Chats { + chatsTemp := Chats{ + tdCommon: tdCommon{Type: "chats"}, + TotalCount: totalCount, + ChatIDs: chatIDs, + } + + return &chatsTemp +} diff --git a/tdlib/chatsNearby.go b/tdlib/chatsNearby.go new file mode 100644 index 0000000..6c3257f --- /dev/null +++ b/tdlib/chatsNearby.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ChatsNearby Represents a list of chats located nearby +type ChatsNearby struct { + tdCommon + UsersNearby []ChatNearby `json:"users_nearby"` // List of users nearby + SupergroupsNearby []ChatNearby `json:"supergroups_nearby"` // List of location-based supergroups nearby +} + +// MessageType return the string telegram-type of ChatsNearby +func (chatsNearby *ChatsNearby) MessageType() string { + return "chatsNearby" +} + +// NewChatsNearby creates a new ChatsNearby +// +// @param usersNearby List of users nearby +// @param supergroupsNearby List of location-based supergroups nearby +func NewChatsNearby(usersNearby []ChatNearby, supergroupsNearby []ChatNearby) *ChatsNearby { + chatsNearbyTemp := ChatsNearby{ + tdCommon: tdCommon{Type: "chatsNearby"}, + UsersNearby: usersNearby, + SupergroupsNearby: supergroupsNearby, + } + + return &chatsNearbyTemp +} diff --git a/tdlib/checkChatUsernameResult.go b/tdlib/checkChatUsernameResult.go new file mode 100644 index 0000000..0c357bf --- /dev/null +++ b/tdlib/checkChatUsernameResult.go @@ -0,0 +1,192 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CheckChatUsernameResult Represents result of checking whether a username can be set for a chat +type CheckChatUsernameResult interface { + GetCheckChatUsernameResultEnum() CheckChatUsernameResultEnum +} + +// 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" +) + +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)) + } +} + +// 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 chats with username, 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 +} diff --git a/tdlib/checkStickerSetNameResult.go b/tdlib/checkStickerSetNameResult.go new file mode 100644 index 0000000..fa70271 --- /dev/null +++ b/tdlib/checkStickerSetNameResult.go @@ -0,0 +1,130 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// CheckStickerSetNameResult Represents result of checking whether a name can be used for a new sticker set +type CheckStickerSetNameResult interface { + GetCheckStickerSetNameResultEnum() CheckStickerSetNameResultEnum +} + +// CheckStickerSetNameResultEnum Alias for abstract CheckStickerSetNameResult 'Sub-Classes', used as constant-enum here +type CheckStickerSetNameResultEnum string + +// CheckStickerSetNameResult enums +const ( + CheckStickerSetNameResultOkType CheckStickerSetNameResultEnum = "checkStickerSetNameResultOk" + CheckStickerSetNameResultNameInvalidType CheckStickerSetNameResultEnum = "checkStickerSetNameResultNameInvalid" + CheckStickerSetNameResultNameOccupiedType CheckStickerSetNameResultEnum = "checkStickerSetNameResultNameOccupied" +) + +func unmarshalCheckStickerSetNameResult(rawMsg *json.RawMessage) (CheckStickerSetNameResult, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch CheckStickerSetNameResultEnum(objMap["@type"].(string)) { + case CheckStickerSetNameResultOkType: + var checkStickerSetNameResultOk CheckStickerSetNameResultOk + err := json.Unmarshal(*rawMsg, &checkStickerSetNameResultOk) + return &checkStickerSetNameResultOk, err + + case CheckStickerSetNameResultNameInvalidType: + var checkStickerSetNameResultNameInvalid CheckStickerSetNameResultNameInvalid + err := json.Unmarshal(*rawMsg, &checkStickerSetNameResultNameInvalid) + return &checkStickerSetNameResultNameInvalid, err + + case CheckStickerSetNameResultNameOccupiedType: + var checkStickerSetNameResultNameOccupied CheckStickerSetNameResultNameOccupied + err := json.Unmarshal(*rawMsg, &checkStickerSetNameResultNameOccupied) + return &checkStickerSetNameResultNameOccupied, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// CheckStickerSetNameResultOk The name can be set +type CheckStickerSetNameResultOk struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckStickerSetNameResultOk +func (checkStickerSetNameResultOk *CheckStickerSetNameResultOk) MessageType() string { + return "checkStickerSetNameResultOk" +} + +// NewCheckStickerSetNameResultOk creates a new CheckStickerSetNameResultOk +// +func NewCheckStickerSetNameResultOk() *CheckStickerSetNameResultOk { + checkStickerSetNameResultOkTemp := CheckStickerSetNameResultOk{ + tdCommon: tdCommon{Type: "checkStickerSetNameResultOk"}, + } + + return &checkStickerSetNameResultOkTemp +} + +// GetCheckStickerSetNameResultEnum return the enum type of this object +func (checkStickerSetNameResultOk *CheckStickerSetNameResultOk) GetCheckStickerSetNameResultEnum() CheckStickerSetNameResultEnum { + return CheckStickerSetNameResultOkType +} + +// CheckStickerSetNameResultNameInvalid The name is invalid +type CheckStickerSetNameResultNameInvalid struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckStickerSetNameResultNameInvalid +func (checkStickerSetNameResultNameInvalid *CheckStickerSetNameResultNameInvalid) MessageType() string { + return "checkStickerSetNameResultNameInvalid" +} + +// NewCheckStickerSetNameResultNameInvalid creates a new CheckStickerSetNameResultNameInvalid +// +func NewCheckStickerSetNameResultNameInvalid() *CheckStickerSetNameResultNameInvalid { + checkStickerSetNameResultNameInvalidTemp := CheckStickerSetNameResultNameInvalid{ + tdCommon: tdCommon{Type: "checkStickerSetNameResultNameInvalid"}, + } + + return &checkStickerSetNameResultNameInvalidTemp +} + +// GetCheckStickerSetNameResultEnum return the enum type of this object +func (checkStickerSetNameResultNameInvalid *CheckStickerSetNameResultNameInvalid) GetCheckStickerSetNameResultEnum() CheckStickerSetNameResultEnum { + return CheckStickerSetNameResultNameInvalidType +} + +// CheckStickerSetNameResultNameOccupied The name is occupied +type CheckStickerSetNameResultNameOccupied struct { + tdCommon +} + +// MessageType return the string telegram-type of CheckStickerSetNameResultNameOccupied +func (checkStickerSetNameResultNameOccupied *CheckStickerSetNameResultNameOccupied) MessageType() string { + return "checkStickerSetNameResultNameOccupied" +} + +// NewCheckStickerSetNameResultNameOccupied creates a new CheckStickerSetNameResultNameOccupied +// +func NewCheckStickerSetNameResultNameOccupied() *CheckStickerSetNameResultNameOccupied { + checkStickerSetNameResultNameOccupiedTemp := CheckStickerSetNameResultNameOccupied{ + tdCommon: tdCommon{Type: "checkStickerSetNameResultNameOccupied"}, + } + + return &checkStickerSetNameResultNameOccupiedTemp +} + +// GetCheckStickerSetNameResultEnum return the enum type of this object +func (checkStickerSetNameResultNameOccupied *CheckStickerSetNameResultNameOccupied) GetCheckStickerSetNameResultEnum() CheckStickerSetNameResultEnum { + return CheckStickerSetNameResultNameOccupiedType +} diff --git a/tdlib/closedVectorPath.go b/tdlib/closedVectorPath.go new file mode 100644 index 0000000..49bad33 --- /dev/null +++ b/tdlib/closedVectorPath.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ClosedVectorPath Represents a closed vector path. The path begins at the end point of the last command +type ClosedVectorPath struct { + tdCommon + Commands []VectorPathCommand `json:"commands"` // List of vector path commands +} + +// MessageType return the string telegram-type of ClosedVectorPath +func (closedVectorPath *ClosedVectorPath) MessageType() string { + return "closedVectorPath" +} + +// NewClosedVectorPath creates a new ClosedVectorPath +// +// @param commands List of vector path commands +func NewClosedVectorPath(commands []VectorPathCommand) *ClosedVectorPath { + closedVectorPathTemp := ClosedVectorPath{ + tdCommon: tdCommon{Type: "closedVectorPath"}, + Commands: commands, + } + + return &closedVectorPathTemp +} diff --git a/tdlib/common.go b/tdlib/common.go new file mode 100644 index 0000000..96c9f28 --- /dev/null +++ b/tdlib/common.go @@ -0,0 +1,58 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "strconv" + "strings" +) + +type tdCommon struct { + Type string `json:"@type"` + Extra string `json:"@extra"` +} + +// TdMessage is the interface for all messages send and received to/from tdlib +type TdMessage interface { + MessageType() string +} + +// RequestError represents an error returned from tdlib. +type RequestError struct { + Code int + Message string +} + +func (re RequestError) Error() string { + return "error! code: " + strconv.FormatInt(int64(re.Code), 10) + " msg: " + re.Message +} + +// JSONInt64 alias for int64, in order to deal with json big number problem +type JSONInt64 int64 + +// UpdateData alias for use in UpdateMsg +type UpdateData map[string]interface{} + +// UpdateMsg is used to unmarshal received json strings into +type UpdateMsg struct { + Data UpdateData + Raw []byte +} + +// 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 +} diff --git a/tdlib/connectedWebsite.go b/tdlib/connectedWebsite.go new file mode 100644 index 0000000..30809fa --- /dev/null +++ b/tdlib/connectedWebsite.go @@ -0,0 +1,50 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 int64 `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 int64, 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 +} diff --git a/tdlib/connectedWebsites.go b/tdlib/connectedWebsites.go new file mode 100644 index 0000000..8ae7834 --- /dev/null +++ b/tdlib/connectedWebsites.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/connectionState.go b/tdlib/connectionState.go new file mode 100644 index 0000000..e7e2e47 --- /dev/null +++ b/tdlib/connectionState.go @@ -0,0 +1,192 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ConnectionState Describes the current state of the connection to Telegram servers +type ConnectionState interface { + GetConnectionStateEnum() ConnectionStateEnum +} + +// 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" +) + +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)) + } +} + +// 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 application 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 +} diff --git a/tdlib/contact.go b/tdlib/contact.go new file mode 100644 index 0000000..91cdd30 --- /dev/null +++ b/tdlib/contact.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 int64 `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 int64) *Contact { + contactTemp := Contact{ + tdCommon: tdCommon{Type: "contact"}, + PhoneNumber: phoneNumber, + FirstName: firstName, + LastName: lastName, + Vcard: vcard, + UserID: userID, + } + + return &contactTemp +} diff --git a/tdlib/count.go b/tdlib/count.go new file mode 100644 index 0000000..c08ecf2 --- /dev/null +++ b/tdlib/count.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/countries.go b/tdlib/countries.go new file mode 100644 index 0000000..a833789 --- /dev/null +++ b/tdlib/countries.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Countries Contains information about countries +type Countries struct { + tdCommon + Countries []CountryInfo `json:"countries"` // The list of countries +} + +// MessageType return the string telegram-type of Countries +func (countries *Countries) MessageType() string { + return "countries" +} + +// NewCountries creates a new Countries +// +// @param countries The list of countries +func NewCountries(countries []CountryInfo) *Countries { + countriesTemp := Countries{ + tdCommon: tdCommon{Type: "countries"}, + Countries: countries, + } + + return &countriesTemp +} diff --git a/tdlib/countryInfo.go b/tdlib/countryInfo.go new file mode 100644 index 0000000..35acc66 --- /dev/null +++ b/tdlib/countryInfo.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// CountryInfo Contains information about a country +type CountryInfo struct { + tdCommon + CountryCode string `json:"country_code"` // A two-letter ISO 3166-1 alpha-2 country code + Name string `json:"name"` // Native name of the country + EnglishName string `json:"english_name"` // English name of the country + IsHidden bool `json:"is_hidden"` // True, if the country should be hidden from the list of all countries + CallingCodes []string `json:"calling_codes"` // List of country calling codes +} + +// MessageType return the string telegram-type of CountryInfo +func (countryInfo *CountryInfo) MessageType() string { + return "countryInfo" +} + +// NewCountryInfo creates a new CountryInfo +// +// @param countryCode A two-letter ISO 3166-1 alpha-2 country code +// @param name Native name of the country +// @param englishName English name of the country +// @param isHidden True, if the country should be hidden from the list of all countries +// @param callingCodes List of country calling codes +func NewCountryInfo(countryCode string, name string, englishName string, isHidden bool, callingCodes []string) *CountryInfo { + countryInfoTemp := CountryInfo{ + tdCommon: tdCommon{Type: "countryInfo"}, + CountryCode: countryCode, + Name: name, + EnglishName: englishName, + IsHidden: isHidden, + CallingCodes: callingCodes, + } + + return &countryInfoTemp +} diff --git a/tdlib/customRequestResult.go b/tdlib/customRequestResult.go new file mode 100644 index 0000000..4b1bbeb --- /dev/null +++ b/tdlib/customRequestResult.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/databaseStatistics.go b/tdlib/databaseStatistics.go new file mode 100644 index 0000000..42e6139 --- /dev/null +++ b/tdlib/databaseStatistics.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// DatabaseStatistics Contains database statistics +type DatabaseStatistics struct { + tdCommon + Statistics string `json:"statistics"` // Database statistics in an unspecified human-readable format +} + +// MessageType return the string telegram-type of DatabaseStatistics +func (databaseStatistics *DatabaseStatistics) MessageType() string { + return "databaseStatistics" +} + +// NewDatabaseStatistics creates a new DatabaseStatistics +// +// @param statistics Database statistics in an unspecified human-readable format +func NewDatabaseStatistics(statistics string) *DatabaseStatistics { + databaseStatisticsTemp := DatabaseStatistics{ + tdCommon: tdCommon{Type: "databaseStatistics"}, + Statistics: statistics, + } + + return &databaseStatisticsTemp +} diff --git a/tdlib/date.go b/tdlib/date.go new file mode 100644 index 0000000..635ed8c --- /dev/null +++ b/tdlib/date.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/dateRange.go b/tdlib/dateRange.go new file mode 100644 index 0000000..785e00d --- /dev/null +++ b/tdlib/dateRange.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// DateRange Represents a date range +type DateRange struct { + tdCommon + StartDate int32 `json:"start_date"` // Point in time (Unix timestamp) at which the date range begins + EndDate int32 `json:"end_date"` // Point in time (Unix timestamp) at which the date range ends +} + +// MessageType return the string telegram-type of DateRange +func (dateRange *DateRange) MessageType() string { + return "dateRange" +} + +// NewDateRange creates a new DateRange +// +// @param startDate Point in time (Unix timestamp) at which the date range begins +// @param endDate Point in time (Unix timestamp) at which the date range ends +func NewDateRange(startDate int32, endDate int32) *DateRange { + dateRangeTemp := DateRange{ + tdCommon: tdCommon{Type: "dateRange"}, + StartDate: startDate, + EndDate: endDate, + } + + return &dateRangeTemp +} diff --git a/tdlib/datedFile.go b/tdlib/datedFile.go new file mode 100644 index 0000000..327190b --- /dev/null +++ b/tdlib/datedFile.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/deepLinkInfo.go b/tdlib/deepLinkInfo.go new file mode 100644 index 0000000..852dfc4 --- /dev/null +++ b/tdlib/deepLinkInfo.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/deviceToken.go b/tdlib/deviceToken.go new file mode 100644 index 0000000..46cbe53 --- /dev/null +++ b/tdlib/deviceToken.go @@ -0,0 +1,429 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// DeviceToken Represents a data needed to subscribe for push notifications through registerDevice method. To use specific push notification service, the correct application platform must be specified and a valid server authentication data must be uploaded at https://my.telegram.org +type DeviceToken interface { + GetDeviceTokenEnum() DeviceTokenEnum +} + +// DeviceTokenEnum Alias for abstract DeviceToken 'Sub-Classes', used as constant-enum here +type DeviceTokenEnum string + +// DeviceToken enums +const ( + DeviceTokenFirebaseCloudMessagingType DeviceTokenEnum = "deviceTokenFirebaseCloudMessaging" + 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" +) + +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 DeviceTokenFirebaseCloudMessagingType: + var deviceTokenFirebaseCloudMessaging DeviceTokenFirebaseCloudMessaging + err := json.Unmarshal(*rawMsg, &deviceTokenFirebaseCloudMessaging) + return &deviceTokenFirebaseCloudMessaging, 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)) + } +} + +// DeviceTokenFirebaseCloudMessaging A token for Firebase Cloud Messaging +type DeviceTokenFirebaseCloudMessaging struct { + tdCommon + Token string `json:"token"` // Device registration token; may be empty to de-register a device + Encrypt bool `json:"encrypt"` // True, if push notifications should be additionally encrypted +} + +// MessageType return the string telegram-type of DeviceTokenFirebaseCloudMessaging +func (deviceTokenFirebaseCloudMessaging *DeviceTokenFirebaseCloudMessaging) MessageType() string { + return "deviceTokenFirebaseCloudMessaging" +} + +// NewDeviceTokenFirebaseCloudMessaging creates a new DeviceTokenFirebaseCloudMessaging +// +// @param token Device registration token; may be empty to de-register a device +// @param encrypt True, if push notifications should be additionally encrypted +func NewDeviceTokenFirebaseCloudMessaging(token string, encrypt bool) *DeviceTokenFirebaseCloudMessaging { + deviceTokenFirebaseCloudMessagingTemp := DeviceTokenFirebaseCloudMessaging{ + tdCommon: tdCommon{Type: "deviceTokenFirebaseCloudMessaging"}, + Token: token, + Encrypt: encrypt, + } + + return &deviceTokenFirebaseCloudMessagingTemp +} + +// GetDeviceTokenEnum return the enum type of this object +func (deviceTokenFirebaseCloudMessaging *DeviceTokenFirebaseCloudMessaging) GetDeviceTokenEnum() DeviceTokenEnum { + return DeviceTokenFirebaseCloudMessagingType +} + +// 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 + Encrypt bool `json:"encrypt"` // True, if push notifications should be additionally encrypted +} + +// 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 +// @param encrypt True, if push notifications should be additionally encrypted +func NewDeviceTokenApplePushVoIP(deviceToken string, isAppSandbox bool, encrypt bool) *DeviceTokenApplePushVoIP { + deviceTokenApplePushVoIPTemp := DeviceTokenApplePushVoIP{ + tdCommon: tdCommon{Type: "deviceTokenApplePushVoIP"}, + DeviceToken: deviceToken, + IsAppSandbox: isAppSandbox, + Encrypt: encrypt, + } + + 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 +} diff --git a/tdlib/diceStickers.go b/tdlib/diceStickers.go new file mode 100644 index 0000000..4cc5b65 --- /dev/null +++ b/tdlib/diceStickers.go @@ -0,0 +1,117 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// DiceStickers Contains animated stickers which should be used for dice animation rendering +type DiceStickers interface { + GetDiceStickersEnum() DiceStickersEnum +} + +// DiceStickersEnum Alias for abstract DiceStickers 'Sub-Classes', used as constant-enum here +type DiceStickersEnum string + +// DiceStickers enums +const ( + DiceStickersRegularType DiceStickersEnum = "diceStickersRegular" + DiceStickersSlotMachineType DiceStickersEnum = "diceStickersSlotMachine" +) + +func unmarshalDiceStickers(rawMsg *json.RawMessage) (DiceStickers, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch DiceStickersEnum(objMap["@type"].(string)) { + case DiceStickersRegularType: + var diceStickersRegular DiceStickersRegular + err := json.Unmarshal(*rawMsg, &diceStickersRegular) + return &diceStickersRegular, err + + case DiceStickersSlotMachineType: + var diceStickersSlotMachine DiceStickersSlotMachine + err := json.Unmarshal(*rawMsg, &diceStickersSlotMachine) + return &diceStickersSlotMachine, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// DiceStickersRegular A regular animated sticker +type DiceStickersRegular struct { + tdCommon + Sticker *Sticker `json:"sticker"` // The animated sticker with the dice animation +} + +// MessageType return the string telegram-type of DiceStickersRegular +func (diceStickersRegular *DiceStickersRegular) MessageType() string { + return "diceStickersRegular" +} + +// NewDiceStickersRegular creates a new DiceStickersRegular +// +// @param sticker The animated sticker with the dice animation +func NewDiceStickersRegular(sticker *Sticker) *DiceStickersRegular { + diceStickersRegularTemp := DiceStickersRegular{ + tdCommon: tdCommon{Type: "diceStickersRegular"}, + Sticker: sticker, + } + + return &diceStickersRegularTemp +} + +// GetDiceStickersEnum return the enum type of this object +func (diceStickersRegular *DiceStickersRegular) GetDiceStickersEnum() DiceStickersEnum { + return DiceStickersRegularType +} + +// DiceStickersSlotMachine Animated stickers to be combined into a slot machine +type DiceStickersSlotMachine struct { + tdCommon + Background *Sticker `json:"background"` // The animated sticker with the slot machine background. The background animation must start playing after all reel animations finish + Lever *Sticker `json:"lever"` // The animated sticker with the lever animation. The lever animation must play once in the initial dice state + LeftReel *Sticker `json:"left_reel"` // The animated sticker with the left reel + CenterReel *Sticker `json:"center_reel"` // The animated sticker with the center reel + RightReel *Sticker `json:"right_reel"` // The animated sticker with the right reel +} + +// MessageType return the string telegram-type of DiceStickersSlotMachine +func (diceStickersSlotMachine *DiceStickersSlotMachine) MessageType() string { + return "diceStickersSlotMachine" +} + +// NewDiceStickersSlotMachine creates a new DiceStickersSlotMachine +// +// @param background The animated sticker with the slot machine background. The background animation must start playing after all reel animations finish +// @param lever The animated sticker with the lever animation. The lever animation must play once in the initial dice state +// @param leftReel The animated sticker with the left reel +// @param centerReel The animated sticker with the center reel +// @param rightReel The animated sticker with the right reel +func NewDiceStickersSlotMachine(background *Sticker, lever *Sticker, leftReel *Sticker, centerReel *Sticker, rightReel *Sticker) *DiceStickersSlotMachine { + diceStickersSlotMachineTemp := DiceStickersSlotMachine{ + tdCommon: tdCommon{Type: "diceStickersSlotMachine"}, + Background: background, + Lever: lever, + LeftReel: leftReel, + CenterReel: centerReel, + RightReel: rightReel, + } + + return &diceStickersSlotMachineTemp +} + +// GetDiceStickersEnum return the enum type of this object +func (diceStickersSlotMachine *DiceStickersSlotMachine) GetDiceStickersEnum() DiceStickersEnum { + return DiceStickersSlotMachineType +} diff --git a/tdlib/document.go b/tdlib/document.go new file mode 100644 index 0000000..76a0d66 --- /dev/null +++ b/tdlib/document.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + Minithumbnail *Minithumbnail `json:"minithumbnail"` // Document minithumbnail; may be null + Thumbnail *Thumbnail `json:"thumbnail"` // Document thumbnail in JPEG or PNG format (PNG will be used only for background patterns); 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 minithumbnail Document minithumbnail; may be null +// @param thumbnail Document thumbnail in JPEG or PNG format (PNG will be used only for background patterns); as defined by the sender; may be null +// @param document File containing the document +func NewDocument(fileName string, mimeType string, minithumbnail *Minithumbnail, thumbnail *Thumbnail, document *File) *Document { + documentTemp := Document{ + tdCommon: tdCommon{Type: "document"}, + FileName: fileName, + MimeType: mimeType, + Minithumbnail: minithumbnail, + Thumbnail: thumbnail, + Document: document, + } + + return &documentTemp +} diff --git a/tdlib/draftMessage.go b/tdlib/draftMessage.go new file mode 100644 index 0000000..b8085b5 --- /dev/null +++ b/tdlib/draftMessage.go @@ -0,0 +1,64 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 + Date int32 `json:"date"` // Point in time (Unix timestamp) when the draft was created + 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 date Point in time (Unix timestamp) when the draft was created +// @param inputMessageText Content of the message draft; this should always be of type inputMessageText +func NewDraftMessage(replyToMessageID int64, date int32, inputMessageText InputMessageContent) *DraftMessage { + draftMessageTemp := DraftMessage{ + tdCommon: tdCommon{Type: "draftMessage"}, + ReplyToMessageID: replyToMessageID, + Date: date, + 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 + Date int32 `json:"date"` // Point in time (Unix timestamp) when the draft was created + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + draftMessage.tdCommon = tempObj.tdCommon + draftMessage.ReplyToMessageID = tempObj.ReplyToMessageID + draftMessage.Date = tempObj.Date + + fieldInputMessageText, _ := unmarshalInputMessageContent(objMap["input_message_text"]) + draftMessage.InputMessageText = fieldInputMessageText + + return nil +} diff --git a/tdlib/emailAddressAuthenticationCodeInfo.go b/tdlib/emailAddressAuthenticationCodeInfo.go new file mode 100644 index 0000000..a1a66c5 --- /dev/null +++ b/tdlib/emailAddressAuthenticationCodeInfo.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/emojis.go b/tdlib/emojis.go new file mode 100644 index 0000000..533ae4b --- /dev/null +++ b/tdlib/emojis.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Emojis Represents a list of emoji +type Emojis struct { + tdCommon + Emojis []string `json:"emojis"` // List of emojis +} + +// MessageType return the string telegram-type of Emojis +func (emojis *Emojis) MessageType() string { + return "emojis" +} + +// NewEmojis creates a new Emojis +// +// @param emojis List of emojis +func NewEmojis(emojis []string) *Emojis { + emojisTemp := Emojis{ + tdCommon: tdCommon{Type: "emojis"}, + Emojis: emojis, + } + + return &emojisTemp +} diff --git a/tdlib/encryptedCredentials.go b/tdlib/encryptedCredentials.go new file mode 100644 index 0000000..e8d193c --- /dev/null +++ b/tdlib/encryptedCredentials.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/encryptedPassportElement.go b/tdlib/encryptedPassportElement.go new file mode 100644 index 0000000..647fbcf --- /dev/null +++ b/tdlib/encryptedPassportElement.go @@ -0,0 +1,93 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/error.go b/tdlib/error.go new file mode 100644 index 0000000..b96e419 --- /dev/null +++ b/tdlib/error.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/file.go b/tdlib/file.go new file mode 100644 index 0000000..7c07631 --- /dev/null +++ b/tdlib/file.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// File Represents a file +type File struct { + tdCommon + ID int32 `json:"id"` // Unique file identifier + Size int32 `json:"size"` // File size, in bytes; 0 if unknown + ExpectedSize int32 `json:"expected_size"` // Approximate file size in bytes in case the exact file size is unknown. 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, in bytes; 0 if unknown +// @param expectedSize Approximate file size in bytes in case the exact file size is unknown. 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 +} diff --git a/tdlib/filePart.go b/tdlib/filePart.go new file mode 100644 index 0000000..5ecb917 --- /dev/null +++ b/tdlib/filePart.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// FilePart Contains a part of a file +type FilePart struct { + tdCommon + Data []byte `json:"data"` // File bytes +} + +// MessageType return the string telegram-type of FilePart +func (filePart *FilePart) MessageType() string { + return "filePart" +} + +// NewFilePart creates a new FilePart +// +// @param data File bytes +func NewFilePart(data []byte) *FilePart { + filePartTemp := FilePart{ + tdCommon: tdCommon{Type: "filePart"}, + Data: data, + } + + return &filePartTemp +} diff --git a/tdlib/fileType.go b/tdlib/fileType.go new file mode 100644 index 0000000..cd1b1b8 --- /dev/null +++ b/tdlib/fileType.go @@ -0,0 +1,533 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// FileType Represents the type of a file +type FileType interface { + GetFileTypeEnum() FileTypeEnum +} + +// 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" +) + +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)) + } +} + +// 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 or a background pattern +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 +} diff --git a/tdlib/formattedText.go b/tdlib/formattedText.go new file mode 100644 index 0000000..abe959f --- /dev/null +++ b/tdlib/formattedText.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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. Entities can be nested, but must not mutually intersect with each other. Pre, Code and PreCode entities can't contain other entities. Bold, Italic, Underline and Strikethrough entities can contain and to be contained in all other entities. All other entities can't contain each other +} + +// 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. Entities can be nested, but must not mutually intersect with each other. Pre, Code and PreCode entities can't contain other entities. Bold, Italic, Underline and Strikethrough entities can contain and to be contained in all other entities. All other entities can't contain each other +func NewFormattedText(text string, entities []TextEntity) *FormattedText { + formattedTextTemp := FormattedText{ + tdCommon: tdCommon{Type: "formattedText"}, + Text: text, + Entities: entities, + } + + return &formattedTextTemp +} diff --git a/tdlib/foundMessages.go b/tdlib/foundMessages.go new file mode 100644 index 0000000..5c96dbf --- /dev/null +++ b/tdlib/foundMessages.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// FoundMessages Contains a list of messages found by a search +type FoundMessages struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of messages found; -1 if unknown + Messages []Message `json:"messages"` // List of messages + NextOffset string `json:"next_offset"` // The offset for the next request. If empty, there are no more results +} + +// MessageType return the string telegram-type of FoundMessages +func (foundMessages *FoundMessages) MessageType() string { + return "foundMessages" +} + +// NewFoundMessages creates a new FoundMessages +// +// @param totalCount Approximate total count of messages found; -1 if unknown +// @param messages List of messages +// @param nextOffset The offset for the next request. If empty, there are no more results +func NewFoundMessages(totalCount int32, messages []Message, nextOffset string) *FoundMessages { + foundMessagesTemp := FoundMessages{ + tdCommon: tdCommon{Type: "foundMessages"}, + TotalCount: totalCount, + Messages: messages, + NextOffset: nextOffset, + } + + return &foundMessagesTemp +} diff --git a/tdlib/game.go b/tdlib/game.go new file mode 100644 index 0000000..0329e66 --- /dev/null +++ b/tdlib/game.go @@ -0,0 +1,44 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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"` // Game 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 Game 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 +} diff --git a/tdlib/gameHighScore.go b/tdlib/gameHighScore.go new file mode 100644 index 0000000..bc84e0f --- /dev/null +++ b/tdlib/gameHighScore.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 int64 `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 int64, score int32) *GameHighScore { + gameHighScoreTemp := GameHighScore{ + tdCommon: tdCommon{Type: "gameHighScore"}, + Position: position, + UserID: userID, + Score: score, + } + + return &gameHighScoreTemp +} diff --git a/tdlib/gameHighScores.go b/tdlib/gameHighScores.go new file mode 100644 index 0000000..66730be --- /dev/null +++ b/tdlib/gameHighScores.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/groupCall.go b/tdlib/groupCall.go new file mode 100644 index 0000000..f4441a2 --- /dev/null +++ b/tdlib/groupCall.go @@ -0,0 +1,80 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// GroupCall Describes a group call +type GroupCall struct { + tdCommon + ID int32 `json:"id"` // Group call identifier + Title string `json:"title"` // Group call title + ScheduledStartDate int32 `json:"scheduled_start_date"` // Point in time (Unix timestamp) when the group call is supposed to be started by an administrator; 0 if it is already active or was ended + EnabledStartNotification bool `json:"enabled_start_notification"` // True, if the group call is scheduled and the current user will receive a notification when the group call will start + IsActive bool `json:"is_active"` // True, if the call is active + IsJoined bool `json:"is_joined"` // True, if the call is joined + NeedRejoin bool `json:"need_rejoin"` // True, if user was kicked from the call because of network loss and the call needs to be rejoined + CanBeManaged bool `json:"can_be_managed"` // True, if the current user can manage the group call + ParticipantCount int32 `json:"participant_count"` // Number of participants in the group call + LoadedAllParticipants bool `json:"loaded_all_participants"` // True, if all group call participants are loaded + RecentSpeakers []GroupCallRecentSpeaker `json:"recent_speakers"` // Recently speaking users in the group call + IsMyVideoEnabled bool `json:"is_my_video_enabled"` // True, if the current user's video is enabled + IsMyVideoPaused bool `json:"is_my_video_paused"` // True, if the current user's video is paused + CanEnableVideo bool `json:"can_enable_video"` // True, if the current user can broadcast video or share screen + MuteNewParticipants bool `json:"mute_new_participants"` // True, if only group call administrators can unmute new participants + CanChangeMuteNewParticipants bool `json:"can_change_mute_new_participants"` // True, if the current user can enable or disable mute_new_participants setting + RecordDuration int32 `json:"record_duration"` // Duration of the ongoing group call recording, in seconds; 0 if none. An updateGroupCall update is not triggered when value of this field changes, but the same recording goes on + IsVideoRecorded bool `json:"is_video_recorded"` // True, if a video file is being recorded for the call + Duration int32 `json:"duration"` // Call duration, in seconds; for ended calls only +} + +// MessageType return the string telegram-type of GroupCall +func (groupCall *GroupCall) MessageType() string { + return "groupCall" +} + +// NewGroupCall creates a new GroupCall +// +// @param iD Group call identifier +// @param title Group call title +// @param scheduledStartDate Point in time (Unix timestamp) when the group call is supposed to be started by an administrator; 0 if it is already active or was ended +// @param enabledStartNotification True, if the group call is scheduled and the current user will receive a notification when the group call will start +// @param isActive True, if the call is active +// @param isJoined True, if the call is joined +// @param needRejoin True, if user was kicked from the call because of network loss and the call needs to be rejoined +// @param canBeManaged True, if the current user can manage the group call +// @param participantCount Number of participants in the group call +// @param loadedAllParticipants True, if all group call participants are loaded +// @param recentSpeakers Recently speaking users in the group call +// @param isMyVideoEnabled True, if the current user's video is enabled +// @param isMyVideoPaused True, if the current user's video is paused +// @param canEnableVideo True, if the current user can broadcast video or share screen +// @param muteNewParticipants True, if only group call administrators can unmute new participants +// @param canChangeMuteNewParticipants True, if the current user can enable or disable mute_new_participants setting +// @param recordDuration Duration of the ongoing group call recording, in seconds; 0 if none. An updateGroupCall update is not triggered when value of this field changes, but the same recording goes on +// @param isVideoRecorded True, if a video file is being recorded for the call +// @param duration Call duration, in seconds; for ended calls only +func NewGroupCall(iD int32, title string, scheduledStartDate int32, enabledStartNotification bool, isActive bool, isJoined bool, needRejoin bool, canBeManaged bool, participantCount int32, loadedAllParticipants bool, recentSpeakers []GroupCallRecentSpeaker, isMyVideoEnabled bool, isMyVideoPaused bool, canEnableVideo bool, muteNewParticipants bool, canChangeMuteNewParticipants bool, recordDuration int32, isVideoRecorded bool, duration int32) *GroupCall { + groupCallTemp := GroupCall{ + tdCommon: tdCommon{Type: "groupCall"}, + ID: iD, + Title: title, + ScheduledStartDate: scheduledStartDate, + EnabledStartNotification: enabledStartNotification, + IsActive: isActive, + IsJoined: isJoined, + NeedRejoin: needRejoin, + CanBeManaged: canBeManaged, + ParticipantCount: participantCount, + LoadedAllParticipants: loadedAllParticipants, + RecentSpeakers: recentSpeakers, + IsMyVideoEnabled: isMyVideoEnabled, + IsMyVideoPaused: isMyVideoPaused, + CanEnableVideo: canEnableVideo, + MuteNewParticipants: muteNewParticipants, + CanChangeMuteNewParticipants: canChangeMuteNewParticipants, + RecordDuration: recordDuration, + IsVideoRecorded: isVideoRecorded, + Duration: duration, + } + + return &groupCallTemp +} diff --git a/tdlib/groupCallID.go b/tdlib/groupCallID.go new file mode 100644 index 0000000..77f5f95 --- /dev/null +++ b/tdlib/groupCallID.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// GroupCallID Contains the group call identifier +type GroupCallID struct { + tdCommon + ID int32 `json:"id"` // Group call identifier +} + +// MessageType return the string telegram-type of GroupCallID +func (groupCallID *GroupCallID) MessageType() string { + return "groupCallId" +} + +// NewGroupCallID creates a new GroupCallID +// +// @param iD Group call identifier +func NewGroupCallID(iD int32) *GroupCallID { + groupCallIDTemp := GroupCallID{ + tdCommon: tdCommon{Type: "groupCallId"}, + ID: iD, + } + + return &groupCallIDTemp +} diff --git a/tdlib/groupCallParticipant.go b/tdlib/groupCallParticipant.go new file mode 100644 index 0000000..5b8bcfd --- /dev/null +++ b/tdlib/groupCallParticipant.go @@ -0,0 +1,138 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// GroupCallParticipant Represents a group call participant +type GroupCallParticipant struct { + tdCommon + ParticipantID MessageSender `json:"participant_id"` // Identifier of the group call participant + AudioSourceID int32 `json:"audio_source_id"` // User's audio channel synchronization source identifier + ScreenSharingAudioSourceID int32 `json:"screen_sharing_audio_source_id"` // User's screen sharing audio channel synchronization source identifier + VideoInfo *GroupCallParticipantVideoInfo `json:"video_info"` // Information about user's video channel; may be null if there is no active video + ScreenSharingVideoInfo *GroupCallParticipantVideoInfo `json:"screen_sharing_video_info"` // Information about user's screen sharing video channel; may be null if there is no active screen sharing video + Bio string `json:"bio"` // The participant user's bio or the participant chat's description + IsCurrentUser bool `json:"is_current_user"` // True, if the participant is the current user + IsSpeaking bool `json:"is_speaking"` // True, if the participant is speaking as set by setGroupCallParticipantIsSpeaking + IsHandRaised bool `json:"is_hand_raised"` // True, if the participant hand is raised + CanBeMutedForAllUsers bool `json:"can_be_muted_for_all_users"` // True, if the current user can mute the participant for all other group call participants + CanBeUnmutedForAllUsers bool `json:"can_be_unmuted_for_all_users"` // True, if the current user can allow the participant to unmute themselves or unmute the participant (if the participant is the current user) + CanBeMutedForCurrentUser bool `json:"can_be_muted_for_current_user"` // True, if the current user can mute the participant only for self + CanBeUnmutedForCurrentUser bool `json:"can_be_unmuted_for_current_user"` // True, if the current user can unmute the participant for self + IsMutedForAllUsers bool `json:"is_muted_for_all_users"` // True, if the participant is muted for all users + IsMutedForCurrentUser bool `json:"is_muted_for_current_user"` // True, if the participant is muted for the current user + CanUnmuteSelf bool `json:"can_unmute_self"` // True, if the participant is muted for all users, but can unmute themselves + VolumeLevel int32 `json:"volume_level"` // Participant's volume level; 1-20000 in hundreds of percents + Order string `json:"order"` // User's order in the group call participant list. Orders must be compared lexicographically. The bigger is order, the higher is user in the list. If order is empty, the user must be removed from the participant list +} + +// MessageType return the string telegram-type of GroupCallParticipant +func (groupCallParticipant *GroupCallParticipant) MessageType() string { + return "groupCallParticipant" +} + +// NewGroupCallParticipant creates a new GroupCallParticipant +// +// @param participantID Identifier of the group call participant +// @param audioSourceID User's audio channel synchronization source identifier +// @param screenSharingAudioSourceID User's screen sharing audio channel synchronization source identifier +// @param videoInfo Information about user's video channel; may be null if there is no active video +// @param screenSharingVideoInfo Information about user's screen sharing video channel; may be null if there is no active screen sharing video +// @param bio The participant user's bio or the participant chat's description +// @param isCurrentUser True, if the participant is the current user +// @param isSpeaking True, if the participant is speaking as set by setGroupCallParticipantIsSpeaking +// @param isHandRaised True, if the participant hand is raised +// @param canBeMutedForAllUsers True, if the current user can mute the participant for all other group call participants +// @param canBeUnmutedForAllUsers True, if the current user can allow the participant to unmute themselves or unmute the participant (if the participant is the current user) +// @param canBeMutedForCurrentUser True, if the current user can mute the participant only for self +// @param canBeUnmutedForCurrentUser True, if the current user can unmute the participant for self +// @param isMutedForAllUsers True, if the participant is muted for all users +// @param isMutedForCurrentUser True, if the participant is muted for the current user +// @param canUnmuteSelf True, if the participant is muted for all users, but can unmute themselves +// @param volumeLevel Participant's volume level; 1-20000 in hundreds of percents +// @param order User's order in the group call participant list. Orders must be compared lexicographically. The bigger is order, the higher is user in the list. If order is empty, the user must be removed from the participant list +func NewGroupCallParticipant(participantID MessageSender, audioSourceID int32, screenSharingAudioSourceID int32, videoInfo *GroupCallParticipantVideoInfo, screenSharingVideoInfo *GroupCallParticipantVideoInfo, bio string, isCurrentUser bool, isSpeaking bool, isHandRaised bool, canBeMutedForAllUsers bool, canBeUnmutedForAllUsers bool, canBeMutedForCurrentUser bool, canBeUnmutedForCurrentUser bool, isMutedForAllUsers bool, isMutedForCurrentUser bool, canUnmuteSelf bool, volumeLevel int32, order string) *GroupCallParticipant { + groupCallParticipantTemp := GroupCallParticipant{ + tdCommon: tdCommon{Type: "groupCallParticipant"}, + ParticipantID: participantID, + AudioSourceID: audioSourceID, + ScreenSharingAudioSourceID: screenSharingAudioSourceID, + VideoInfo: videoInfo, + ScreenSharingVideoInfo: screenSharingVideoInfo, + Bio: bio, + IsCurrentUser: isCurrentUser, + IsSpeaking: isSpeaking, + IsHandRaised: isHandRaised, + CanBeMutedForAllUsers: canBeMutedForAllUsers, + CanBeUnmutedForAllUsers: canBeUnmutedForAllUsers, + CanBeMutedForCurrentUser: canBeMutedForCurrentUser, + CanBeUnmutedForCurrentUser: canBeUnmutedForCurrentUser, + IsMutedForAllUsers: isMutedForAllUsers, + IsMutedForCurrentUser: isMutedForCurrentUser, + CanUnmuteSelf: canUnmuteSelf, + VolumeLevel: volumeLevel, + Order: order, + } + + return &groupCallParticipantTemp +} + +// UnmarshalJSON unmarshal to json +func (groupCallParticipant *GroupCallParticipant) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + AudioSourceID int32 `json:"audio_source_id"` // User's audio channel synchronization source identifier + ScreenSharingAudioSourceID int32 `json:"screen_sharing_audio_source_id"` // User's screen sharing audio channel synchronization source identifier + VideoInfo *GroupCallParticipantVideoInfo `json:"video_info"` // Information about user's video channel; may be null if there is no active video + ScreenSharingVideoInfo *GroupCallParticipantVideoInfo `json:"screen_sharing_video_info"` // Information about user's screen sharing video channel; may be null if there is no active screen sharing video + Bio string `json:"bio"` // The participant user's bio or the participant chat's description + IsCurrentUser bool `json:"is_current_user"` // True, if the participant is the current user + IsSpeaking bool `json:"is_speaking"` // True, if the participant is speaking as set by setGroupCallParticipantIsSpeaking + IsHandRaised bool `json:"is_hand_raised"` // True, if the participant hand is raised + CanBeMutedForAllUsers bool `json:"can_be_muted_for_all_users"` // True, if the current user can mute the participant for all other group call participants + CanBeUnmutedForAllUsers bool `json:"can_be_unmuted_for_all_users"` // True, if the current user can allow the participant to unmute themselves or unmute the participant (if the participant is the current user) + CanBeMutedForCurrentUser bool `json:"can_be_muted_for_current_user"` // True, if the current user can mute the participant only for self + CanBeUnmutedForCurrentUser bool `json:"can_be_unmuted_for_current_user"` // True, if the current user can unmute the participant for self + IsMutedForAllUsers bool `json:"is_muted_for_all_users"` // True, if the participant is muted for all users + IsMutedForCurrentUser bool `json:"is_muted_for_current_user"` // True, if the participant is muted for the current user + CanUnmuteSelf bool `json:"can_unmute_self"` // True, if the participant is muted for all users, but can unmute themselves + VolumeLevel int32 `json:"volume_level"` // Participant's volume level; 1-20000 in hundreds of percents + Order string `json:"order"` // User's order in the group call participant list. Orders must be compared lexicographically. The bigger is order, the higher is user in the list. If order is empty, the user must be removed from the participant list + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + groupCallParticipant.tdCommon = tempObj.tdCommon + groupCallParticipant.AudioSourceID = tempObj.AudioSourceID + groupCallParticipant.ScreenSharingAudioSourceID = tempObj.ScreenSharingAudioSourceID + groupCallParticipant.VideoInfo = tempObj.VideoInfo + groupCallParticipant.ScreenSharingVideoInfo = tempObj.ScreenSharingVideoInfo + groupCallParticipant.Bio = tempObj.Bio + groupCallParticipant.IsCurrentUser = tempObj.IsCurrentUser + groupCallParticipant.IsSpeaking = tempObj.IsSpeaking + groupCallParticipant.IsHandRaised = tempObj.IsHandRaised + groupCallParticipant.CanBeMutedForAllUsers = tempObj.CanBeMutedForAllUsers + groupCallParticipant.CanBeUnmutedForAllUsers = tempObj.CanBeUnmutedForAllUsers + groupCallParticipant.CanBeMutedForCurrentUser = tempObj.CanBeMutedForCurrentUser + groupCallParticipant.CanBeUnmutedForCurrentUser = tempObj.CanBeUnmutedForCurrentUser + groupCallParticipant.IsMutedForAllUsers = tempObj.IsMutedForAllUsers + groupCallParticipant.IsMutedForCurrentUser = tempObj.IsMutedForCurrentUser + groupCallParticipant.CanUnmuteSelf = tempObj.CanUnmuteSelf + groupCallParticipant.VolumeLevel = tempObj.VolumeLevel + groupCallParticipant.Order = tempObj.Order + + fieldParticipantID, _ := unmarshalMessageSender(objMap["participant_id"]) + groupCallParticipant.ParticipantID = fieldParticipantID + + return nil +} diff --git a/tdlib/groupCallParticipantVideoInfo.go b/tdlib/groupCallParticipantVideoInfo.go new file mode 100644 index 0000000..0084f7b --- /dev/null +++ b/tdlib/groupCallParticipantVideoInfo.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// GroupCallParticipantVideoInfo Contains information about a group call participant's video channel +type GroupCallParticipantVideoInfo struct { + tdCommon + SourceGroups []GroupCallVideoSourceGroup `json:"source_groups"` // List of synchronization source groups of the video + EndpointID string `json:"endpoint_id"` // Video channel endpoint identifier + IsPaused bool `json:"is_paused"` // True if the video is paused. This flag needs to be ignored, if new video frames are received +} + +// MessageType return the string telegram-type of GroupCallParticipantVideoInfo +func (groupCallParticipantVideoInfo *GroupCallParticipantVideoInfo) MessageType() string { + return "groupCallParticipantVideoInfo" +} + +// NewGroupCallParticipantVideoInfo creates a new GroupCallParticipantVideoInfo +// +// @param sourceGroups List of synchronization source groups of the video +// @param endpointID Video channel endpoint identifier +// @param isPaused True if the video is paused. This flag needs to be ignored, if new video frames are received +func NewGroupCallParticipantVideoInfo(sourceGroups []GroupCallVideoSourceGroup, endpointID string, isPaused bool) *GroupCallParticipantVideoInfo { + groupCallParticipantVideoInfoTemp := GroupCallParticipantVideoInfo{ + tdCommon: tdCommon{Type: "groupCallParticipantVideoInfo"}, + SourceGroups: sourceGroups, + EndpointID: endpointID, + IsPaused: isPaused, + } + + return &groupCallParticipantVideoInfoTemp +} diff --git a/tdlib/groupCallRecentSpeaker.go b/tdlib/groupCallRecentSpeaker.go new file mode 100644 index 0000000..c2b884b --- /dev/null +++ b/tdlib/groupCallRecentSpeaker.go @@ -0,0 +1,58 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// GroupCallRecentSpeaker Describes a recently speaking participant in a group call +type GroupCallRecentSpeaker struct { + tdCommon + ParticipantID MessageSender `json:"participant_id"` // Group call participant identifier + IsSpeaking bool `json:"is_speaking"` // True, is the user has spoken recently +} + +// MessageType return the string telegram-type of GroupCallRecentSpeaker +func (groupCallRecentSpeaker *GroupCallRecentSpeaker) MessageType() string { + return "groupCallRecentSpeaker" +} + +// NewGroupCallRecentSpeaker creates a new GroupCallRecentSpeaker +// +// @param participantID Group call participant identifier +// @param isSpeaking True, is the user has spoken recently +func NewGroupCallRecentSpeaker(participantID MessageSender, isSpeaking bool) *GroupCallRecentSpeaker { + groupCallRecentSpeakerTemp := GroupCallRecentSpeaker{ + tdCommon: tdCommon{Type: "groupCallRecentSpeaker"}, + ParticipantID: participantID, + IsSpeaking: isSpeaking, + } + + return &groupCallRecentSpeakerTemp +} + +// UnmarshalJSON unmarshal to json +func (groupCallRecentSpeaker *GroupCallRecentSpeaker) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + IsSpeaking bool `json:"is_speaking"` // True, is the user has spoken recently + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + groupCallRecentSpeaker.tdCommon = tempObj.tdCommon + groupCallRecentSpeaker.IsSpeaking = tempObj.IsSpeaking + + fieldParticipantID, _ := unmarshalMessageSender(objMap["participant_id"]) + groupCallRecentSpeaker.ParticipantID = fieldParticipantID + + return nil +} diff --git a/tdlib/groupCallVideoQuality.go b/tdlib/groupCallVideoQuality.go new file mode 100644 index 0000000..dc6d175 --- /dev/null +++ b/tdlib/groupCallVideoQuality.go @@ -0,0 +1,130 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// GroupCallVideoQuality Describes the quality of a group call video +type GroupCallVideoQuality interface { + GetGroupCallVideoQualityEnum() GroupCallVideoQualityEnum +} + +// GroupCallVideoQualityEnum Alias for abstract GroupCallVideoQuality 'Sub-Classes', used as constant-enum here +type GroupCallVideoQualityEnum string + +// GroupCallVideoQuality enums +const ( + GroupCallVideoQualityThumbnailType GroupCallVideoQualityEnum = "groupCallVideoQualityThumbnail" + GroupCallVideoQualityMediumType GroupCallVideoQualityEnum = "groupCallVideoQualityMedium" + GroupCallVideoQualityFullType GroupCallVideoQualityEnum = "groupCallVideoQualityFull" +) + +func unmarshalGroupCallVideoQuality(rawMsg *json.RawMessage) (GroupCallVideoQuality, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch GroupCallVideoQualityEnum(objMap["@type"].(string)) { + case GroupCallVideoQualityThumbnailType: + var groupCallVideoQualityThumbnail GroupCallVideoQualityThumbnail + err := json.Unmarshal(*rawMsg, &groupCallVideoQualityThumbnail) + return &groupCallVideoQualityThumbnail, err + + case GroupCallVideoQualityMediumType: + var groupCallVideoQualityMedium GroupCallVideoQualityMedium + err := json.Unmarshal(*rawMsg, &groupCallVideoQualityMedium) + return &groupCallVideoQualityMedium, err + + case GroupCallVideoQualityFullType: + var groupCallVideoQualityFull GroupCallVideoQualityFull + err := json.Unmarshal(*rawMsg, &groupCallVideoQualityFull) + return &groupCallVideoQualityFull, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// GroupCallVideoQualityThumbnail The worst available video quality +type GroupCallVideoQualityThumbnail struct { + tdCommon +} + +// MessageType return the string telegram-type of GroupCallVideoQualityThumbnail +func (groupCallVideoQualityThumbnail *GroupCallVideoQualityThumbnail) MessageType() string { + return "groupCallVideoQualityThumbnail" +} + +// NewGroupCallVideoQualityThumbnail creates a new GroupCallVideoQualityThumbnail +// +func NewGroupCallVideoQualityThumbnail() *GroupCallVideoQualityThumbnail { + groupCallVideoQualityThumbnailTemp := GroupCallVideoQualityThumbnail{ + tdCommon: tdCommon{Type: "groupCallVideoQualityThumbnail"}, + } + + return &groupCallVideoQualityThumbnailTemp +} + +// GetGroupCallVideoQualityEnum return the enum type of this object +func (groupCallVideoQualityThumbnail *GroupCallVideoQualityThumbnail) GetGroupCallVideoQualityEnum() GroupCallVideoQualityEnum { + return GroupCallVideoQualityThumbnailType +} + +// GroupCallVideoQualityMedium The medium video quality +type GroupCallVideoQualityMedium struct { + tdCommon +} + +// MessageType return the string telegram-type of GroupCallVideoQualityMedium +func (groupCallVideoQualityMedium *GroupCallVideoQualityMedium) MessageType() string { + return "groupCallVideoQualityMedium" +} + +// NewGroupCallVideoQualityMedium creates a new GroupCallVideoQualityMedium +// +func NewGroupCallVideoQualityMedium() *GroupCallVideoQualityMedium { + groupCallVideoQualityMediumTemp := GroupCallVideoQualityMedium{ + tdCommon: tdCommon{Type: "groupCallVideoQualityMedium"}, + } + + return &groupCallVideoQualityMediumTemp +} + +// GetGroupCallVideoQualityEnum return the enum type of this object +func (groupCallVideoQualityMedium *GroupCallVideoQualityMedium) GetGroupCallVideoQualityEnum() GroupCallVideoQualityEnum { + return GroupCallVideoQualityMediumType +} + +// GroupCallVideoQualityFull The best available video quality +type GroupCallVideoQualityFull struct { + tdCommon +} + +// MessageType return the string telegram-type of GroupCallVideoQualityFull +func (groupCallVideoQualityFull *GroupCallVideoQualityFull) MessageType() string { + return "groupCallVideoQualityFull" +} + +// NewGroupCallVideoQualityFull creates a new GroupCallVideoQualityFull +// +func NewGroupCallVideoQualityFull() *GroupCallVideoQualityFull { + groupCallVideoQualityFullTemp := GroupCallVideoQualityFull{ + tdCommon: tdCommon{Type: "groupCallVideoQualityFull"}, + } + + return &groupCallVideoQualityFullTemp +} + +// GetGroupCallVideoQualityEnum return the enum type of this object +func (groupCallVideoQualityFull *GroupCallVideoQualityFull) GetGroupCallVideoQualityEnum() GroupCallVideoQualityEnum { + return GroupCallVideoQualityFullType +} diff --git a/tdlib/groupCallVideoSourceGroup.go b/tdlib/groupCallVideoSourceGroup.go new file mode 100644 index 0000000..0be0184 --- /dev/null +++ b/tdlib/groupCallVideoSourceGroup.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// GroupCallVideoSourceGroup Describes a group of video synchronization source identifiers +type GroupCallVideoSourceGroup struct { + tdCommon + Semantics string `json:"semantics"` // The semantics of sources, one of "SIM" or "FID" + SourceIDs []int32 `json:"source_ids"` // The list of synchronization source identifiers +} + +// MessageType return the string telegram-type of GroupCallVideoSourceGroup +func (groupCallVideoSourceGroup *GroupCallVideoSourceGroup) MessageType() string { + return "groupCallVideoSourceGroup" +} + +// NewGroupCallVideoSourceGroup creates a new GroupCallVideoSourceGroup +// +// @param semantics The semantics of sources, one of "SIM" or "FID" +// @param sourceIDs The list of synchronization source identifiers +func NewGroupCallVideoSourceGroup(semantics string, sourceIDs []int32) *GroupCallVideoSourceGroup { + groupCallVideoSourceGroupTemp := GroupCallVideoSourceGroup{ + tdCommon: tdCommon{Type: "groupCallVideoSourceGroup"}, + Semantics: semantics, + SourceIDs: sourceIDs, + } + + return &groupCallVideoSourceGroupTemp +} diff --git a/tdlib/hashtags.go b/tdlib/hashtags.go new file mode 100644 index 0000000..8f3ac33 --- /dev/null +++ b/tdlib/hashtags.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/httpURL.go b/tdlib/httpURL.go new file mode 100644 index 0000000..311618a --- /dev/null +++ b/tdlib/httpURL.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// HttpURL Contains an HTTP URL +type HttpURL struct { + tdCommon + URL string `json:"url"` // The URL +} + +// MessageType return the string telegram-type of HttpURL +func (httpURL *HttpURL) MessageType() string { + return "httpUrl" +} + +// NewHttpURL creates a new HttpURL +// +// @param uRL The URL +func NewHttpURL(uRL string) *HttpURL { + httpURLTemp := HttpURL{ + tdCommon: tdCommon{Type: "httpUrl"}, + URL: uRL, + } + + return &httpURLTemp +} diff --git a/tdlib/iDentityDocument.go b/tdlib/iDentityDocument.go new file mode 100644 index 0000000..815e521 --- /dev/null +++ b/tdlib/iDentityDocument.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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; 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 +} + +// 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; 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 +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 +} diff --git a/tdlib/importedContacts.go b/tdlib/importedContacts.go new file mode 100644 index 0000000..f63bb9b --- /dev/null +++ b/tdlib/importedContacts.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// ImportedContacts Represents the result of an ImportContacts request +type ImportedContacts struct { + tdCommon + UserIDs []int64 `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 []int64, importerCount []int32) *ImportedContacts { + importedContactsTemp := ImportedContacts{ + tdCommon: tdCommon{Type: "importedContacts"}, + UserIDs: userIDs, + ImporterCount: importerCount, + } + + return &importedContactsTemp +} diff --git a/tdlib/inlineKeyboardButton.go b/tdlib/inlineKeyboardButton.go new file mode 100644 index 0000000..9341cd1 --- /dev/null +++ b/tdlib/inlineKeyboardButton.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/inlineKeyboardButtonType.go b/tdlib/inlineKeyboardButtonType.go new file mode 100644 index 0000000..838ab9d --- /dev/null +++ b/tdlib/inlineKeyboardButtonType.go @@ -0,0 +1,278 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InlineKeyboardButtonType Describes the type of an inline keyboard button +type InlineKeyboardButtonType interface { + GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum +} + +// InlineKeyboardButtonTypeEnum Alias for abstract InlineKeyboardButtonType 'Sub-Classes', used as constant-enum here +type InlineKeyboardButtonTypeEnum string + +// InlineKeyboardButtonType enums +const ( + InlineKeyboardButtonTypeURLType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeUrl" + InlineKeyboardButtonTypeLoginURLType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeLoginUrl" + InlineKeyboardButtonTypeCallbackType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeCallback" + InlineKeyboardButtonTypeCallbackWithPasswordType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeCallbackWithPassword" + InlineKeyboardButtonTypeCallbackGameType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeCallbackGame" + InlineKeyboardButtonTypeSwitchInlineType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeSwitchInline" + InlineKeyboardButtonTypeBuyType InlineKeyboardButtonTypeEnum = "inlineKeyboardButtonTypeBuy" +) + +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 InlineKeyboardButtonTypeLoginURLType: + var inlineKeyboardButtonTypeLoginURL InlineKeyboardButtonTypeLoginURL + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeLoginURL) + return &inlineKeyboardButtonTypeLoginURL, err + + case InlineKeyboardButtonTypeCallbackType: + var inlineKeyboardButtonTypeCallback InlineKeyboardButtonTypeCallback + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeCallback) + return &inlineKeyboardButtonTypeCallback, err + + case InlineKeyboardButtonTypeCallbackWithPasswordType: + var inlineKeyboardButtonTypeCallbackWithPassword InlineKeyboardButtonTypeCallbackWithPassword + err := json.Unmarshal(*rawMsg, &inlineKeyboardButtonTypeCallbackWithPassword) + return &inlineKeyboardButtonTypeCallbackWithPassword, 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)) + } +} + +// 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 +} + +// InlineKeyboardButtonTypeLoginURL A button that opens a specified URL and automatically authorize the current user if allowed to do so +type InlineKeyboardButtonTypeLoginURL struct { + tdCommon + URL string `json:"url"` // An HTTP URL to open + ID int64 `json:"id"` // Unique button identifier + ForwardText string `json:"forward_text"` // If non-empty, new text of the button in forwarded messages +} + +// MessageType return the string telegram-type of InlineKeyboardButtonTypeLoginURL +func (inlineKeyboardButtonTypeLoginURL *InlineKeyboardButtonTypeLoginURL) MessageType() string { + return "inlineKeyboardButtonTypeLoginUrl" +} + +// NewInlineKeyboardButtonTypeLoginURL creates a new InlineKeyboardButtonTypeLoginURL +// +// @param uRL An HTTP URL to open +// @param iD Unique button identifier +// @param forwardText If non-empty, new text of the button in forwarded messages +func NewInlineKeyboardButtonTypeLoginURL(uRL string, iD int64, forwardText string) *InlineKeyboardButtonTypeLoginURL { + inlineKeyboardButtonTypeLoginURLTemp := InlineKeyboardButtonTypeLoginURL{ + tdCommon: tdCommon{Type: "inlineKeyboardButtonTypeLoginUrl"}, + URL: uRL, + ID: iD, + ForwardText: forwardText, + } + + return &inlineKeyboardButtonTypeLoginURLTemp +} + +// GetInlineKeyboardButtonTypeEnum return the enum type of this object +func (inlineKeyboardButtonTypeLoginURL *InlineKeyboardButtonTypeLoginURL) GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum { + return InlineKeyboardButtonTypeLoginURLType +} + +// InlineKeyboardButtonTypeCallback A button that sends a 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 +} + +// InlineKeyboardButtonTypeCallbackWithPassword A button that asks for password of the current user and then sends a callback query to a bot +type InlineKeyboardButtonTypeCallbackWithPassword struct { + tdCommon + Data []byte `json:"data"` // Data to be sent to the bot via a callback query +} + +// MessageType return the string telegram-type of InlineKeyboardButtonTypeCallbackWithPassword +func (inlineKeyboardButtonTypeCallbackWithPassword *InlineKeyboardButtonTypeCallbackWithPassword) MessageType() string { + return "inlineKeyboardButtonTypeCallbackWithPassword" +} + +// NewInlineKeyboardButtonTypeCallbackWithPassword creates a new InlineKeyboardButtonTypeCallbackWithPassword +// +// @param data Data to be sent to the bot via a callback query +func NewInlineKeyboardButtonTypeCallbackWithPassword(data []byte) *InlineKeyboardButtonTypeCallbackWithPassword { + inlineKeyboardButtonTypeCallbackWithPasswordTemp := InlineKeyboardButtonTypeCallbackWithPassword{ + tdCommon: tdCommon{Type: "inlineKeyboardButtonTypeCallbackWithPassword"}, + Data: data, + } + + return &inlineKeyboardButtonTypeCallbackWithPasswordTemp +} + +// GetInlineKeyboardButtonTypeEnum return the enum type of this object +func (inlineKeyboardButtonTypeCallbackWithPassword *InlineKeyboardButtonTypeCallbackWithPassword) GetInlineKeyboardButtonTypeEnum() InlineKeyboardButtonTypeEnum { + return InlineKeyboardButtonTypeCallbackWithPasswordType +} + +// InlineKeyboardButtonTypeCallbackGame A button with a game that sends a 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 +} diff --git a/tdlib/inlineQueryResult.go b/tdlib/inlineQueryResult.go new file mode 100644 index 0000000..f8b88a2 --- /dev/null +++ b/tdlib/inlineQueryResult.go @@ -0,0 +1,529 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InlineQueryResult Represents a single result of an inline query +type InlineQueryResult interface { + GetInlineQueryResultEnum() InlineQueryResultEnum +} + +// 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" +) + +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)) + } +} + +// 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"` // A short description of the result + Thumbnail *Thumbnail `json:"thumbnail"` // Result thumbnail in JPEG format; 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 A short description of the result +// @param thumbnail Result thumbnail in JPEG format; may be null +func NewInlineQueryResultArticle(iD string, uRL string, hideURL bool, title string, description string, thumbnail *Thumbnail) *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 *Thumbnail `json:"thumbnail"` // Result thumbnail in JPEG format; 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 in JPEG format; may be null +func NewInlineQueryResultContact(iD string, contact *Contact, thumbnail *Thumbnail) *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 *Thumbnail `json:"thumbnail"` // Result thumbnail in JPEG format; 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 in JPEG format; may be null +func NewInlineQueryResultLocation(iD string, location *Location, title string, thumbnail *Thumbnail) *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 *Thumbnail `json:"thumbnail"` // Result thumbnail in JPEG format; 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 in JPEG format; may be null +func NewInlineQueryResultVenue(iD string, venue *Venue, thumbnail *Thumbnail) *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"` // Document 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 Document 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"` // A short description of the result, if known +} + +// 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 A short description of the result, if known +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"` // Description of the video +} + +// 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 Description of the video +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 +} diff --git a/tdlib/inlineQueryResults.go b/tdlib/inlineQueryResults.go new file mode 100644 index 0000000..0cd9416 --- /dev/null +++ b/tdlib/inlineQueryResults.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/inputBackground.go b/tdlib/inputBackground.go new file mode 100644 index 0000000..32f06ca --- /dev/null +++ b/tdlib/inputBackground.go @@ -0,0 +1,128 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputBackground Contains information about background to set +type InputBackground interface { + GetInputBackgroundEnum() InputBackgroundEnum +} + +// InputBackgroundEnum Alias for abstract InputBackground 'Sub-Classes', used as constant-enum here +type InputBackgroundEnum string + +// InputBackground enums +const ( + InputBackgroundLocalType InputBackgroundEnum = "inputBackgroundLocal" + InputBackgroundRemoteType InputBackgroundEnum = "inputBackgroundRemote" +) + +func unmarshalInputBackground(rawMsg *json.RawMessage) (InputBackground, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputBackgroundEnum(objMap["@type"].(string)) { + case InputBackgroundLocalType: + var inputBackgroundLocal InputBackgroundLocal + err := json.Unmarshal(*rawMsg, &inputBackgroundLocal) + return &inputBackgroundLocal, err + + case InputBackgroundRemoteType: + var inputBackgroundRemote InputBackgroundRemote + err := json.Unmarshal(*rawMsg, &inputBackgroundRemote) + return &inputBackgroundRemote, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// InputBackgroundLocal A background from a local file +type InputBackgroundLocal struct { + tdCommon + Background InputFile `json:"background"` // Background file to use. Only inputFileLocal and inputFileGenerated are supported. The file must be in JPEG format for wallpapers and in PNG format for patterns +} + +// MessageType return the string telegram-type of InputBackgroundLocal +func (inputBackgroundLocal *InputBackgroundLocal) MessageType() string { + return "inputBackgroundLocal" +} + +// NewInputBackgroundLocal creates a new InputBackgroundLocal +// +// @param background Background file to use. Only inputFileLocal and inputFileGenerated are supported. The file must be in JPEG format for wallpapers and in PNG format for patterns +func NewInputBackgroundLocal(background InputFile) *InputBackgroundLocal { + inputBackgroundLocalTemp := InputBackgroundLocal{ + tdCommon: tdCommon{Type: "inputBackgroundLocal"}, + Background: background, + } + + return &inputBackgroundLocalTemp +} + +// UnmarshalJSON unmarshal to json +func (inputBackgroundLocal *InputBackgroundLocal) 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 + } + + inputBackgroundLocal.tdCommon = tempObj.tdCommon + + fieldBackground, _ := unmarshalInputFile(objMap["background"]) + inputBackgroundLocal.Background = fieldBackground + + return nil +} + +// GetInputBackgroundEnum return the enum type of this object +func (inputBackgroundLocal *InputBackgroundLocal) GetInputBackgroundEnum() InputBackgroundEnum { + return InputBackgroundLocalType +} + +// InputBackgroundRemote A background from the server +type InputBackgroundRemote struct { + tdCommon + BackgroundID JSONInt64 `json:"background_id"` // The background identifier +} + +// MessageType return the string telegram-type of InputBackgroundRemote +func (inputBackgroundRemote *InputBackgroundRemote) MessageType() string { + return "inputBackgroundRemote" +} + +// NewInputBackgroundRemote creates a new InputBackgroundRemote +// +// @param backgroundID The background identifier +func NewInputBackgroundRemote(backgroundID JSONInt64) *InputBackgroundRemote { + inputBackgroundRemoteTemp := InputBackgroundRemote{ + tdCommon: tdCommon{Type: "inputBackgroundRemote"}, + BackgroundID: backgroundID, + } + + return &inputBackgroundRemoteTemp +} + +// GetInputBackgroundEnum return the enum type of this object +func (inputBackgroundRemote *InputBackgroundRemote) GetInputBackgroundEnum() InputBackgroundEnum { + return InputBackgroundRemoteType +} diff --git a/tdlib/inputChatPhoto.go b/tdlib/inputChatPhoto.go new file mode 100644 index 0000000..3dd1775 --- /dev/null +++ b/tdlib/inputChatPhoto.go @@ -0,0 +1,190 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputChatPhoto Describes a photo to be set as a user profile or chat photo +type InputChatPhoto interface { + GetInputChatPhotoEnum() InputChatPhotoEnum +} + +// InputChatPhotoEnum Alias for abstract InputChatPhoto 'Sub-Classes', used as constant-enum here +type InputChatPhotoEnum string + +// InputChatPhoto enums +const ( + InputChatPhotoPreviousType InputChatPhotoEnum = "inputChatPhotoPrevious" + InputChatPhotoStaticType InputChatPhotoEnum = "inputChatPhotoStatic" + InputChatPhotoAnimationType InputChatPhotoEnum = "inputChatPhotoAnimation" +) + +func unmarshalInputChatPhoto(rawMsg *json.RawMessage) (InputChatPhoto, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputChatPhotoEnum(objMap["@type"].(string)) { + case InputChatPhotoPreviousType: + var inputChatPhotoPrevious InputChatPhotoPrevious + err := json.Unmarshal(*rawMsg, &inputChatPhotoPrevious) + return &inputChatPhotoPrevious, err + + case InputChatPhotoStaticType: + var inputChatPhotoStatic InputChatPhotoStatic + err := json.Unmarshal(*rawMsg, &inputChatPhotoStatic) + return &inputChatPhotoStatic, err + + case InputChatPhotoAnimationType: + var inputChatPhotoAnimation InputChatPhotoAnimation + err := json.Unmarshal(*rawMsg, &inputChatPhotoAnimation) + return &inputChatPhotoAnimation, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// InputChatPhotoPrevious A previously used profile photo of the current user +type InputChatPhotoPrevious struct { + tdCommon + ChatPhotoID JSONInt64 `json:"chat_photo_id"` // Identifier of the current user's profile photo to reuse +} + +// MessageType return the string telegram-type of InputChatPhotoPrevious +func (inputChatPhotoPrevious *InputChatPhotoPrevious) MessageType() string { + return "inputChatPhotoPrevious" +} + +// NewInputChatPhotoPrevious creates a new InputChatPhotoPrevious +// +// @param chatPhotoID Identifier of the current user's profile photo to reuse +func NewInputChatPhotoPrevious(chatPhotoID JSONInt64) *InputChatPhotoPrevious { + inputChatPhotoPreviousTemp := InputChatPhotoPrevious{ + tdCommon: tdCommon{Type: "inputChatPhotoPrevious"}, + ChatPhotoID: chatPhotoID, + } + + return &inputChatPhotoPreviousTemp +} + +// GetInputChatPhotoEnum return the enum type of this object +func (inputChatPhotoPrevious *InputChatPhotoPrevious) GetInputChatPhotoEnum() InputChatPhotoEnum { + return InputChatPhotoPreviousType +} + +// InputChatPhotoStatic A static photo in JPEG format +type InputChatPhotoStatic struct { + tdCommon + Photo InputFile `json:"photo"` // Photo to be set as profile photo. Only inputFileLocal and inputFileGenerated are allowed +} + +// MessageType return the string telegram-type of InputChatPhotoStatic +func (inputChatPhotoStatic *InputChatPhotoStatic) MessageType() string { + return "inputChatPhotoStatic" +} + +// NewInputChatPhotoStatic creates a new InputChatPhotoStatic +// +// @param photo Photo to be set as profile photo. Only inputFileLocal and inputFileGenerated are allowed +func NewInputChatPhotoStatic(photo InputFile) *InputChatPhotoStatic { + inputChatPhotoStaticTemp := InputChatPhotoStatic{ + tdCommon: tdCommon{Type: "inputChatPhotoStatic"}, + Photo: photo, + } + + return &inputChatPhotoStaticTemp +} + +// UnmarshalJSON unmarshal to json +func (inputChatPhotoStatic *InputChatPhotoStatic) 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 + } + + inputChatPhotoStatic.tdCommon = tempObj.tdCommon + + fieldPhoto, _ := unmarshalInputFile(objMap["photo"]) + inputChatPhotoStatic.Photo = fieldPhoto + + return nil +} + +// GetInputChatPhotoEnum return the enum type of this object +func (inputChatPhotoStatic *InputChatPhotoStatic) GetInputChatPhotoEnum() InputChatPhotoEnum { + return InputChatPhotoStaticType +} + +// InputChatPhotoAnimation An animation in MPEG4 format; must be square, at most 10 seconds long, have width between 160 and 800 and be at most 2MB in size +type InputChatPhotoAnimation struct { + tdCommon + Animation InputFile `json:"animation"` // Animation to be set as profile photo. Only inputFileLocal and inputFileGenerated are allowed + MainFrameTimestamp float64 `json:"main_frame_timestamp"` // Timestamp of the frame, which will be used as static chat photo +} + +// MessageType return the string telegram-type of InputChatPhotoAnimation +func (inputChatPhotoAnimation *InputChatPhotoAnimation) MessageType() string { + return "inputChatPhotoAnimation" +} + +// NewInputChatPhotoAnimation creates a new InputChatPhotoAnimation +// +// @param animation Animation to be set as profile photo. Only inputFileLocal and inputFileGenerated are allowed +// @param mainFrameTimestamp Timestamp of the frame, which will be used as static chat photo +func NewInputChatPhotoAnimation(animation InputFile, mainFrameTimestamp float64) *InputChatPhotoAnimation { + inputChatPhotoAnimationTemp := InputChatPhotoAnimation{ + tdCommon: tdCommon{Type: "inputChatPhotoAnimation"}, + Animation: animation, + MainFrameTimestamp: mainFrameTimestamp, + } + + return &inputChatPhotoAnimationTemp +} + +// UnmarshalJSON unmarshal to json +func (inputChatPhotoAnimation *InputChatPhotoAnimation) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + MainFrameTimestamp float64 `json:"main_frame_timestamp"` // Timestamp of the frame, which will be used as static chat photo + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputChatPhotoAnimation.tdCommon = tempObj.tdCommon + inputChatPhotoAnimation.MainFrameTimestamp = tempObj.MainFrameTimestamp + + fieldAnimation, _ := unmarshalInputFile(objMap["animation"]) + inputChatPhotoAnimation.Animation = fieldAnimation + + return nil +} + +// GetInputChatPhotoEnum return the enum type of this object +func (inputChatPhotoAnimation *InputChatPhotoAnimation) GetInputChatPhotoEnum() InputChatPhotoEnum { + return InputChatPhotoAnimationType +} diff --git a/tdlib/inputCredentials.go b/tdlib/inputCredentials.go new file mode 100644 index 0000000..3a894f8 --- /dev/null +++ b/tdlib/inputCredentials.go @@ -0,0 +1,176 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputCredentials Contains information about the payment method chosen by the user +type InputCredentials interface { + GetInputCredentialsEnum() InputCredentialsEnum +} + +// InputCredentialsEnum Alias for abstract InputCredentials 'Sub-Classes', used as constant-enum here +type InputCredentialsEnum string + +// InputCredentials enums +const ( + InputCredentialsSavedType InputCredentialsEnum = "inputCredentialsSaved" + InputCredentialsNewType InputCredentialsEnum = "inputCredentialsNew" + InputCredentialsApplePayType InputCredentialsEnum = "inputCredentialsApplePay" + InputCredentialsGooglePayType InputCredentialsEnum = "inputCredentialsGooglePay" +) + +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 InputCredentialsApplePayType: + var inputCredentialsApplePay InputCredentialsApplePay + err := json.Unmarshal(*rawMsg, &inputCredentialsApplePay) + return &inputCredentialsApplePay, err + + case InputCredentialsGooglePayType: + var inputCredentialsGooglePay InputCredentialsGooglePay + err := json.Unmarshal(*rawMsg, &inputCredentialsGooglePay) + return &inputCredentialsGooglePay, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 +} + +// 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 +} + +// InputCredentialsGooglePay Applies if a user enters new credentials using Google Pay +type InputCredentialsGooglePay struct { + tdCommon + Data string `json:"data"` // JSON-encoded data with the credential identifier +} + +// MessageType return the string telegram-type of InputCredentialsGooglePay +func (inputCredentialsGooglePay *InputCredentialsGooglePay) MessageType() string { + return "inputCredentialsGooglePay" +} + +// NewInputCredentialsGooglePay creates a new InputCredentialsGooglePay +// +// @param data JSON-encoded data with the credential identifier +func NewInputCredentialsGooglePay(data string) *InputCredentialsGooglePay { + inputCredentialsGooglePayTemp := InputCredentialsGooglePay{ + tdCommon: tdCommon{Type: "inputCredentialsGooglePay"}, + Data: data, + } + + return &inputCredentialsGooglePayTemp +} + +// GetInputCredentialsEnum return the enum type of this object +func (inputCredentialsGooglePay *InputCredentialsGooglePay) GetInputCredentialsEnum() InputCredentialsEnum { + return InputCredentialsGooglePayType +} diff --git a/tdlib/inputFile.go b/tdlib/inputFile.go new file mode 100644 index 0000000..a300ebb --- /dev/null +++ b/tdlib/inputFile.go @@ -0,0 +1,179 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputFile Points to a file +type InputFile interface { + GetInputFileEnum() InputFileEnum +} + +// 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" +) + +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)) + } +} + +// 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. The remote ID is guaranteed to be usable only if the corresponding file is still accessible to the user and known to TDLib. For example, if the file is from a message, then the message must be not deleted and accessible to the user. If the file database is disabled, then the corresponding object with the file must be preloaded by the application +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 application +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. Conversions beginning with '#' are reserved for internal TDLib usage + ExpectedSize int32 `json:"expected_size"` // Expected size of the generated file, in bytes; 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. Conversions beginning with '#' are reserved for internal TDLib usage +// @param expectedSize Expected size of the generated file, in bytes; 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 +} diff --git a/tdlib/inputIDentityDocument.go b/tdlib/inputIDentityDocument.go new file mode 100644 index 0000000..6bcb7fa --- /dev/null +++ b/tdlib/inputIDentityDocument.go @@ -0,0 +1,80 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/inputInlineQueryResult.go b/tdlib/inputInlineQueryResult.go new file mode 100644 index 0000000..2d0a8b9 --- /dev/null +++ b/tdlib/inputInlineQueryResult.go @@ -0,0 +1,1169 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputInlineQueryResult Represents a single result of an inline query; for bots only +type InputInlineQueryResult interface { + GetInputInlineQueryResultEnum() InputInlineQueryResultEnum +} + +// InputInlineQueryResultEnum Alias for abstract InputInlineQueryResult 'Sub-Classes', used as constant-enum here +type InputInlineQueryResultEnum string + +// InputInlineQueryResult enums +const ( + InputInlineQueryResultAnimationType InputInlineQueryResultEnum = "inputInlineQueryResultAnimation" + 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" +) + +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 InputInlineQueryResultAnimationType: + var inputInlineQueryResultAnimation InputInlineQueryResultAnimation + err := json.Unmarshal(*rawMsg, &inputInlineQueryResultAnimation) + return &inputInlineQueryResultAnimation, 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)) + } +} + +// InputInlineQueryResultAnimation Represents a link to an animated GIF or an animated (i.e. without sound) H.264/MPEG-4 AVC video +type InputInlineQueryResultAnimation 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 result thumbnail (JPEG, GIF, or MPEG4), if it exists + ThumbnailMimeType string `json:"thumbnail_mime_type"` // MIME type of the video thumbnail. If non-empty, must be one of "image/jpeg", "image/gif" and "video/mp4" + VideoURL string `json:"video_url"` // The URL of the video file (file size must not exceed 1MB) + VideoMimeType string `json:"video_mime_type"` // MIME type of the video file. Must be one of "image/gif" and "video/mp4" + VideoDuration int32 `json:"video_duration"` // Duration of the video, in seconds + VideoWidth int32 `json:"video_width"` // Width of the video + VideoHeight int32 `json:"video_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, inputMessageInvoice, inputMessageLocation, inputMessageVenue or inputMessageContact +} + +// MessageType return the string telegram-type of InputInlineQueryResultAnimation +func (inputInlineQueryResultAnimation *InputInlineQueryResultAnimation) MessageType() string { + return "inputInlineQueryResultAnimation" +} + +// NewInputInlineQueryResultAnimation creates a new InputInlineQueryResultAnimation +// +// @param iD Unique identifier of the query result +// @param title Title of the query result +// @param thumbnailURL URL of the result thumbnail (JPEG, GIF, or MPEG4), if it exists +// @param thumbnailMimeType MIME type of the video thumbnail. If non-empty, must be one of "image/jpeg", "image/gif" and "video/mp4" +// @param videoURL The URL of the video file (file size must not exceed 1MB) +// @param videoMimeType MIME type of the video file. Must be one of "image/gif" and "video/mp4" +// @param videoDuration Duration of the video, in seconds +// @param videoWidth Width of the video +// @param videoHeight 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, inputMessageInvoice, inputMessageLocation, inputMessageVenue or inputMessageContact +func NewInputInlineQueryResultAnimation(iD string, title string, thumbnailURL string, thumbnailMimeType string, videoURL string, videoMimeType string, videoDuration int32, videoWidth int32, videoHeight int32, replyMarkup ReplyMarkup, inputMessageContent InputMessageContent) *InputInlineQueryResultAnimation { + inputInlineQueryResultAnimationTemp := InputInlineQueryResultAnimation{ + tdCommon: tdCommon{Type: "inputInlineQueryResultAnimation"}, + ID: iD, + Title: title, + ThumbnailURL: thumbnailURL, + ThumbnailMimeType: thumbnailMimeType, + VideoURL: videoURL, + VideoMimeType: videoMimeType, + VideoDuration: videoDuration, + VideoWidth: videoWidth, + VideoHeight: videoHeight, + ReplyMarkup: replyMarkup, + InputMessageContent: inputMessageContent, + } + + return &inputInlineQueryResultAnimationTemp +} + +// UnmarshalJSON unmarshal to json +func (inputInlineQueryResultAnimation *InputInlineQueryResultAnimation) 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 result thumbnail (JPEG, GIF, or MPEG4), if it exists + ThumbnailMimeType string `json:"thumbnail_mime_type"` // MIME type of the video thumbnail. If non-empty, must be one of "image/jpeg", "image/gif" and "video/mp4" + VideoURL string `json:"video_url"` // The URL of the video file (file size must not exceed 1MB) + VideoMimeType string `json:"video_mime_type"` // MIME type of the video file. Must be one of "image/gif" and "video/mp4" + VideoDuration int32 `json:"video_duration"` // Duration of the video, in seconds + VideoWidth int32 `json:"video_width"` // Width of the video + VideoHeight int32 `json:"video_height"` // Height of the video + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputInlineQueryResultAnimation.tdCommon = tempObj.tdCommon + inputInlineQueryResultAnimation.ID = tempObj.ID + inputInlineQueryResultAnimation.Title = tempObj.Title + inputInlineQueryResultAnimation.ThumbnailURL = tempObj.ThumbnailURL + inputInlineQueryResultAnimation.ThumbnailMimeType = tempObj.ThumbnailMimeType + inputInlineQueryResultAnimation.VideoURL = tempObj.VideoURL + inputInlineQueryResultAnimation.VideoMimeType = tempObj.VideoMimeType + inputInlineQueryResultAnimation.VideoDuration = tempObj.VideoDuration + inputInlineQueryResultAnimation.VideoWidth = tempObj.VideoWidth + inputInlineQueryResultAnimation.VideoHeight = tempObj.VideoHeight + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + inputInlineQueryResultAnimation.ReplyMarkup = fieldReplyMarkup + + fieldInputMessageContent, _ := unmarshalInputMessageContent(objMap["input_message_content"]) + inputInlineQueryResultAnimation.InputMessageContent = fieldInputMessageContent + + return nil +} + +// GetInputInlineQueryResultEnum return the enum type of this object +func (inputInlineQueryResultAnimation *InputInlineQueryResultAnimation) GetInputInlineQueryResultEnum() InputInlineQueryResultEnum { + return InputInlineQueryResultAnimationType +} + +// 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"` // A short description 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, inputMessageInvoice, 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 A short description 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, inputMessageInvoice, 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"` // A short description 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 + } + + 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, inputMessageInvoice, 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, inputMessageInvoice, 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, inputMessageInvoice, 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, inputMessageInvoice, 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"` // Short description of the result, if known + 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, inputMessageInvoice, 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 Short description of the result, if known +// @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, inputMessageInvoice, 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"` // Short description of the result, if known + 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, inputMessageInvoice, 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, inputMessageInvoice, 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"` // A short description of the result, if known + 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, inputMessageInvoice, 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 A short description of the result, if known +// @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, inputMessageInvoice, 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"` // A short description of the result, if known + 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 or TGS 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 or TGS 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, inputMessageInvoice, 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 or TGS 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, inputMessageInvoice, 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 or TGS 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, inputMessageInvoice, 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, inputMessageInvoice, 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"` // A short description of the result, if known + 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, inputMessageInvoice, 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 A short description of the result, if known +// @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, inputMessageInvoice, 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"` // A short description of the result, if known + 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, inputMessageInvoice, 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, inputMessageInvoice, 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 +} diff --git a/tdlib/inputMessageContent.go b/tdlib/inputMessageContent.go new file mode 100644 index 0000000..0001e85 --- /dev/null +++ b/tdlib/inputMessageContent.go @@ -0,0 +1,1102 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputMessageContent The content of a message to send +type InputMessageContent interface { + GetInputMessageContentEnum() InputMessageContentEnum +} + +// 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" + InputMessageDiceType InputMessageContentEnum = "inputMessageDice" + InputMessageGameType InputMessageContentEnum = "inputMessageGame" + InputMessageInvoiceType InputMessageContentEnum = "inputMessageInvoice" + InputMessagePollType InputMessageContentEnum = "inputMessagePoll" + InputMessageForwardedType InputMessageContentEnum = "inputMessageForwarded" +) + +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 InputMessageDiceType: + var inputMessageDice InputMessageDice + err := json.Unmarshal(*rawMsg, &inputMessageDice) + return &inputMessageDice, 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 InputMessagePollType: + var inputMessagePoll InputMessagePoll + err := json.Unmarshal(*rawMsg, &inputMessagePoll) + return &inputMessagePoll, 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)) + } +} + +// 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, Underline, Strikethrough, Code, Pre, PreCode, TextUrl and MentionName 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, Underline, Strikethrough, Code, Pre, PreCode, TextUrl and MentionName 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 + AddedStickerFileIDs []int32 `json:"added_sticker_file_ids"` // File identifiers of the stickers added to the animation, if applicable + 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 addedStickerFileIDs File identifiers of the stickers added to the animation, if applicable +// @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, addedStickerFileIDs []int32, duration int32, width int32, height int32, caption *FormattedText) *InputMessageAnimation { + inputMessageAnimationTemp := InputMessageAnimation{ + tdCommon: tdCommon{Type: "inputMessageAnimation"}, + Animation: animation, + Thumbnail: thumbnail, + AddedStickerFileIDs: addedStickerFileIDs, + 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 + AddedStickerFileIDs []int32 `json:"added_sticker_file_ids"` // File identifiers of the stickers added to the animation, if applicable + 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.AddedStickerFileIDs = tempObj.AddedStickerFileIDs + 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 + DisableContentTypeDetection bool `json:"disable_content_type_detection"` // If true, automatic file type detection will be disabled and the document will be always sent as file. Always true for files sent to secret chats + 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 disableContentTypeDetection If true, automatic file type detection will be disabled and the document will be always sent as file. Always true for files sent to secret chats +// @param caption Document caption; 0-GetOption("message_caption_length_max") characters +func NewInputMessageDocument(document InputFile, thumbnail *InputThumbnail, disableContentTypeDetection bool, caption *FormattedText) *InputMessageDocument { + inputMessageDocumentTemp := InputMessageDocument{ + tdCommon: tdCommon{Type: "inputMessageDocument"}, + Document: document, + Thumbnail: thumbnail, + DisableContentTypeDetection: disableContentTypeDetection, + 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 + DisableContentTypeDetection bool `json:"disable_content_type_detection"` // If true, automatic file type detection will be disabled and the document will be always sent as file. Always true for files sent to secret chats + 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.DisableContentTypeDetection = tempObj.DisableContentTypeDetection + 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 + Emoji string `json:"emoji"` // Emoji used to choose the sticker +} + +// 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 +// @param emoji Emoji used to choose the sticker +func NewInputMessageSticker(sticker InputFile, thumbnail *InputThumbnail, width int32, height int32, emoji string) *InputMessageSticker { + inputMessageStickerTemp := InputMessageSticker{ + tdCommon: tdCommon{Type: "inputMessageSticker"}, + Sticker: sticker, + Thumbnail: thumbnail, + Width: width, + Height: height, + Emoji: emoji, + } + + 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 + Emoji string `json:"emoji"` // Emoji used to choose the sticker + }{} + 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 + inputMessageSticker.Emoji = tempObj.Emoji + + 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 be between 60 and 86400 for a live location and 0 otherwise + Heading int32 `json:"heading"` // For live locations, a direction in which the location moves, in degrees; 1-360. Pass 0 if unknown + ProximityAlertRadius int32 `json:"proximity_alert_radius"` // For live locations, a maximum distance to another chat member for proximity alerts, in meters (0-100000). Pass 0 if the notification is disabled. Can't be enabled in channels and Saved Messages +} + +// 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 be between 60 and 86400 for a live location and 0 otherwise +// @param heading For live locations, a direction in which the location moves, in degrees; 1-360. Pass 0 if unknown +// @param proximityAlertRadius For live locations, a maximum distance to another chat member for proximity alerts, in meters (0-100000). Pass 0 if the notification is disabled. Can't be enabled in channels and Saved Messages +func NewInputMessageLocation(location *Location, livePeriod int32, heading int32, proximityAlertRadius int32) *InputMessageLocation { + inputMessageLocationTemp := InputMessageLocation{ + tdCommon: tdCommon{Type: "inputMessageLocation"}, + Location: location, + LivePeriod: livePeriod, + Heading: heading, + ProximityAlertRadius: proximityAlertRadius, + } + + 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 +} + +// InputMessageDice A dice message +type InputMessageDice struct { + tdCommon + Emoji string `json:"emoji"` // Emoji on which the dice throw animation is based + ClearDraft bool `json:"clear_draft"` // True, if a chat message draft should be deleted +} + +// MessageType return the string telegram-type of InputMessageDice +func (inputMessageDice *InputMessageDice) MessageType() string { + return "inputMessageDice" +} + +// NewInputMessageDice creates a new InputMessageDice +// +// @param emoji Emoji on which the dice throw animation is based +// @param clearDraft True, if a chat message draft should be deleted +func NewInputMessageDice(emoji string, clearDraft bool) *InputMessageDice { + inputMessageDiceTemp := InputMessageDice{ + tdCommon: tdCommon{Type: "inputMessageDice"}, + Emoji: emoji, + ClearDraft: clearDraft, + } + + return &inputMessageDiceTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageDice *InputMessageDice) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageDiceType +} + +// InputMessageGame A message with a game; not supported for channels or secret chats +type InputMessageGame struct { + tdCommon + BotUserID int64 `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 int64, 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 +type InputMessageInvoice struct { + tdCommon + Invoice *Invoice `json:"invoice"` // Invoice + Title string `json:"title"` // Product title; 1-32 characters + Description string `json:"description"` // Product description; 0-255 characters + 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 deep link parameter for the generation of this invoice. If empty, it would be possible to pay directly from forwards of the invoice message +} + +// 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 Product description; 0-255 characters +// @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 deep link parameter for the generation of this invoice. If empty, it would be possible to pay directly from forwards of the invoice message +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 +} + +// InputMessagePoll A message with a poll. Polls can't be sent to secret chats. Polls can be sent only to a private chat with a bot +type InputMessagePoll struct { + tdCommon + Question string `json:"question"` // Poll question; 1-255 characters (up to 300 characters for bots) + Options []string `json:"options"` // List of poll answer options, 2-10 strings 1-100 characters each + IsAnonymous bool `json:"is_anonymous"` // True, if the poll voters are anonymous. Non-anonymous polls can't be sent or forwarded to channels + Type PollType `json:"type"` // Type of the poll + OpenPeriod int32 `json:"open_period"` // Amount of time the poll will be active after creation, in seconds; for bots only + CloseDate int32 `json:"close_date"` // Point in time (Unix timestamp) when the poll will be automatically closed; for bots only + IsClosed bool `json:"is_closed"` // True, if the poll needs to be sent already closed; for bots only +} + +// MessageType return the string telegram-type of InputMessagePoll +func (inputMessagePoll *InputMessagePoll) MessageType() string { + return "inputMessagePoll" +} + +// NewInputMessagePoll creates a new InputMessagePoll +// +// @param question Poll question; 1-255 characters (up to 300 characters for bots) +// @param options List of poll answer options, 2-10 strings 1-100 characters each +// @param isAnonymous True, if the poll voters are anonymous. Non-anonymous polls can't be sent or forwarded to channels +// @param typeParam Type of the poll +// @param openPeriod Amount of time the poll will be active after creation, in seconds; for bots only +// @param closeDate Point in time (Unix timestamp) when the poll will be automatically closed; for bots only +// @param isClosed True, if the poll needs to be sent already closed; for bots only +func NewInputMessagePoll(question string, options []string, isAnonymous bool, typeParam PollType, openPeriod int32, closeDate int32, isClosed bool) *InputMessagePoll { + inputMessagePollTemp := InputMessagePoll{ + tdCommon: tdCommon{Type: "inputMessagePoll"}, + Question: question, + Options: options, + IsAnonymous: isAnonymous, + Type: typeParam, + OpenPeriod: openPeriod, + CloseDate: closeDate, + IsClosed: isClosed, + } + + return &inputMessagePollTemp +} + +// UnmarshalJSON unmarshal to json +func (inputMessagePoll *InputMessagePoll) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Question string `json:"question"` // Poll question; 1-255 characters (up to 300 characters for bots) + Options []string `json:"options"` // List of poll answer options, 2-10 strings 1-100 characters each + IsAnonymous bool `json:"is_anonymous"` // True, if the poll voters are anonymous. Non-anonymous polls can't be sent or forwarded to channels + OpenPeriod int32 `json:"open_period"` // Amount of time the poll will be active after creation, in seconds; for bots only + CloseDate int32 `json:"close_date"` // Point in time (Unix timestamp) when the poll will be automatically closed; for bots only + IsClosed bool `json:"is_closed"` // True, if the poll needs to be sent already closed; for bots only + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputMessagePoll.tdCommon = tempObj.tdCommon + inputMessagePoll.Question = tempObj.Question + inputMessagePoll.Options = tempObj.Options + inputMessagePoll.IsAnonymous = tempObj.IsAnonymous + inputMessagePoll.OpenPeriod = tempObj.OpenPeriod + inputMessagePoll.CloseDate = tempObj.CloseDate + inputMessagePoll.IsClosed = tempObj.IsClosed + + fieldType, _ := unmarshalPollType(objMap["type"]) + inputMessagePoll.Type = fieldType + + return nil +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessagePoll *InputMessagePoll) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessagePollType +} + +// 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 + CopyOptions *MessageCopyOptions `json:"copy_options"` // Options to be used to copy content of the message without a link to the original message +} + +// 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 +// @param copyOptions Options to be used to copy content of the message without a link to the original message +func NewInputMessageForwarded(fromChatID int64, messageID int64, inGameShare bool, copyOptions *MessageCopyOptions) *InputMessageForwarded { + inputMessageForwardedTemp := InputMessageForwarded{ + tdCommon: tdCommon{Type: "inputMessageForwarded"}, + FromChatID: fromChatID, + MessageID: messageID, + InGameShare: inGameShare, + CopyOptions: copyOptions, + } + + return &inputMessageForwardedTemp +} + +// GetInputMessageContentEnum return the enum type of this object +func (inputMessageForwarded *InputMessageForwarded) GetInputMessageContentEnum() InputMessageContentEnum { + return InputMessageForwardedType +} diff --git a/tdlib/inputPassportElement.go b/tdlib/inputPassportElement.go new file mode 100644 index 0000000..84a1a7f --- /dev/null +++ b/tdlib/inputPassportElement.go @@ -0,0 +1,479 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputPassportElement Contains information about a Telegram Passport element to be saved +type InputPassportElement interface { + GetInputPassportElementEnum() InputPassportElementEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/inputPassportElementError.go b/tdlib/inputPassportElementError.go new file mode 100644 index 0000000..1dd1c1a --- /dev/null +++ b/tdlib/inputPassportElementError.go @@ -0,0 +1,65 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/inputPassportElementErrorSource.go b/tdlib/inputPassportElementErrorSource.go new file mode 100644 index 0000000..f2e73d2 --- /dev/null +++ b/tdlib/inputPassportElementErrorSource.go @@ -0,0 +1,346 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputPassportElementErrorSource Contains the description of an error in a Telegram Passport element; for bots only +type InputPassportElementErrorSource interface { + GetInputPassportElementErrorSourceEnum() InputPassportElementErrorSourceEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/inputPersonalDocument.go b/tdlib/inputPersonalDocument.go new file mode 100644 index 0000000..a35c3a8 --- /dev/null +++ b/tdlib/inputPersonalDocument.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/inputSticker.go b/tdlib/inputSticker.go new file mode 100644 index 0000000..375fa0f --- /dev/null +++ b/tdlib/inputSticker.go @@ -0,0 +1,166 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InputSticker Describes a sticker that needs to be added to a sticker set +type InputSticker interface { + GetInputStickerEnum() InputStickerEnum +} + +// InputStickerEnum Alias for abstract InputSticker 'Sub-Classes', used as constant-enum here +type InputStickerEnum string + +// InputSticker enums +const ( + InputStickerStaticType InputStickerEnum = "inputStickerStatic" + InputStickerAnimatedType InputStickerEnum = "inputStickerAnimated" +) + +func unmarshalInputSticker(rawMsg *json.RawMessage) (InputSticker, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InputStickerEnum(objMap["@type"].(string)) { + case InputStickerStaticType: + var inputStickerStatic InputStickerStatic + err := json.Unmarshal(*rawMsg, &inputStickerStatic) + return &inputStickerStatic, err + + case InputStickerAnimatedType: + var inputStickerAnimated InputStickerAnimated + err := json.Unmarshal(*rawMsg, &inputStickerAnimated) + return &inputStickerAnimated, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// InputStickerStatic A static sticker in PNG format, which will be converted to WEBP server-side +type InputStickerStatic struct { + tdCommon + Sticker InputFile `json:"sticker"` // PNG image with the sticker; must be up to 512 KB in size and fit in a 512x512 square + Emojis string `json:"emojis"` // Emojis 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 InputStickerStatic +func (inputStickerStatic *InputStickerStatic) MessageType() string { + return "inputStickerStatic" +} + +// NewInputStickerStatic creates a new InputStickerStatic +// +// @param sticker PNG image with the sticker; must be up to 512 KB in size and fit in a 512x512 square +// @param emojis Emojis corresponding to the sticker +// @param maskPosition For masks, position where the mask should be placed; may be null +func NewInputStickerStatic(sticker InputFile, emojis string, maskPosition *MaskPosition) *InputStickerStatic { + inputStickerStaticTemp := InputStickerStatic{ + tdCommon: tdCommon{Type: "inputStickerStatic"}, + Sticker: sticker, + Emojis: emojis, + MaskPosition: maskPosition, + } + + return &inputStickerStaticTemp +} + +// UnmarshalJSON unmarshal to json +func (inputStickerStatic *InputStickerStatic) 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"` // Emojis 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 + } + + inputStickerStatic.tdCommon = tempObj.tdCommon + inputStickerStatic.Emojis = tempObj.Emojis + inputStickerStatic.MaskPosition = tempObj.MaskPosition + + fieldSticker, _ := unmarshalInputFile(objMap["sticker"]) + inputStickerStatic.Sticker = fieldSticker + + return nil +} + +// GetInputStickerEnum return the enum type of this object +func (inputStickerStatic *InputStickerStatic) GetInputStickerEnum() InputStickerEnum { + return InputStickerStaticType +} + +// InputStickerAnimated An animated sticker in TGS format +type InputStickerAnimated struct { + tdCommon + Sticker InputFile `json:"sticker"` // File with the animated sticker. Only local or uploaded within a week files are supported. See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements + Emojis string `json:"emojis"` // Emojis corresponding to the sticker +} + +// MessageType return the string telegram-type of InputStickerAnimated +func (inputStickerAnimated *InputStickerAnimated) MessageType() string { + return "inputStickerAnimated" +} + +// NewInputStickerAnimated creates a new InputStickerAnimated +// +// @param sticker File with the animated sticker. Only local or uploaded within a week files are supported. See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements +// @param emojis Emojis corresponding to the sticker +func NewInputStickerAnimated(sticker InputFile, emojis string) *InputStickerAnimated { + inputStickerAnimatedTemp := InputStickerAnimated{ + tdCommon: tdCommon{Type: "inputStickerAnimated"}, + Sticker: sticker, + Emojis: emojis, + } + + return &inputStickerAnimatedTemp +} + +// UnmarshalJSON unmarshal to json +func (inputStickerAnimated *InputStickerAnimated) 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"` // Emojis corresponding to the sticker + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + inputStickerAnimated.tdCommon = tempObj.tdCommon + inputStickerAnimated.Emojis = tempObj.Emojis + + fieldSticker, _ := unmarshalInputFile(objMap["sticker"]) + inputStickerAnimated.Sticker = fieldSticker + + return nil +} + +// GetInputStickerEnum return the enum type of this object +func (inputStickerAnimated *InputStickerAnimated) GetInputStickerEnum() InputStickerEnum { + return InputStickerAnimatedType +} diff --git a/tdlib/inputThumbnail.go b/tdlib/inputThumbnail.go new file mode 100644 index 0000000..e4cc6f8 --- /dev/null +++ b/tdlib/inputThumbnail.go @@ -0,0 +1,63 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// InputThumbnail A thumbnail to be sent along with a file; must 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 320. Use 0 if unknown + Height int32 `json:"height"` // Thumbnail height, usually shouldn't exceed 320. 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 320. Use 0 if unknown +// @param height Thumbnail height, usually shouldn't exceed 320. 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 320. Use 0 if unknown + Height int32 `json:"height"` // Thumbnail height, usually shouldn't exceed 320. 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 +} diff --git a/tdlib/internalLinkType.go b/tdlib/internalLinkType.go new file mode 100644 index 0000000..5971fd5 --- /dev/null +++ b/tdlib/internalLinkType.go @@ -0,0 +1,868 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// InternalLinkType Describes an internal https://t.me or tg: link, which must be processed by the app in a special way +type InternalLinkType interface { + GetInternalLinkTypeEnum() InternalLinkTypeEnum +} + +// InternalLinkTypeEnum Alias for abstract InternalLinkType 'Sub-Classes', used as constant-enum here +type InternalLinkTypeEnum string + +// InternalLinkType enums +const ( + InternalLinkTypeActiveSessionsType InternalLinkTypeEnum = "internalLinkTypeActiveSessions" + InternalLinkTypeAuthenticationCodeType InternalLinkTypeEnum = "internalLinkTypeAuthenticationCode" + InternalLinkTypeBackgroundType InternalLinkTypeEnum = "internalLinkTypeBackground" + InternalLinkTypeBotStartType InternalLinkTypeEnum = "internalLinkTypeBotStart" + InternalLinkTypeBotStartInGroupType InternalLinkTypeEnum = "internalLinkTypeBotStartInGroup" + InternalLinkTypeChangePhoneNumberType InternalLinkTypeEnum = "internalLinkTypeChangePhoneNumber" + InternalLinkTypeChatInviteType InternalLinkTypeEnum = "internalLinkTypeChatInvite" + InternalLinkTypeFilterSettingsType InternalLinkTypeEnum = "internalLinkTypeFilterSettings" + InternalLinkTypeGameType InternalLinkTypeEnum = "internalLinkTypeGame" + InternalLinkTypeLanguagePackType InternalLinkTypeEnum = "internalLinkTypeLanguagePack" + InternalLinkTypeMessageType InternalLinkTypeEnum = "internalLinkTypeMessage" + InternalLinkTypeMessageDraftType InternalLinkTypeEnum = "internalLinkTypeMessageDraft" + InternalLinkTypePassportDataRequestType InternalLinkTypeEnum = "internalLinkTypePassportDataRequest" + InternalLinkTypePhoneNumberConfirmationType InternalLinkTypeEnum = "internalLinkTypePhoneNumberConfirmation" + InternalLinkTypeProxyType InternalLinkTypeEnum = "internalLinkTypeProxy" + InternalLinkTypePublicChatType InternalLinkTypeEnum = "internalLinkTypePublicChat" + InternalLinkTypeQrCodeAuthenticationType InternalLinkTypeEnum = "internalLinkTypeQrCodeAuthentication" + InternalLinkTypeSettingsType InternalLinkTypeEnum = "internalLinkTypeSettings" + InternalLinkTypeStickerSetType InternalLinkTypeEnum = "internalLinkTypeStickerSet" + InternalLinkTypeThemeType InternalLinkTypeEnum = "internalLinkTypeTheme" + InternalLinkTypeThemeSettingsType InternalLinkTypeEnum = "internalLinkTypeThemeSettings" + InternalLinkTypeUnknownDeepLinkType InternalLinkTypeEnum = "internalLinkTypeUnknownDeepLink" + InternalLinkTypeVoiceChatType InternalLinkTypeEnum = "internalLinkTypeVoiceChat" +) + +func unmarshalInternalLinkType(rawMsg *json.RawMessage) (InternalLinkType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch InternalLinkTypeEnum(objMap["@type"].(string)) { + case InternalLinkTypeActiveSessionsType: + var internalLinkTypeActiveSessions InternalLinkTypeActiveSessions + err := json.Unmarshal(*rawMsg, &internalLinkTypeActiveSessions) + return &internalLinkTypeActiveSessions, err + + case InternalLinkTypeAuthenticationCodeType: + var internalLinkTypeAuthenticationCode InternalLinkTypeAuthenticationCode + err := json.Unmarshal(*rawMsg, &internalLinkTypeAuthenticationCode) + return &internalLinkTypeAuthenticationCode, err + + case InternalLinkTypeBackgroundType: + var internalLinkTypeBackground InternalLinkTypeBackground + err := json.Unmarshal(*rawMsg, &internalLinkTypeBackground) + return &internalLinkTypeBackground, err + + case InternalLinkTypeBotStartType: + var internalLinkTypeBotStart InternalLinkTypeBotStart + err := json.Unmarshal(*rawMsg, &internalLinkTypeBotStart) + return &internalLinkTypeBotStart, err + + case InternalLinkTypeBotStartInGroupType: + var internalLinkTypeBotStartInGroup InternalLinkTypeBotStartInGroup + err := json.Unmarshal(*rawMsg, &internalLinkTypeBotStartInGroup) + return &internalLinkTypeBotStartInGroup, err + + case InternalLinkTypeChangePhoneNumberType: + var internalLinkTypeChangePhoneNumber InternalLinkTypeChangePhoneNumber + err := json.Unmarshal(*rawMsg, &internalLinkTypeChangePhoneNumber) + return &internalLinkTypeChangePhoneNumber, err + + case InternalLinkTypeChatInviteType: + var internalLinkTypeChatInvite InternalLinkTypeChatInvite + err := json.Unmarshal(*rawMsg, &internalLinkTypeChatInvite) + return &internalLinkTypeChatInvite, err + + case InternalLinkTypeFilterSettingsType: + var internalLinkTypeFilterSettings InternalLinkTypeFilterSettings + err := json.Unmarshal(*rawMsg, &internalLinkTypeFilterSettings) + return &internalLinkTypeFilterSettings, err + + case InternalLinkTypeGameType: + var internalLinkTypeGame InternalLinkTypeGame + err := json.Unmarshal(*rawMsg, &internalLinkTypeGame) + return &internalLinkTypeGame, err + + case InternalLinkTypeLanguagePackType: + var internalLinkTypeLanguagePack InternalLinkTypeLanguagePack + err := json.Unmarshal(*rawMsg, &internalLinkTypeLanguagePack) + return &internalLinkTypeLanguagePack, err + + case InternalLinkTypeMessageType: + var internalLinkTypeMessage InternalLinkTypeMessage + err := json.Unmarshal(*rawMsg, &internalLinkTypeMessage) + return &internalLinkTypeMessage, err + + case InternalLinkTypeMessageDraftType: + var internalLinkTypeMessageDraft InternalLinkTypeMessageDraft + err := json.Unmarshal(*rawMsg, &internalLinkTypeMessageDraft) + return &internalLinkTypeMessageDraft, err + + case InternalLinkTypePassportDataRequestType: + var internalLinkTypePassportDataRequest InternalLinkTypePassportDataRequest + err := json.Unmarshal(*rawMsg, &internalLinkTypePassportDataRequest) + return &internalLinkTypePassportDataRequest, err + + case InternalLinkTypePhoneNumberConfirmationType: + var internalLinkTypePhoneNumberConfirmation InternalLinkTypePhoneNumberConfirmation + err := json.Unmarshal(*rawMsg, &internalLinkTypePhoneNumberConfirmation) + return &internalLinkTypePhoneNumberConfirmation, err + + case InternalLinkTypeProxyType: + var internalLinkTypeProxy InternalLinkTypeProxy + err := json.Unmarshal(*rawMsg, &internalLinkTypeProxy) + return &internalLinkTypeProxy, err + + case InternalLinkTypePublicChatType: + var internalLinkTypePublicChat InternalLinkTypePublicChat + err := json.Unmarshal(*rawMsg, &internalLinkTypePublicChat) + return &internalLinkTypePublicChat, err + + case InternalLinkTypeQrCodeAuthenticationType: + var internalLinkTypeQrCodeAuthentication InternalLinkTypeQrCodeAuthentication + err := json.Unmarshal(*rawMsg, &internalLinkTypeQrCodeAuthentication) + return &internalLinkTypeQrCodeAuthentication, err + + case InternalLinkTypeSettingsType: + var internalLinkTypeSettings InternalLinkTypeSettings + err := json.Unmarshal(*rawMsg, &internalLinkTypeSettings) + return &internalLinkTypeSettings, err + + case InternalLinkTypeStickerSetType: + var internalLinkTypeStickerSet InternalLinkTypeStickerSet + err := json.Unmarshal(*rawMsg, &internalLinkTypeStickerSet) + return &internalLinkTypeStickerSet, err + + case InternalLinkTypeThemeType: + var internalLinkTypeTheme InternalLinkTypeTheme + err := json.Unmarshal(*rawMsg, &internalLinkTypeTheme) + return &internalLinkTypeTheme, err + + case InternalLinkTypeThemeSettingsType: + var internalLinkTypeThemeSettings InternalLinkTypeThemeSettings + err := json.Unmarshal(*rawMsg, &internalLinkTypeThemeSettings) + return &internalLinkTypeThemeSettings, err + + case InternalLinkTypeUnknownDeepLinkType: + var internalLinkTypeUnknownDeepLink InternalLinkTypeUnknownDeepLink + err := json.Unmarshal(*rawMsg, &internalLinkTypeUnknownDeepLink) + return &internalLinkTypeUnknownDeepLink, err + + case InternalLinkTypeVoiceChatType: + var internalLinkTypeVoiceChat InternalLinkTypeVoiceChat + err := json.Unmarshal(*rawMsg, &internalLinkTypeVoiceChat) + return &internalLinkTypeVoiceChat, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// InternalLinkTypeActiveSessions The link is a link to the active sessions section of the app. Use getActiveSessions to handle the link +type InternalLinkTypeActiveSessions struct { + tdCommon +} + +// MessageType return the string telegram-type of InternalLinkTypeActiveSessions +func (internalLinkTypeActiveSessions *InternalLinkTypeActiveSessions) MessageType() string { + return "internalLinkTypeActiveSessions" +} + +// NewInternalLinkTypeActiveSessions creates a new InternalLinkTypeActiveSessions +// +func NewInternalLinkTypeActiveSessions() *InternalLinkTypeActiveSessions { + internalLinkTypeActiveSessionsTemp := InternalLinkTypeActiveSessions{ + tdCommon: tdCommon{Type: "internalLinkTypeActiveSessions"}, + } + + return &internalLinkTypeActiveSessionsTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeActiveSessions *InternalLinkTypeActiveSessions) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeActiveSessionsType +} + +// InternalLinkTypeAuthenticationCode The link contains an authentication code. Call checkAuthenticationCode with the code if the current authorization state is authorizationStateWaitCode +type InternalLinkTypeAuthenticationCode struct { + tdCommon + Code string `json:"code"` // The authentication code +} + +// MessageType return the string telegram-type of InternalLinkTypeAuthenticationCode +func (internalLinkTypeAuthenticationCode *InternalLinkTypeAuthenticationCode) MessageType() string { + return "internalLinkTypeAuthenticationCode" +} + +// NewInternalLinkTypeAuthenticationCode creates a new InternalLinkTypeAuthenticationCode +// +// @param code The authentication code +func NewInternalLinkTypeAuthenticationCode(code string) *InternalLinkTypeAuthenticationCode { + internalLinkTypeAuthenticationCodeTemp := InternalLinkTypeAuthenticationCode{ + tdCommon: tdCommon{Type: "internalLinkTypeAuthenticationCode"}, + Code: code, + } + + return &internalLinkTypeAuthenticationCodeTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeAuthenticationCode *InternalLinkTypeAuthenticationCode) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeAuthenticationCodeType +} + +// InternalLinkTypeBackground The link is a link to a background. Call searchBackground with the given background name to process the link +type InternalLinkTypeBackground struct { + tdCommon + BackgroundName string `json:"background_name"` // Name of the background +} + +// MessageType return the string telegram-type of InternalLinkTypeBackground +func (internalLinkTypeBackground *InternalLinkTypeBackground) MessageType() string { + return "internalLinkTypeBackground" +} + +// NewInternalLinkTypeBackground creates a new InternalLinkTypeBackground +// +// @param backgroundName Name of the background +func NewInternalLinkTypeBackground(backgroundName string) *InternalLinkTypeBackground { + internalLinkTypeBackgroundTemp := InternalLinkTypeBackground{ + tdCommon: tdCommon{Type: "internalLinkTypeBackground"}, + BackgroundName: backgroundName, + } + + return &internalLinkTypeBackgroundTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeBackground *InternalLinkTypeBackground) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeBackgroundType +} + +// InternalLinkTypeBotStart The link is a link to a chat with a Telegram bot. Call searchPublicChat with the given bot username, check that the user is a bot, show START button in the chat with the bot, and then call sendBotStartMessage with the given start parameter after the button is pressed +type InternalLinkTypeBotStart struct { + tdCommon + BotUsername string `json:"bot_username"` // Username of the bot + StartParameter string `json:"start_parameter"` // The parameter to be passed to sendBotStartMessage +} + +// MessageType return the string telegram-type of InternalLinkTypeBotStart +func (internalLinkTypeBotStart *InternalLinkTypeBotStart) MessageType() string { + return "internalLinkTypeBotStart" +} + +// NewInternalLinkTypeBotStart creates a new InternalLinkTypeBotStart +// +// @param botUsername Username of the bot +// @param startParameter The parameter to be passed to sendBotStartMessage +func NewInternalLinkTypeBotStart(botUsername string, startParameter string) *InternalLinkTypeBotStart { + internalLinkTypeBotStartTemp := InternalLinkTypeBotStart{ + tdCommon: tdCommon{Type: "internalLinkTypeBotStart"}, + BotUsername: botUsername, + StartParameter: startParameter, + } + + return &internalLinkTypeBotStartTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeBotStart *InternalLinkTypeBotStart) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeBotStartType +} + +// InternalLinkTypeBotStartInGroup The link is a link to a Telegram bot, which is supposed to be added to a group chat. Call searchPublicChat with the given bot username, check that the user is a bot and can be added to groups, ask the current user to select a group to add the bot to, and then call sendBotStartMessage with the given start parameter and the chosen group chat. Bots can be added to a public group only by administrators of the group +type InternalLinkTypeBotStartInGroup struct { + tdCommon + BotUsername string `json:"bot_username"` // Username of the bot + StartParameter string `json:"start_parameter"` // The parameter to be passed to sendBotStartMessage +} + +// MessageType return the string telegram-type of InternalLinkTypeBotStartInGroup +func (internalLinkTypeBotStartInGroup *InternalLinkTypeBotStartInGroup) MessageType() string { + return "internalLinkTypeBotStartInGroup" +} + +// NewInternalLinkTypeBotStartInGroup creates a new InternalLinkTypeBotStartInGroup +// +// @param botUsername Username of the bot +// @param startParameter The parameter to be passed to sendBotStartMessage +func NewInternalLinkTypeBotStartInGroup(botUsername string, startParameter string) *InternalLinkTypeBotStartInGroup { + internalLinkTypeBotStartInGroupTemp := InternalLinkTypeBotStartInGroup{ + tdCommon: tdCommon{Type: "internalLinkTypeBotStartInGroup"}, + BotUsername: botUsername, + StartParameter: startParameter, + } + + return &internalLinkTypeBotStartInGroupTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeBotStartInGroup *InternalLinkTypeBotStartInGroup) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeBotStartInGroupType +} + +// InternalLinkTypeChangePhoneNumber The link is a link to the change phone number section of the app +type InternalLinkTypeChangePhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of InternalLinkTypeChangePhoneNumber +func (internalLinkTypeChangePhoneNumber *InternalLinkTypeChangePhoneNumber) MessageType() string { + return "internalLinkTypeChangePhoneNumber" +} + +// NewInternalLinkTypeChangePhoneNumber creates a new InternalLinkTypeChangePhoneNumber +// +func NewInternalLinkTypeChangePhoneNumber() *InternalLinkTypeChangePhoneNumber { + internalLinkTypeChangePhoneNumberTemp := InternalLinkTypeChangePhoneNumber{ + tdCommon: tdCommon{Type: "internalLinkTypeChangePhoneNumber"}, + } + + return &internalLinkTypeChangePhoneNumberTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeChangePhoneNumber *InternalLinkTypeChangePhoneNumber) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeChangePhoneNumberType +} + +// InternalLinkTypeChatInvite The link is a chat invite link. Call checkChatInviteLink with the given invite link to process the link +type InternalLinkTypeChatInvite struct { + tdCommon + InviteLink string `json:"invite_link"` // Internal representation of the invite link +} + +// MessageType return the string telegram-type of InternalLinkTypeChatInvite +func (internalLinkTypeChatInvite *InternalLinkTypeChatInvite) MessageType() string { + return "internalLinkTypeChatInvite" +} + +// NewInternalLinkTypeChatInvite creates a new InternalLinkTypeChatInvite +// +// @param inviteLink Internal representation of the invite link +func NewInternalLinkTypeChatInvite(inviteLink string) *InternalLinkTypeChatInvite { + internalLinkTypeChatInviteTemp := InternalLinkTypeChatInvite{ + tdCommon: tdCommon{Type: "internalLinkTypeChatInvite"}, + InviteLink: inviteLink, + } + + return &internalLinkTypeChatInviteTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeChatInvite *InternalLinkTypeChatInvite) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeChatInviteType +} + +// InternalLinkTypeFilterSettings The link is a link to the filter settings section of the app +type InternalLinkTypeFilterSettings struct { + tdCommon +} + +// MessageType return the string telegram-type of InternalLinkTypeFilterSettings +func (internalLinkTypeFilterSettings *InternalLinkTypeFilterSettings) MessageType() string { + return "internalLinkTypeFilterSettings" +} + +// NewInternalLinkTypeFilterSettings creates a new InternalLinkTypeFilterSettings +// +func NewInternalLinkTypeFilterSettings() *InternalLinkTypeFilterSettings { + internalLinkTypeFilterSettingsTemp := InternalLinkTypeFilterSettings{ + tdCommon: tdCommon{Type: "internalLinkTypeFilterSettings"}, + } + + return &internalLinkTypeFilterSettingsTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeFilterSettings *InternalLinkTypeFilterSettings) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeFilterSettingsType +} + +// InternalLinkTypeGame The link is a link to a game. Call searchPublicChat with the given bot username, check that the user is a bot, ask the current user to select a chat to send the game, and then call sendMessage with inputMessageGame +type InternalLinkTypeGame struct { + tdCommon + BotUsername string `json:"bot_username"` // Username 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 InternalLinkTypeGame +func (internalLinkTypeGame *InternalLinkTypeGame) MessageType() string { + return "internalLinkTypeGame" +} + +// NewInternalLinkTypeGame creates a new InternalLinkTypeGame +// +// @param botUsername Username of the bot that owns the game +// @param gameShortName Short name of the game +func NewInternalLinkTypeGame(botUsername string, gameShortName string) *InternalLinkTypeGame { + internalLinkTypeGameTemp := InternalLinkTypeGame{ + tdCommon: tdCommon{Type: "internalLinkTypeGame"}, + BotUsername: botUsername, + GameShortName: gameShortName, + } + + return &internalLinkTypeGameTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeGame *InternalLinkTypeGame) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeGameType +} + +// InternalLinkTypeLanguagePack The link is a link to a language pack. Call getLanguagePackInfo with the given language pack identifier to process the link +type InternalLinkTypeLanguagePack struct { + tdCommon + LanguagePackID string `json:"language_pack_id"` // Language pack identifier +} + +// MessageType return the string telegram-type of InternalLinkTypeLanguagePack +func (internalLinkTypeLanguagePack *InternalLinkTypeLanguagePack) MessageType() string { + return "internalLinkTypeLanguagePack" +} + +// NewInternalLinkTypeLanguagePack creates a new InternalLinkTypeLanguagePack +// +// @param languagePackID Language pack identifier +func NewInternalLinkTypeLanguagePack(languagePackID string) *InternalLinkTypeLanguagePack { + internalLinkTypeLanguagePackTemp := InternalLinkTypeLanguagePack{ + tdCommon: tdCommon{Type: "internalLinkTypeLanguagePack"}, + LanguagePackID: languagePackID, + } + + return &internalLinkTypeLanguagePackTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeLanguagePack *InternalLinkTypeLanguagePack) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeLanguagePackType +} + +// InternalLinkTypeMessage The link is a link to a Telegram message. Call getMessageLinkInfo with the given URL to process the link +type InternalLinkTypeMessage struct { + tdCommon + URL string `json:"url"` // URL to be passed to getMessageLinkInfo +} + +// MessageType return the string telegram-type of InternalLinkTypeMessage +func (internalLinkTypeMessage *InternalLinkTypeMessage) MessageType() string { + return "internalLinkTypeMessage" +} + +// NewInternalLinkTypeMessage creates a new InternalLinkTypeMessage +// +// @param uRL URL to be passed to getMessageLinkInfo +func NewInternalLinkTypeMessage(uRL string) *InternalLinkTypeMessage { + internalLinkTypeMessageTemp := InternalLinkTypeMessage{ + tdCommon: tdCommon{Type: "internalLinkTypeMessage"}, + URL: uRL, + } + + return &internalLinkTypeMessageTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeMessage *InternalLinkTypeMessage) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeMessageType +} + +// InternalLinkTypeMessageDraft The link contains a message draft text. A share screen needs to be shown to the user, then the chosen chat should be open and the text should be added to the input field +type InternalLinkTypeMessageDraft struct { + tdCommon + Text *FormattedText `json:"text"` // Message draft text + ContainsLink bool `json:"contains_link"` // True, if the first line of the text contains a link. If true, the input field needs to be focused and the text after the link should be selected +} + +// MessageType return the string telegram-type of InternalLinkTypeMessageDraft +func (internalLinkTypeMessageDraft *InternalLinkTypeMessageDraft) MessageType() string { + return "internalLinkTypeMessageDraft" +} + +// NewInternalLinkTypeMessageDraft creates a new InternalLinkTypeMessageDraft +// +// @param text Message draft text +// @param containsLink True, if the first line of the text contains a link. If true, the input field needs to be focused and the text after the link should be selected +func NewInternalLinkTypeMessageDraft(text *FormattedText, containsLink bool) *InternalLinkTypeMessageDraft { + internalLinkTypeMessageDraftTemp := InternalLinkTypeMessageDraft{ + tdCommon: tdCommon{Type: "internalLinkTypeMessageDraft"}, + Text: text, + ContainsLink: containsLink, + } + + return &internalLinkTypeMessageDraftTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeMessageDraft *InternalLinkTypeMessageDraft) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeMessageDraftType +} + +// InternalLinkTypePassportDataRequest The link contains a request of Telegram passport data. Call getPassportAuthorizationForm with the given parameters to process the link if the link was received from outside of the app, otherwise ignore it +type InternalLinkTypePassportDataRequest struct { + tdCommon + BotUserID int64 `json:"bot_user_id"` // User identifier of the service's bot + Scope string `json:"scope"` // Telegram Passport element types requested by the service + PublicKey string `json:"public_key"` // Service's public key + Nonce string `json:"nonce"` // Unique request identifier provided by the service + CallbackURL string `json:"callback_url"` // An HTTP URL to open once the request is finished or canceled with the parameter tg_passport=success or tg_passport=cancel respectively. If empty, then the link tgbot{bot_user_id}://passport/success or tgbot{bot_user_id}://passport/cancel needs to be opened instead +} + +// MessageType return the string telegram-type of InternalLinkTypePassportDataRequest +func (internalLinkTypePassportDataRequest *InternalLinkTypePassportDataRequest) MessageType() string { + return "internalLinkTypePassportDataRequest" +} + +// NewInternalLinkTypePassportDataRequest creates a new InternalLinkTypePassportDataRequest +// +// @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 Unique request identifier provided by the service +// @param callbackURL An HTTP URL to open once the request is finished or canceled with the parameter tg_passport=success or tg_passport=cancel respectively. If empty, then the link tgbot{bot_user_id}://passport/success or tgbot{bot_user_id}://passport/cancel needs to be opened instead +func NewInternalLinkTypePassportDataRequest(botUserID int64, scope string, publicKey string, nonce string, callbackURL string) *InternalLinkTypePassportDataRequest { + internalLinkTypePassportDataRequestTemp := InternalLinkTypePassportDataRequest{ + tdCommon: tdCommon{Type: "internalLinkTypePassportDataRequest"}, + BotUserID: botUserID, + Scope: scope, + PublicKey: publicKey, + Nonce: nonce, + CallbackURL: callbackURL, + } + + return &internalLinkTypePassportDataRequestTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypePassportDataRequest *InternalLinkTypePassportDataRequest) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypePassportDataRequestType +} + +// InternalLinkTypePhoneNumberConfirmation The link can be used to confirm ownership of a phone number to prevent account deletion. Call sendPhoneNumberConfirmationCode with the given hash and phone number to process the link +type InternalLinkTypePhoneNumberConfirmation struct { + tdCommon + Hash string `json:"hash"` // Hash value from the link + PhoneNumber string `json:"phone_number"` // Phone number value from the link +} + +// MessageType return the string telegram-type of InternalLinkTypePhoneNumberConfirmation +func (internalLinkTypePhoneNumberConfirmation *InternalLinkTypePhoneNumberConfirmation) MessageType() string { + return "internalLinkTypePhoneNumberConfirmation" +} + +// NewInternalLinkTypePhoneNumberConfirmation creates a new InternalLinkTypePhoneNumberConfirmation +// +// @param hash Hash value from the link +// @param phoneNumber Phone number value from the link +func NewInternalLinkTypePhoneNumberConfirmation(hash string, phoneNumber string) *InternalLinkTypePhoneNumberConfirmation { + internalLinkTypePhoneNumberConfirmationTemp := InternalLinkTypePhoneNumberConfirmation{ + tdCommon: tdCommon{Type: "internalLinkTypePhoneNumberConfirmation"}, + Hash: hash, + PhoneNumber: phoneNumber, + } + + return &internalLinkTypePhoneNumberConfirmationTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypePhoneNumberConfirmation *InternalLinkTypePhoneNumberConfirmation) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypePhoneNumberConfirmationType +} + +// InternalLinkTypeProxy The link is a link to a proxy. Call addProxy with the given parameters to process the link and add the proxy +type InternalLinkTypeProxy struct { + tdCommon + Server string `json:"server"` // Proxy server IP address + Port int32 `json:"port"` // Proxy server port + Type ProxyType `json:"type"` // Type of the proxy +} + +// MessageType return the string telegram-type of InternalLinkTypeProxy +func (internalLinkTypeProxy *InternalLinkTypeProxy) MessageType() string { + return "internalLinkTypeProxy" +} + +// NewInternalLinkTypeProxy creates a new InternalLinkTypeProxy +// +// @param server Proxy server IP address +// @param port Proxy server port +// @param typeParam Type of the proxy +func NewInternalLinkTypeProxy(server string, port int32, typeParam ProxyType) *InternalLinkTypeProxy { + internalLinkTypeProxyTemp := InternalLinkTypeProxy{ + tdCommon: tdCommon{Type: "internalLinkTypeProxy"}, + Server: server, + Port: port, + Type: typeParam, + } + + return &internalLinkTypeProxyTemp +} + +// UnmarshalJSON unmarshal to json +func (internalLinkTypeProxy *InternalLinkTypeProxy) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Server string `json:"server"` // Proxy server IP address + Port int32 `json:"port"` // Proxy server port + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + internalLinkTypeProxy.tdCommon = tempObj.tdCommon + internalLinkTypeProxy.Server = tempObj.Server + internalLinkTypeProxy.Port = tempObj.Port + + fieldType, _ := unmarshalProxyType(objMap["type"]) + internalLinkTypeProxy.Type = fieldType + + return nil +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeProxy *InternalLinkTypeProxy) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeProxyType +} + +// InternalLinkTypePublicChat The link is a link to a chat by its username. Call searchPublicChat with the given chat username to process the link +type InternalLinkTypePublicChat struct { + tdCommon + ChatUsername string `json:"chat_username"` // Username of the chat +} + +// MessageType return the string telegram-type of InternalLinkTypePublicChat +func (internalLinkTypePublicChat *InternalLinkTypePublicChat) MessageType() string { + return "internalLinkTypePublicChat" +} + +// NewInternalLinkTypePublicChat creates a new InternalLinkTypePublicChat +// +// @param chatUsername Username of the chat +func NewInternalLinkTypePublicChat(chatUsername string) *InternalLinkTypePublicChat { + internalLinkTypePublicChatTemp := InternalLinkTypePublicChat{ + tdCommon: tdCommon{Type: "internalLinkTypePublicChat"}, + ChatUsername: chatUsername, + } + + return &internalLinkTypePublicChatTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypePublicChat *InternalLinkTypePublicChat) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypePublicChatType +} + +// InternalLinkTypeQrCodeAuthentication The link can be used to login the current user on another device, but it must be scanned from QR-code using in-app camera. An alert similar to "This code can be used to allow someone to log in to your Telegram account. To confirm Telegram login, please go to Settings > Devices > Scan QR and scan the code" needs to be shown +type InternalLinkTypeQrCodeAuthentication struct { + tdCommon +} + +// MessageType return the string telegram-type of InternalLinkTypeQrCodeAuthentication +func (internalLinkTypeQrCodeAuthentication *InternalLinkTypeQrCodeAuthentication) MessageType() string { + return "internalLinkTypeQrCodeAuthentication" +} + +// NewInternalLinkTypeQrCodeAuthentication creates a new InternalLinkTypeQrCodeAuthentication +// +func NewInternalLinkTypeQrCodeAuthentication() *InternalLinkTypeQrCodeAuthentication { + internalLinkTypeQrCodeAuthenticationTemp := InternalLinkTypeQrCodeAuthentication{ + tdCommon: tdCommon{Type: "internalLinkTypeQrCodeAuthentication"}, + } + + return &internalLinkTypeQrCodeAuthenticationTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeQrCodeAuthentication *InternalLinkTypeQrCodeAuthentication) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeQrCodeAuthenticationType +} + +// InternalLinkTypeSettings The link is a link to app settings +type InternalLinkTypeSettings struct { + tdCommon +} + +// MessageType return the string telegram-type of InternalLinkTypeSettings +func (internalLinkTypeSettings *InternalLinkTypeSettings) MessageType() string { + return "internalLinkTypeSettings" +} + +// NewInternalLinkTypeSettings creates a new InternalLinkTypeSettings +// +func NewInternalLinkTypeSettings() *InternalLinkTypeSettings { + internalLinkTypeSettingsTemp := InternalLinkTypeSettings{ + tdCommon: tdCommon{Type: "internalLinkTypeSettings"}, + } + + return &internalLinkTypeSettingsTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeSettings *InternalLinkTypeSettings) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeSettingsType +} + +// InternalLinkTypeStickerSet The link is a link to a sticker set. Call searchStickerSet with the given sticker set name to process the link and show the sticker set +type InternalLinkTypeStickerSet struct { + tdCommon + StickerSetName string `json:"sticker_set_name"` // Name of the sticker set +} + +// MessageType return the string telegram-type of InternalLinkTypeStickerSet +func (internalLinkTypeStickerSet *InternalLinkTypeStickerSet) MessageType() string { + return "internalLinkTypeStickerSet" +} + +// NewInternalLinkTypeStickerSet creates a new InternalLinkTypeStickerSet +// +// @param stickerSetName Name of the sticker set +func NewInternalLinkTypeStickerSet(stickerSetName string) *InternalLinkTypeStickerSet { + internalLinkTypeStickerSetTemp := InternalLinkTypeStickerSet{ + tdCommon: tdCommon{Type: "internalLinkTypeStickerSet"}, + StickerSetName: stickerSetName, + } + + return &internalLinkTypeStickerSetTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeStickerSet *InternalLinkTypeStickerSet) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeStickerSetType +} + +// InternalLinkTypeTheme The link is a link to a theme. TDLib has no theme support yet +type InternalLinkTypeTheme struct { + tdCommon + ThemeName string `json:"theme_name"` // Name of the theme +} + +// MessageType return the string telegram-type of InternalLinkTypeTheme +func (internalLinkTypeTheme *InternalLinkTypeTheme) MessageType() string { + return "internalLinkTypeTheme" +} + +// NewInternalLinkTypeTheme creates a new InternalLinkTypeTheme +// +// @param themeName Name of the theme +func NewInternalLinkTypeTheme(themeName string) *InternalLinkTypeTheme { + internalLinkTypeThemeTemp := InternalLinkTypeTheme{ + tdCommon: tdCommon{Type: "internalLinkTypeTheme"}, + ThemeName: themeName, + } + + return &internalLinkTypeThemeTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeTheme *InternalLinkTypeTheme) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeThemeType +} + +// InternalLinkTypeThemeSettings The link is a link to the theme settings section of the app +type InternalLinkTypeThemeSettings struct { + tdCommon +} + +// MessageType return the string telegram-type of InternalLinkTypeThemeSettings +func (internalLinkTypeThemeSettings *InternalLinkTypeThemeSettings) MessageType() string { + return "internalLinkTypeThemeSettings" +} + +// NewInternalLinkTypeThemeSettings creates a new InternalLinkTypeThemeSettings +// +func NewInternalLinkTypeThemeSettings() *InternalLinkTypeThemeSettings { + internalLinkTypeThemeSettingsTemp := InternalLinkTypeThemeSettings{ + tdCommon: tdCommon{Type: "internalLinkTypeThemeSettings"}, + } + + return &internalLinkTypeThemeSettingsTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeThemeSettings *InternalLinkTypeThemeSettings) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeThemeSettingsType +} + +// InternalLinkTypeUnknownDeepLink The link is an unknown tg: link. Call getDeepLinkInfo to process the link +type InternalLinkTypeUnknownDeepLink struct { + tdCommon + Link string `json:"link"` // Link to be passed to getDeepLinkInfo +} + +// MessageType return the string telegram-type of InternalLinkTypeUnknownDeepLink +func (internalLinkTypeUnknownDeepLink *InternalLinkTypeUnknownDeepLink) MessageType() string { + return "internalLinkTypeUnknownDeepLink" +} + +// NewInternalLinkTypeUnknownDeepLink creates a new InternalLinkTypeUnknownDeepLink +// +// @param link Link to be passed to getDeepLinkInfo +func NewInternalLinkTypeUnknownDeepLink(link string) *InternalLinkTypeUnknownDeepLink { + internalLinkTypeUnknownDeepLinkTemp := InternalLinkTypeUnknownDeepLink{ + tdCommon: tdCommon{Type: "internalLinkTypeUnknownDeepLink"}, + Link: link, + } + + return &internalLinkTypeUnknownDeepLinkTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeUnknownDeepLink *InternalLinkTypeUnknownDeepLink) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeUnknownDeepLinkType +} + +// InternalLinkTypeVoiceChat The link is a link to a voice chat. Call searchPublicChat with the given chat username, and then joinGoupCall with the given invite hash to process the link +type InternalLinkTypeVoiceChat struct { + tdCommon + ChatUsername string `json:"chat_username"` // Username of the chat with the voice chat + InviteHash string `json:"invite_hash"` // If non-empty, invite hash to be used to join the voice chat without being muted by administrators + IsLiveStream bool `json:"is_live_stream"` // True, if the voice chat is expected to be a live stream in a channel or a broadcast group +} + +// MessageType return the string telegram-type of InternalLinkTypeVoiceChat +func (internalLinkTypeVoiceChat *InternalLinkTypeVoiceChat) MessageType() string { + return "internalLinkTypeVoiceChat" +} + +// NewInternalLinkTypeVoiceChat creates a new InternalLinkTypeVoiceChat +// +// @param chatUsername Username of the chat with the voice chat +// @param inviteHash If non-empty, invite hash to be used to join the voice chat without being muted by administrators +// @param isLiveStream True, if the voice chat is expected to be a live stream in a channel or a broadcast group +func NewInternalLinkTypeVoiceChat(chatUsername string, inviteHash string, isLiveStream bool) *InternalLinkTypeVoiceChat { + internalLinkTypeVoiceChatTemp := InternalLinkTypeVoiceChat{ + tdCommon: tdCommon{Type: "internalLinkTypeVoiceChat"}, + ChatUsername: chatUsername, + InviteHash: inviteHash, + IsLiveStream: isLiveStream, + } + + return &internalLinkTypeVoiceChatTemp +} + +// GetInternalLinkTypeEnum return the enum type of this object +func (internalLinkTypeVoiceChat *InternalLinkTypeVoiceChat) GetInternalLinkTypeEnum() InternalLinkTypeEnum { + return InternalLinkTypeVoiceChatType +} diff --git a/tdlib/invoice.go b/tdlib/invoice.go new file mode 100644 index 0000000..5e432a9 --- /dev/null +++ b/tdlib/invoice.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + MaxTipAmount int64 `json:"max_tip_amount"` // The maximum allowed amount of tip in the smallest units of the currency + SuggestedTipAmounts []int64 `json:"suggested_tip_amounts"` // Suggested amounts of tip in the smallest units of the currency + 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 maxTipAmount The maximum allowed amount of tip in the smallest units of the currency +// @param suggestedTipAmounts Suggested amounts of tip in the smallest units of the currency +// @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, maxTipAmount int64, suggestedTipAmounts []int64, 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, + MaxTipAmount: maxTipAmount, + SuggestedTipAmounts: suggestedTipAmounts, + IsTest: isTest, + NeedName: needName, + NeedPhoneNumber: needPhoneNumber, + NeedEmailAddress: needEmailAddress, + NeedShippingAddress: needShippingAddress, + SendPhoneNumberToProvider: sendPhoneNumberToProvider, + SendEmailAddressToProvider: sendEmailAddressToProvider, + IsFlexible: isFlexible, + } + + return &invoiceTemp +} diff --git a/tdlib/jsonObjectMember.go b/tdlib/jsonObjectMember.go new file mode 100644 index 0000000..2ea531c --- /dev/null +++ b/tdlib/jsonObjectMember.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// JsonObjectMember Represents one member of a JSON object +type JsonObjectMember struct { + tdCommon + Key string `json:"key"` // Member's key + Value JsonValue `json:"value"` // Member's value +} + +// MessageType return the string telegram-type of JsonObjectMember +func (jsonObjectMember *JsonObjectMember) MessageType() string { + return "jsonObjectMember" +} + +// NewJsonObjectMember creates a new JsonObjectMember +// +// @param key Member's key +// @param value Member's value +func NewJsonObjectMember(key string, value JsonValue) *JsonObjectMember { + jsonObjectMemberTemp := JsonObjectMember{ + tdCommon: tdCommon{Type: "jsonObjectMember"}, + Key: key, + Value: value, + } + + return &jsonObjectMemberTemp +} + +// UnmarshalJSON unmarshal to json +func (jsonObjectMember *JsonObjectMember) 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"` // Member's key + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + jsonObjectMember.tdCommon = tempObj.tdCommon + jsonObjectMember.Key = tempObj.Key + + fieldValue, _ := unmarshalJsonValue(objMap["value"]) + jsonObjectMember.Value = fieldValue + + return nil +} diff --git a/tdlib/jsonValue.go b/tdlib/jsonValue.go new file mode 100644 index 0000000..1029d93 --- /dev/null +++ b/tdlib/jsonValue.go @@ -0,0 +1,238 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// JsonValue Represents a JSON value +type JsonValue interface { + GetJsonValueEnum() JsonValueEnum +} + +// JsonValueEnum Alias for abstract JsonValue 'Sub-Classes', used as constant-enum here +type JsonValueEnum string + +// JsonValue enums +const ( + JsonValueNullType JsonValueEnum = "jsonValueNull" + JsonValueBooleanType JsonValueEnum = "jsonValueBoolean" + JsonValueNumberType JsonValueEnum = "jsonValueNumber" + JsonValueStringType JsonValueEnum = "jsonValueString" + JsonValueArrayType JsonValueEnum = "jsonValueArray" + JsonValueObjectType JsonValueEnum = "jsonValueObject" +) + +func unmarshalJsonValue(rawMsg *json.RawMessage) (JsonValue, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch JsonValueEnum(objMap["@type"].(string)) { + case JsonValueNullType: + var jsonValueNull JsonValueNull + err := json.Unmarshal(*rawMsg, &jsonValueNull) + return &jsonValueNull, err + + case JsonValueBooleanType: + var jsonValueBoolean JsonValueBoolean + err := json.Unmarshal(*rawMsg, &jsonValueBoolean) + return &jsonValueBoolean, err + + case JsonValueNumberType: + var jsonValueNumber JsonValueNumber + err := json.Unmarshal(*rawMsg, &jsonValueNumber) + return &jsonValueNumber, err + + case JsonValueStringType: + var jsonValueString JsonValueString + err := json.Unmarshal(*rawMsg, &jsonValueString) + return &jsonValueString, err + + case JsonValueArrayType: + var jsonValueArray JsonValueArray + err := json.Unmarshal(*rawMsg, &jsonValueArray) + return &jsonValueArray, err + + case JsonValueObjectType: + var jsonValueObject JsonValueObject + err := json.Unmarshal(*rawMsg, &jsonValueObject) + return &jsonValueObject, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// JsonValueNull Represents a null JSON value +type JsonValueNull struct { + tdCommon +} + +// MessageType return the string telegram-type of JsonValueNull +func (jsonValueNull *JsonValueNull) MessageType() string { + return "jsonValueNull" +} + +// NewJsonValueNull creates a new JsonValueNull +// +func NewJsonValueNull() *JsonValueNull { + jsonValueNullTemp := JsonValueNull{ + tdCommon: tdCommon{Type: "jsonValueNull"}, + } + + return &jsonValueNullTemp +} + +// GetJsonValueEnum return the enum type of this object +func (jsonValueNull *JsonValueNull) GetJsonValueEnum() JsonValueEnum { + return JsonValueNullType +} + +// JsonValueBoolean Represents a boolean JSON value +type JsonValueBoolean struct { + tdCommon + Value bool `json:"value"` // The value +} + +// MessageType return the string telegram-type of JsonValueBoolean +func (jsonValueBoolean *JsonValueBoolean) MessageType() string { + return "jsonValueBoolean" +} + +// NewJsonValueBoolean creates a new JsonValueBoolean +// +// @param value The value +func NewJsonValueBoolean(value bool) *JsonValueBoolean { + jsonValueBooleanTemp := JsonValueBoolean{ + tdCommon: tdCommon{Type: "jsonValueBoolean"}, + Value: value, + } + + return &jsonValueBooleanTemp +} + +// GetJsonValueEnum return the enum type of this object +func (jsonValueBoolean *JsonValueBoolean) GetJsonValueEnum() JsonValueEnum { + return JsonValueBooleanType +} + +// JsonValueNumber Represents a numeric JSON value +type JsonValueNumber struct { + tdCommon + Value float64 `json:"value"` // The value +} + +// MessageType return the string telegram-type of JsonValueNumber +func (jsonValueNumber *JsonValueNumber) MessageType() string { + return "jsonValueNumber" +} + +// NewJsonValueNumber creates a new JsonValueNumber +// +// @param value The value +func NewJsonValueNumber(value float64) *JsonValueNumber { + jsonValueNumberTemp := JsonValueNumber{ + tdCommon: tdCommon{Type: "jsonValueNumber"}, + Value: value, + } + + return &jsonValueNumberTemp +} + +// GetJsonValueEnum return the enum type of this object +func (jsonValueNumber *JsonValueNumber) GetJsonValueEnum() JsonValueEnum { + return JsonValueNumberType +} + +// JsonValueString Represents a string JSON value +type JsonValueString struct { + tdCommon + Value string `json:"value"` // The value +} + +// MessageType return the string telegram-type of JsonValueString +func (jsonValueString *JsonValueString) MessageType() string { + return "jsonValueString" +} + +// NewJsonValueString creates a new JsonValueString +// +// @param value The value +func NewJsonValueString(value string) *JsonValueString { + jsonValueStringTemp := JsonValueString{ + tdCommon: tdCommon{Type: "jsonValueString"}, + Value: value, + } + + return &jsonValueStringTemp +} + +// GetJsonValueEnum return the enum type of this object +func (jsonValueString *JsonValueString) GetJsonValueEnum() JsonValueEnum { + return JsonValueStringType +} + +// JsonValueArray Represents a JSON array +type JsonValueArray struct { + tdCommon + Values []JsonValue `json:"values"` // The list of array elements +} + +// MessageType return the string telegram-type of JsonValueArray +func (jsonValueArray *JsonValueArray) MessageType() string { + return "jsonValueArray" +} + +// NewJsonValueArray creates a new JsonValueArray +// +// @param values The list of array elements +func NewJsonValueArray(values []JsonValue) *JsonValueArray { + jsonValueArrayTemp := JsonValueArray{ + tdCommon: tdCommon{Type: "jsonValueArray"}, + Values: values, + } + + return &jsonValueArrayTemp +} + +// GetJsonValueEnum return the enum type of this object +func (jsonValueArray *JsonValueArray) GetJsonValueEnum() JsonValueEnum { + return JsonValueArrayType +} + +// JsonValueObject Represents a JSON object +type JsonValueObject struct { + tdCommon + Members []JsonObjectMember `json:"members"` // The list of object members +} + +// MessageType return the string telegram-type of JsonValueObject +func (jsonValueObject *JsonValueObject) MessageType() string { + return "jsonValueObject" +} + +// NewJsonValueObject creates a new JsonValueObject +// +// @param members The list of object members +func NewJsonValueObject(members []JsonObjectMember) *JsonValueObject { + jsonValueObjectTemp := JsonValueObject{ + tdCommon: tdCommon{Type: "jsonValueObject"}, + Members: members, + } + + return &jsonValueObjectTemp +} + +// GetJsonValueEnum return the enum type of this object +func (jsonValueObject *JsonValueObject) GetJsonValueEnum() JsonValueEnum { + return JsonValueObjectType +} diff --git a/tdlib/keyboardButton.go b/tdlib/keyboardButton.go new file mode 100644 index 0000000..f1c4e23 --- /dev/null +++ b/tdlib/keyboardButton.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/keyboardButtonType.go b/tdlib/keyboardButtonType.go new file mode 100644 index 0000000..5566356 --- /dev/null +++ b/tdlib/keyboardButtonType.go @@ -0,0 +1,167 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// KeyboardButtonType Describes a keyboard button type +type KeyboardButtonType interface { + GetKeyboardButtonTypeEnum() KeyboardButtonTypeEnum +} + +// 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" + KeyboardButtonTypeRequestPollType KeyboardButtonTypeEnum = "keyboardButtonTypeRequestPoll" +) + +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 + + case KeyboardButtonTypeRequestPollType: + var keyboardButtonTypeRequestPoll KeyboardButtonTypeRequestPoll + err := json.Unmarshal(*rawMsg, &keyboardButtonTypeRequestPoll) + return &keyboardButtonTypeRequestPoll, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 +} + +// KeyboardButtonTypeRequestPoll A button that allows the user to create and send a poll when pressed; available only in private chats +type KeyboardButtonTypeRequestPoll struct { + tdCommon + ForceRegular bool `json:"force_regular"` // If true, only regular polls must be allowed to create + ForceQuiz bool `json:"force_quiz"` // If true, only polls in quiz mode must be allowed to create +} + +// MessageType return the string telegram-type of KeyboardButtonTypeRequestPoll +func (keyboardButtonTypeRequestPoll *KeyboardButtonTypeRequestPoll) MessageType() string { + return "keyboardButtonTypeRequestPoll" +} + +// NewKeyboardButtonTypeRequestPoll creates a new KeyboardButtonTypeRequestPoll +// +// @param forceRegular If true, only regular polls must be allowed to create +// @param forceQuiz If true, only polls in quiz mode must be allowed to create +func NewKeyboardButtonTypeRequestPoll(forceRegular bool, forceQuiz bool) *KeyboardButtonTypeRequestPoll { + keyboardButtonTypeRequestPollTemp := KeyboardButtonTypeRequestPoll{ + tdCommon: tdCommon{Type: "keyboardButtonTypeRequestPoll"}, + ForceRegular: forceRegular, + ForceQuiz: forceQuiz, + } + + return &keyboardButtonTypeRequestPollTemp +} + +// GetKeyboardButtonTypeEnum return the enum type of this object +func (keyboardButtonTypeRequestPoll *KeyboardButtonTypeRequestPoll) GetKeyboardButtonTypeEnum() KeyboardButtonTypeEnum { + return KeyboardButtonTypeRequestPollType +} diff --git a/tdlib/labeledPricePart.go b/tdlib/labeledPricePart.go new file mode 100644 index 0000000..66fd8e0 --- /dev/null +++ b/tdlib/labeledPricePart.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 the smallest units 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 the smallest units of the currency +func NewLabeledPricePart(label string, amount int64) *LabeledPricePart { + labeledPricePartTemp := LabeledPricePart{ + tdCommon: tdCommon{Type: "labeledPricePart"}, + Label: label, + Amount: amount, + } + + return &labeledPricePartTemp +} diff --git a/tdlib/languagePackInfo.go b/tdlib/languagePackInfo.go new file mode 100644 index 0000000..7762083 --- /dev/null +++ b/tdlib/languagePackInfo.go @@ -0,0 +1,62 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// LanguagePackInfo Contains information about a language pack +type LanguagePackInfo struct { + tdCommon + ID string `json:"id"` // Unique language pack identifier + BaseLanguagePackID string `json:"base_language_pack_id"` // Identifier of a base language pack; may be empty. If a string is missed in the language pack, then it should be fetched from base language pack. Unsupported in custom language packs + Name string `json:"name"` // Language name + NativeName string `json:"native_name"` // Name of the language in that language + PluralCode string `json:"plural_code"` // A language code to be used to apply plural forms. See https://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html for more info + IsOfficial bool `json:"is_official"` // True, if the language pack is official + IsRtl bool `json:"is_rtl"` // True, if the language pack strings are RTL + IsBeta bool `json:"is_beta"` // True, if the language pack is a beta language pack + IsInstalled bool `json:"is_installed"` // True, if the language pack is installed by the current user + TotalStringCount int32 `json:"total_string_count"` // Total number of non-deleted strings from the language pack + TranslatedStringCount int32 `json:"translated_string_count"` // Total number of translated strings from the language pack + LocalStringCount int32 `json:"local_string_count"` // Total number of non-deleted strings from the language pack available locally + TranslationURL string `json:"translation_url"` // Link to language translation interface; empty for custom local language packs +} + +// 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 baseLanguagePackID Identifier of a base language pack; may be empty. If a string is missed in the language pack, then it should be fetched from base language pack. Unsupported in custom language packs +// @param name Language name +// @param nativeName Name of the language in that language +// @param pluralCode A language code to be used to apply plural forms. See https://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html for more info +// @param isOfficial True, if the language pack is official +// @param isRtl True, if the language pack strings are RTL +// @param isBeta True, if the language pack is a beta language pack +// @param isInstalled True, if the language pack is installed by the current user +// @param totalStringCount Total number of non-deleted strings from the language pack +// @param translatedStringCount Total number of translated strings from the language pack +// @param localStringCount Total number of non-deleted strings from the language pack available locally +// @param translationURL Link to language translation interface; empty for custom local language packs +func NewLanguagePackInfo(iD string, baseLanguagePackID string, name string, nativeName string, pluralCode string, isOfficial bool, isRtl bool, isBeta bool, isInstalled bool, totalStringCount int32, translatedStringCount int32, localStringCount int32, translationURL string) *LanguagePackInfo { + languagePackInfoTemp := LanguagePackInfo{ + tdCommon: tdCommon{Type: "languagePackInfo"}, + ID: iD, + BaseLanguagePackID: baseLanguagePackID, + Name: name, + NativeName: nativeName, + PluralCode: pluralCode, + IsOfficial: isOfficial, + IsRtl: isRtl, + IsBeta: isBeta, + IsInstalled: isInstalled, + TotalStringCount: totalStringCount, + TranslatedStringCount: translatedStringCount, + LocalStringCount: localStringCount, + TranslationURL: translationURL, + } + + return &languagePackInfoTemp +} diff --git a/tdlib/languagePackString.go b/tdlib/languagePackString.go new file mode 100644 index 0000000..e4b83d7 --- /dev/null +++ b/tdlib/languagePackString.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/languagePackStringValue.go b/tdlib/languagePackStringValue.go new file mode 100644 index 0000000..24b5cf3 --- /dev/null +++ b/tdlib/languagePackStringValue.go @@ -0,0 +1,151 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// LanguagePackStringValue Represents the value of a string in a language pack +type LanguagePackStringValue interface { + GetLanguagePackStringValueEnum() LanguagePackStringValueEnum +} + +// 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" +) + +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)) + } +} + +// 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. See https://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html for more info +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 +} diff --git a/tdlib/languagePackStrings.go b/tdlib/languagePackStrings.go new file mode 100644 index 0000000..56ddc45 --- /dev/null +++ b/tdlib/languagePackStrings.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/localFile.go b/tdlib/localFile.go new file mode 100644 index 0000000..add57e9 --- /dev/null +++ b/tdlib/localFile.go @@ -0,0 +1,47 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + DownloadOffset int32 `json:"download_offset"` // Download will be started from this offset. downloaded_prefix_size is calculated from this offset + DownloadedPrefixSize int32 `json:"downloaded_prefix_size"` // If is_downloading_completed is false, then only some prefix of the file starting from download_offset is ready to be read. downloaded_prefix_size is the size of that prefix in bytes + DownloadedSize int32 `json:"downloaded_size"` // Total downloaded file size, in 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 downloadOffset Download will be started from this offset. downloaded_prefix_size is calculated from this offset +// @param downloadedPrefixSize If is_downloading_completed is false, then only some prefix of the file starting from download_offset is ready to be read. downloaded_prefix_size is the size of that prefix in bytes +// @param downloadedSize Total downloaded file size, in 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, downloadOffset int32, downloadedPrefixSize int32, downloadedSize int32) *LocalFile { + localFileTemp := LocalFile{ + tdCommon: tdCommon{Type: "localFile"}, + Path: path, + CanBeDownloaded: canBeDownloaded, + CanBeDeleted: canBeDeleted, + IsDownloadingActive: isDownloadingActive, + IsDownloadingCompleted: isDownloadingCompleted, + DownloadOffset: downloadOffset, + DownloadedPrefixSize: downloadedPrefixSize, + DownloadedSize: downloadedSize, + } + + return &localFileTemp +} diff --git a/tdlib/localizationTargetInfo.go b/tdlib/localizationTargetInfo.go new file mode 100644 index 0000000..84395f6 --- /dev/null +++ b/tdlib/localizationTargetInfo.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/location.go b/tdlib/location.go new file mode 100644 index 0000000..27b4dde --- /dev/null +++ b/tdlib/location.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + HorizontalAccuracy float64 `json:"horizontal_accuracy"` // The estimated horizontal accuracy of the location, in meters; as defined by the sender. 0 if unknown +} + +// 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 +// @param horizontalAccuracy The estimated horizontal accuracy of the location, in meters; as defined by the sender. 0 if unknown +func NewLocation(latitude float64, longitude float64, horizontalAccuracy float64) *Location { + locationTemp := Location{ + tdCommon: tdCommon{Type: "location"}, + Latitude: latitude, + Longitude: longitude, + HorizontalAccuracy: horizontalAccuracy, + } + + return &locationTemp +} diff --git a/tdlib/logStream.go b/tdlib/logStream.go new file mode 100644 index 0000000..6f9afb3 --- /dev/null +++ b/tdlib/logStream.go @@ -0,0 +1,139 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// LogStream Describes a stream to which TDLib internal log is written +type LogStream interface { + GetLogStreamEnum() LogStreamEnum +} + +// LogStreamEnum Alias for abstract LogStream 'Sub-Classes', used as constant-enum here +type LogStreamEnum string + +// LogStream enums +const ( + LogStreamDefaultType LogStreamEnum = "logStreamDefault" + LogStreamFileType LogStreamEnum = "logStreamFile" + LogStreamEmptyType LogStreamEnum = "logStreamEmpty" +) + +func unmarshalLogStream(rawMsg *json.RawMessage) (LogStream, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch LogStreamEnum(objMap["@type"].(string)) { + case LogStreamDefaultType: + var logStreamDefault LogStreamDefault + err := json.Unmarshal(*rawMsg, &logStreamDefault) + return &logStreamDefault, err + + case LogStreamFileType: + var logStreamFile LogStreamFile + err := json.Unmarshal(*rawMsg, &logStreamFile) + return &logStreamFile, err + + case LogStreamEmptyType: + var logStreamEmpty LogStreamEmpty + err := json.Unmarshal(*rawMsg, &logStreamEmpty) + return &logStreamEmpty, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// LogStreamDefault The log is written to stderr or an OS specific log +type LogStreamDefault struct { + tdCommon +} + +// MessageType return the string telegram-type of LogStreamDefault +func (logStreamDefault *LogStreamDefault) MessageType() string { + return "logStreamDefault" +} + +// NewLogStreamDefault creates a new LogStreamDefault +// +func NewLogStreamDefault() *LogStreamDefault { + logStreamDefaultTemp := LogStreamDefault{ + tdCommon: tdCommon{Type: "logStreamDefault"}, + } + + return &logStreamDefaultTemp +} + +// GetLogStreamEnum return the enum type of this object +func (logStreamDefault *LogStreamDefault) GetLogStreamEnum() LogStreamEnum { + return LogStreamDefaultType +} + +// LogStreamFile The log is written to a file +type LogStreamFile struct { + tdCommon + Path string `json:"path"` // Path to the file to where the internal TDLib log will be written + MaxFileSize int64 `json:"max_file_size"` // The maximum size of the file to where the internal TDLib log is written before the file will be auto-rotated, in bytes + RedirectStderr bool `json:"redirect_stderr"` // Pass true to additionally redirect stderr to the log file. Ignored on Windows +} + +// MessageType return the string telegram-type of LogStreamFile +func (logStreamFile *LogStreamFile) MessageType() string { + return "logStreamFile" +} + +// NewLogStreamFile creates a new LogStreamFile +// +// @param path Path to the file to where the internal TDLib log will be written +// @param maxFileSize The maximum size of the file to where the internal TDLib log is written before the file will be auto-rotated, in bytes +// @param redirectStderr Pass true to additionally redirect stderr to the log file. Ignored on Windows +func NewLogStreamFile(path string, maxFileSize int64, redirectStderr bool) *LogStreamFile { + logStreamFileTemp := LogStreamFile{ + tdCommon: tdCommon{Type: "logStreamFile"}, + Path: path, + MaxFileSize: maxFileSize, + RedirectStderr: redirectStderr, + } + + return &logStreamFileTemp +} + +// GetLogStreamEnum return the enum type of this object +func (logStreamFile *LogStreamFile) GetLogStreamEnum() LogStreamEnum { + return LogStreamFileType +} + +// LogStreamEmpty The log is written nowhere +type LogStreamEmpty struct { + tdCommon +} + +// MessageType return the string telegram-type of LogStreamEmpty +func (logStreamEmpty *LogStreamEmpty) MessageType() string { + return "logStreamEmpty" +} + +// NewLogStreamEmpty creates a new LogStreamEmpty +// +func NewLogStreamEmpty() *LogStreamEmpty { + logStreamEmptyTemp := LogStreamEmpty{ + tdCommon: tdCommon{Type: "logStreamEmpty"}, + } + + return &logStreamEmptyTemp +} + +// GetLogStreamEnum return the enum type of this object +func (logStreamEmpty *LogStreamEmpty) GetLogStreamEnum() LogStreamEnum { + return LogStreamEmptyType +} diff --git a/tdlib/logTags.go b/tdlib/logTags.go new file mode 100644 index 0000000..5c0dbca --- /dev/null +++ b/tdlib/logTags.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// LogTags Contains a list of available TDLib internal log tags +type LogTags struct { + tdCommon + Tags []string `json:"tags"` // List of log tags +} + +// MessageType return the string telegram-type of LogTags +func (logTags *LogTags) MessageType() string { + return "logTags" +} + +// NewLogTags creates a new LogTags +// +// @param tags List of log tags +func NewLogTags(tags []string) *LogTags { + logTagsTemp := LogTags{ + tdCommon: tdCommon{Type: "logTags"}, + Tags: tags, + } + + return &logTagsTemp +} diff --git a/tdlib/logVerbosityLevel.go b/tdlib/logVerbosityLevel.go new file mode 100644 index 0000000..9328b54 --- /dev/null +++ b/tdlib/logVerbosityLevel.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// LogVerbosityLevel Contains a TDLib internal log verbosity level +type LogVerbosityLevel struct { + tdCommon + VerbosityLevel int32 `json:"verbosity_level"` // Log verbosity level +} + +// MessageType return the string telegram-type of LogVerbosityLevel +func (logVerbosityLevel *LogVerbosityLevel) MessageType() string { + return "logVerbosityLevel" +} + +// NewLogVerbosityLevel creates a new LogVerbosityLevel +// +// @param verbosityLevel Log verbosity level +func NewLogVerbosityLevel(verbosityLevel int32) *LogVerbosityLevel { + logVerbosityLevelTemp := LogVerbosityLevel{ + tdCommon: tdCommon{Type: "logVerbosityLevel"}, + VerbosityLevel: verbosityLevel, + } + + return &logVerbosityLevelTemp +} diff --git a/tdlib/loginURLInfo.go b/tdlib/loginURLInfo.go new file mode 100644 index 0000000..baab3af --- /dev/null +++ b/tdlib/loginURLInfo.go @@ -0,0 +1,95 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// LoginURLInfo Contains information about an inline button of type inlineKeyboardButtonTypeLoginUrl +type LoginURLInfo interface { + GetLoginURLInfoEnum() LoginURLInfoEnum +} + +// LoginURLInfoEnum Alias for abstract LoginURLInfo 'Sub-Classes', used as constant-enum here +type LoginURLInfoEnum string + +// LoginURLInfo enums +const () + +func unmarshalLoginURLInfo(rawMsg *json.RawMessage) (LoginURLInfo, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch LoginURLInfoEnum(objMap["@type"].(string)) { + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// LoginURLInfoOpen An HTTP url needs to be open +type LoginURLInfoOpen struct { + tdCommon + URL string `json:"url"` // The URL to open + SkipConfirm bool `json:"skip_confirm"` // True, if there is no need to show an ordinary open URL confirm +} + +// MessageType return the string telegram-type of LoginURLInfoOpen +func (loginURLInfoOpen *LoginURLInfoOpen) MessageType() string { + return "loginUrlInfoOpen" +} + +// NewLoginURLInfoOpen creates a new LoginURLInfoOpen +// +// @param uRL The URL to open +// @param skipConfirm True, if there is no need to show an ordinary open URL confirm +func NewLoginURLInfoOpen(uRL string, skipConfirm bool) *LoginURLInfoOpen { + loginURLInfoOpenTemp := LoginURLInfoOpen{ + tdCommon: tdCommon{Type: "loginUrlInfoOpen"}, + URL: uRL, + SkipConfirm: skipConfirm, + } + + return &loginURLInfoOpenTemp +} + +// LoginURLInfoRequestConfirmation An authorization confirmation dialog needs to be shown to the user +type LoginURLInfoRequestConfirmation struct { + tdCommon + URL string `json:"url"` // An HTTP URL to be opened + Domain string `json:"domain"` // A domain of the URL + BotUserID int64 `json:"bot_user_id"` // User identifier of a bot linked with the website + RequestWriteAccess bool `json:"request_write_access"` // True, if the user needs to be requested to give the permission to the bot to send them messages +} + +// MessageType return the string telegram-type of LoginURLInfoRequestConfirmation +func (loginURLInfoRequestConfirmation *LoginURLInfoRequestConfirmation) MessageType() string { + return "loginUrlInfoRequestConfirmation" +} + +// NewLoginURLInfoRequestConfirmation creates a new LoginURLInfoRequestConfirmation +// +// @param uRL An HTTP URL to be opened +// @param domain A domain of the URL +// @param botUserID User identifier of a bot linked with the website +// @param requestWriteAccess True, if the user needs to be requested to give the permission to the bot to send them messages +func NewLoginURLInfoRequestConfirmation(uRL string, domain string, botUserID int64, requestWriteAccess bool) *LoginURLInfoRequestConfirmation { + loginURLInfoRequestConfirmationTemp := LoginURLInfoRequestConfirmation{ + tdCommon: tdCommon{Type: "loginUrlInfoRequestConfirmation"}, + URL: uRL, + Domain: domain, + BotUserID: botUserID, + RequestWriteAccess: requestWriteAccess, + } + + return &loginURLInfoRequestConfirmationTemp +} diff --git a/tdlib/maskPoint.go b/tdlib/maskPoint.go new file mode 100644 index 0000000..3efca39 --- /dev/null +++ b/tdlib/maskPoint.go @@ -0,0 +1,161 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// MaskPoint Part of the face, relative to which a mask should be placed +type MaskPoint interface { + GetMaskPointEnum() MaskPointEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/maskPosition.go b/tdlib/maskPosition.go new file mode 100644 index 0000000..9cbf0ca --- /dev/null +++ b/tdlib/maskPosition.go @@ -0,0 +1,68 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/message.go b/tdlib/message.go new file mode 100644 index 0000000..ffca190 --- /dev/null +++ b/tdlib/message.go @@ -0,0 +1,222 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "log" +) + +// Message Describes a message +type Message struct { + tdCommon + ID int64 `json:"id"` // Message identifier; unique for the chat to which the message belongs + Sender []MessageSender `json:"sender"` // The sender of the message + ChatID int64 `json:"chat_id"` // Chat identifier + SendingState MessageSendingState `json:"sending_state"` // Information about the sending state of the message; may be null + SchedulingState MessageSchedulingState `json:"scheduling_state"` // Information about the scheduling state of the message; may be null + IsOutgoing bool `json:"is_outgoing"` // True, if the message is outgoing + IsPinned bool `json:"is_pinned"` // True, if the message is pinned + CanBeEdited bool `json:"can_be_edited"` // True, if the message can be edited. For live location and poll messages this fields shows whether editMessageLiveLocation or stopPoll can be used with this message by the application + 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 + CanGetStatistics bool `json:"can_get_statistics"` // True, if the message statistics are available + CanGetMessageThread bool `json:"can_get_message_thread"` // True, if the message thread info is available + CanGetMediaTimestampLinks bool `json:"can_get_media_timestamp_links"` // True, if media timestamp links can be generated for media timestamp entities in the message text, caption or web page description + HasTimestampedMedia bool `json:"has_timestamped_media"` // True, if media timestamp entities refers to a media in this message as opposed to a media in the replied message + 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 + InteractionInfo *MessageInteractionInfo `json:"interaction_info"` // Information about interactions with the message; may be null + ReplyInChatID int64 `json:"reply_in_chat_id"` // If non-zero, the identifier of the chat to which the replied message belongs; Currently, only messages in the Replies chat can have different reply_in_chat_id and chat_id + 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 + MessageThreadID int64 `json:"message_thread_id"` // If non-zero, the identifier of the message thread the message belongs to; unique within the chat to which the message belongs + 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. If the TTL timer isn't started yet, equals to the value of the ttl field + ViaBotUserID int64 `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 and anonymous group messages, optional author signature + MediaAlbumID JSONInt64 `json:"media_album_id"` // Unique identifier of an album this message belongs to. Only audios, documents, photos and videos can be grouped together in albums + RestrictionReason string `json:"restriction_reason"` // If non-empty, contains a human-readable description of the reason why access to this message must be restricted + 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 sender The sender of the message +// @param chatID Chat identifier +// @param sendingState Information about the sending state of the message; may be null +// @param schedulingState Information about the scheduling state of the message; may be null +// @param isOutgoing True, if the message is outgoing +// @param isPinned True, if the message is pinned +// @param canBeEdited True, if the message can be edited. For live location and poll messages this fields shows whether editMessageLiveLocation or stopPoll can be used with this message by the application +// @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 canGetStatistics True, if the message statistics are available +// @param canGetMessageThread True, if the message thread info is available +// @param canGetMediaTimestampLinks True, if media timestamp links can be generated for media timestamp entities in the message text, caption or web page description +// @param hasTimestampedMedia True, if media timestamp entities refers to a media in this message as opposed to a media in the replied message +// @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 interactionInfo Information about interactions with the message; may be null +// @param replyInChatID If non-zero, the identifier of the chat to which the replied message belongs; Currently, only messages in the Replies chat can have different reply_in_chat_id and chat_id +// @param replyToMessageID If non-zero, the identifier of the message this message is replying to; can be the identifier of a deleted message +// @param messageThreadID If non-zero, the identifier of the message thread the message belongs to; unique within the chat to which the message belongs +// @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. If the TTL timer isn't started yet, equals to the value of the ttl field +// @param viaBotUserID If non-zero, the user identifier of the bot through which this message was sent +// @param authorSignature For channel posts and anonymous group messages, optional author signature +// @param mediaAlbumID Unique identifier of an album this message belongs to. Only audios, documents, photos and videos can be grouped together in albums +// @param restrictionReason If non-empty, contains a human-readable description of the reason why access to this message must be restricted +// @param content Content of the message +// @param replyMarkup Reply markup for the message; may be null +func NewMessage(iD int64, sender []MessageSender, chatID int64, sendingState MessageSendingState, schedulingState MessageSchedulingState, isOutgoing bool, isPinned bool, canBeEdited bool, canBeForwarded bool, canBeDeletedOnlyForSelf bool, canBeDeletedForAllUsers bool, canGetStatistics bool, canGetMessageThread bool, canGetMediaTimestampLinks bool, hasTimestampedMedia bool, isChannelPost bool, containsUnreadMention bool, date int32, editDate int32, forwardInfo *MessageForwardInfo, interactionInfo *MessageInteractionInfo, replyInChatID int64, replyToMessageID int64, messageThreadID int64, tTL int32, tTLExpiresIn float64, viaBotUserID int64, authorSignature string, mediaAlbumID JSONInt64, restrictionReason string, content MessageContent, replyMarkup ReplyMarkup) *Message { + messageTemp := Message{ + tdCommon: tdCommon{Type: "message"}, + ID: iD, + Sender: sender, + ChatID: chatID, + SendingState: sendingState, + SchedulingState: schedulingState, + IsOutgoing: isOutgoing, + IsPinned: isPinned, + CanBeEdited: canBeEdited, + CanBeForwarded: canBeForwarded, + CanBeDeletedOnlyForSelf: canBeDeletedOnlyForSelf, + CanBeDeletedForAllUsers: canBeDeletedForAllUsers, + CanGetStatistics: canGetStatistics, + CanGetMessageThread: canGetMessageThread, + CanGetMediaTimestampLinks: canGetMediaTimestampLinks, + HasTimestampedMedia: hasTimestampedMedia, + IsChannelPost: isChannelPost, + ContainsUnreadMention: containsUnreadMention, + Date: date, + EditDate: editDate, + ForwardInfo: forwardInfo, + InteractionInfo: interactionInfo, + ReplyInChatID: replyInChatID, + ReplyToMessageID: replyToMessageID, + MessageThreadID: messageThreadID, + TTL: tTL, + TTLExpiresIn: tTLExpiresIn, + ViaBotUserID: viaBotUserID, + AuthorSignature: authorSignature, + MediaAlbumID: mediaAlbumID, + RestrictionReason: restrictionReason, + 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 + ChatID int64 `json:"chat_id"` // Chat identifier + IsOutgoing bool `json:"is_outgoing"` // True, if the message is outgoing + IsPinned bool `json:"is_pinned"` // True, if the message is pinned + CanBeEdited bool `json:"can_be_edited"` // True, if the message can be edited. For live location and poll messages this fields shows whether editMessageLiveLocation or stopPoll can be used with this message by the application + 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 + CanGetStatistics bool `json:"can_get_statistics"` // True, if the message statistics are available + CanGetMessageThread bool `json:"can_get_message_thread"` // True, if the message thread info is available + CanGetMediaTimestampLinks bool `json:"can_get_media_timestamp_links"` // True, if media timestamp links can be generated for media timestamp entities in the message text, caption or web page description + HasTimestampedMedia bool `json:"has_timestamped_media"` // True, if media timestamp entities refers to a media in this message as opposed to a media in the replied message + 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 + InteractionInfo *MessageInteractionInfo `json:"interaction_info"` // Information about interactions with the message; may be null + ReplyInChatID int64 `json:"reply_in_chat_id"` // If non-zero, the identifier of the chat to which the replied message belongs; Currently, only messages in the Replies chat can have different reply_in_chat_id and chat_id + 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 + MessageThreadID int64 `json:"message_thread_id"` // If non-zero, the identifier of the message thread the message belongs to; unique within the chat to which the message belongs + 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. If the TTL timer isn't started yet, equals to the value of the ttl field + ViaBotUserID int64 `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 and anonymous group messages, optional author signature + MediaAlbumID JSONInt64 `json:"media_album_id"` // Unique identifier of an album this message belongs to. Only audios, documents, photos and videos can be grouped together in albums + RestrictionReason string `json:"restriction_reason"` // If non-empty, contains a human-readable description of the reason why access to this message must be restricted + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + log.Println(err) + return err + } + + message.tdCommon = tempObj.tdCommon + message.ID = tempObj.ID + message.ChatID = tempObj.ChatID + message.IsOutgoing = tempObj.IsOutgoing + message.IsPinned = tempObj.IsPinned + message.CanBeEdited = tempObj.CanBeEdited + message.CanBeForwarded = tempObj.CanBeForwarded + message.CanBeDeletedOnlyForSelf = tempObj.CanBeDeletedOnlyForSelf + message.CanBeDeletedForAllUsers = tempObj.CanBeDeletedForAllUsers + message.CanGetStatistics = tempObj.CanGetStatistics + message.CanGetMessageThread = tempObj.CanGetMessageThread + message.CanGetMediaTimestampLinks = tempObj.CanGetMediaTimestampLinks + message.HasTimestampedMedia = tempObj.HasTimestampedMedia + message.IsChannelPost = tempObj.IsChannelPost + message.ContainsUnreadMention = tempObj.ContainsUnreadMention + message.Date = tempObj.Date + message.EditDate = tempObj.EditDate + message.ForwardInfo = tempObj.ForwardInfo + message.InteractionInfo = tempObj.InteractionInfo + message.ReplyInChatID = tempObj.ReplyInChatID + message.ReplyToMessageID = tempObj.ReplyToMessageID + message.MessageThreadID = tempObj.MessageThreadID + message.TTL = tempObj.TTL + message.TTLExpiresIn = tempObj.TTLExpiresIn + message.ViaBotUserID = tempObj.ViaBotUserID + message.AuthorSignature = tempObj.AuthorSignature + message.MediaAlbumID = tempObj.MediaAlbumID + message.RestrictionReason = tempObj.RestrictionReason + + //fieldSender, _ := unmarshalMessageSender(objMap["sender"]) + //message.Sender = fieldSender + + var slicePoor []*json.RawMessage + err = json.Unmarshal(b, &slicePoor) + + fieldSenderMany, _ := unmarshalListOfMessageSender(slicePoor) + message.Sender = fieldSenderMany + + fieldSendingState, _ := unmarshalMessageSendingState(objMap["sending_state"]) + message.SendingState = fieldSendingState + + fieldSchedulingState, _ := unmarshalMessageSchedulingState(objMap["scheduling_state"]) + message.SchedulingState = fieldSchedulingState + + fieldContent, _ := unmarshalMessageContent(objMap["content"]) + message.Content = fieldContent + + fieldReplyMarkup, _ := unmarshalReplyMarkup(objMap["reply_markup"]) + message.ReplyMarkup = fieldReplyMarkup + + return nil +} + diff --git a/tdlib/messageContent.go b/tdlib/messageContent.go new file mode 100644 index 0000000..bd73cca --- /dev/null +++ b/tdlib/messageContent.go @@ -0,0 +1,1848 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// MessageContent Contains the content of a message +type MessageContent interface { + GetMessageContentEnum() MessageContentEnum +} + +// 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" + MessageDiceType MessageContentEnum = "messageDice" + MessageGameType MessageContentEnum = "messageGame" + MessagePollType MessageContentEnum = "messagePoll" + MessageInvoiceType MessageContentEnum = "messageInvoice" + MessageCallType MessageContentEnum = "messageCall" + MessageVoiceChatScheduledType MessageContentEnum = "messageVoiceChatScheduled" + MessageVoiceChatStartedType MessageContentEnum = "messageVoiceChatStarted" + MessageVoiceChatEndedType MessageContentEnum = "messageVoiceChatEnded" + MessageInviteVoiceChatParticipantsType MessageContentEnum = "messageInviteVoiceChatParticipants" + 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" + MessageChatSetThemeType MessageContentEnum = "messageChatSetTheme" + 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" + MessageProximityAlertTriggeredType MessageContentEnum = "messageProximityAlertTriggered" + MessageUnsupportedType MessageContentEnum = "messageUnsupported" +) + +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 MessageDiceType: + var messageDice MessageDice + err := json.Unmarshal(*rawMsg, &messageDice) + return &messageDice, err + + case MessageGameType: + var messageGame MessageGame + err := json.Unmarshal(*rawMsg, &messageGame) + return &messageGame, err + + case MessagePollType: + var messagePoll MessagePoll + err := json.Unmarshal(*rawMsg, &messagePoll) + return &messagePoll, 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 MessageVoiceChatScheduledType: + var messageVoiceChatScheduled MessageVoiceChatScheduled + err := json.Unmarshal(*rawMsg, &messageVoiceChatScheduled) + return &messageVoiceChatScheduled, err + + case MessageVoiceChatStartedType: + var messageVoiceChatStarted MessageVoiceChatStarted + err := json.Unmarshal(*rawMsg, &messageVoiceChatStarted) + return &messageVoiceChatStarted, err + + case MessageVoiceChatEndedType: + var messageVoiceChatEnded MessageVoiceChatEnded + err := json.Unmarshal(*rawMsg, &messageVoiceChatEnded) + return &messageVoiceChatEnded, err + + case MessageInviteVoiceChatParticipantsType: + var messageInviteVoiceChatParticipants MessageInviteVoiceChatParticipants + err := json.Unmarshal(*rawMsg, &messageInviteVoiceChatParticipants) + return &messageInviteVoiceChatParticipants, 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 MessageChatSetThemeType: + var messageChatSetTheme MessageChatSetTheme + err := json.Unmarshal(*rawMsg, &messageChatSetTheme) + return &messageChatSetTheme, 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 MessageProximityAlertTriggeredType: + var messageProximityAlertTriggered MessageProximityAlertTriggered + err := json.Unmarshal(*rawMsg, &messageProximityAlertTriggered) + return &messageProximityAlertTriggered, 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)) + } +} + +// 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"` // The animation description + 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 The animation description +// @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"` // The audio description + 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 The audio description +// @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"` // The document description + 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 The document description +// @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"` // The photo description + 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 The photo description +// @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"` // The sticker description +} + +// MessageType return the string telegram-type of MessageSticker +func (messageSticker *MessageSticker) MessageType() string { + return "messageSticker" +} + +// NewMessageSticker creates a new MessageSticker +// +// @param sticker The sticker description +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"` // The video description + 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 The video description +// @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"` // The video note description + 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 The video note description +// @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"` // The voice note description + 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 The voice note description +// @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"` // The location description + LivePeriod int32 `json:"live_period"` // Time relative to the message send date, for 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 + Heading int32 `json:"heading"` // For live locations, a direction in which the location moves, in degrees; 1-360. If 0 the direction is unknown + ProximityAlertRadius int32 `json:"proximity_alert_radius"` // For live locations, a maximum distance to another chat member for proximity alerts, in meters (0-100000). 0 if the notification is disabled. Available only for the message sender +} + +// MessageType return the string telegram-type of MessageLocation +func (messageLocation *MessageLocation) MessageType() string { + return "messageLocation" +} + +// NewMessageLocation creates a new MessageLocation +// +// @param location The location description +// @param livePeriod Time relative to the message send date, for 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 +// @param heading For live locations, a direction in which the location moves, in degrees; 1-360. If 0 the direction is unknown +// @param proximityAlertRadius For live locations, a maximum distance to another chat member for proximity alerts, in meters (0-100000). 0 if the notification is disabled. Available only for the message sender +func NewMessageLocation(location *Location, livePeriod int32, expiresIn int32, heading int32, proximityAlertRadius int32) *MessageLocation { + messageLocationTemp := MessageLocation{ + tdCommon: tdCommon{Type: "messageLocation"}, + Location: location, + LivePeriod: livePeriod, + ExpiresIn: expiresIn, + Heading: heading, + ProximityAlertRadius: proximityAlertRadius, + } + + 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"` // The venue description +} + +// MessageType return the string telegram-type of MessageVenue +func (messageVenue *MessageVenue) MessageType() string { + return "messageVenue" +} + +// NewMessageVenue creates a new MessageVenue +// +// @param venue The venue description +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"` // The contact description +} + +// MessageType return the string telegram-type of MessageContact +func (messageContact *MessageContact) MessageType() string { + return "messageContact" +} + +// NewMessageContact creates a new MessageContact +// +// @param contact The contact description +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 +} + +// MessageDice A dice message. The dice value is randomly generated by the server +type MessageDice struct { + tdCommon + InitialState DiceStickers `json:"initial_state"` // The animated stickers with the initial dice animation; may be null if unknown. updateMessageContent will be sent when the sticker became known + FinalState DiceStickers `json:"final_state"` // The animated stickers with the final dice animation; may be null if unknown. updateMessageContent will be sent when the sticker became known + Emoji string `json:"emoji"` // Emoji on which the dice throw animation is based + Value int32 `json:"value"` // The dice value. If the value is 0, the dice don't have final state yet + SuccessAnimationFrameNumber int32 `json:"success_animation_frame_number"` // Number of frame after which a success animation like a shower of confetti needs to be shown on updateMessageSendSucceeded +} + +// MessageType return the string telegram-type of MessageDice +func (messageDice *MessageDice) MessageType() string { + return "messageDice" +} + +// NewMessageDice creates a new MessageDice +// +// @param initialState The animated stickers with the initial dice animation; may be null if unknown. updateMessageContent will be sent when the sticker became known +// @param finalState The animated stickers with the final dice animation; may be null if unknown. updateMessageContent will be sent when the sticker became known +// @param emoji Emoji on which the dice throw animation is based +// @param value The dice value. If the value is 0, the dice don't have final state yet +// @param successAnimationFrameNumber Number of frame after which a success animation like a shower of confetti needs to be shown on updateMessageSendSucceeded +func NewMessageDice(initialState DiceStickers, finalState DiceStickers, emoji string, value int32, successAnimationFrameNumber int32) *MessageDice { + messageDiceTemp := MessageDice{ + tdCommon: tdCommon{Type: "messageDice"}, + InitialState: initialState, + FinalState: finalState, + Emoji: emoji, + Value: value, + SuccessAnimationFrameNumber: successAnimationFrameNumber, + } + + return &messageDiceTemp +} + +// UnmarshalJSON unmarshal to json +func (messageDice *MessageDice) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Emoji string `json:"emoji"` // Emoji on which the dice throw animation is based + Value int32 `json:"value"` // The dice value. If the value is 0, the dice don't have final state yet + SuccessAnimationFrameNumber int32 `json:"success_animation_frame_number"` // Number of frame after which a success animation like a shower of confetti needs to be shown on updateMessageSendSucceeded + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + messageDice.tdCommon = tempObj.tdCommon + messageDice.Emoji = tempObj.Emoji + messageDice.Value = tempObj.Value + messageDice.SuccessAnimationFrameNumber = tempObj.SuccessAnimationFrameNumber + + fieldInitialState, _ := unmarshalDiceStickers(objMap["initial_state"]) + messageDice.InitialState = fieldInitialState + + fieldFinalState, _ := unmarshalDiceStickers(objMap["final_state"]) + messageDice.FinalState = fieldFinalState + + return nil +} + +// GetMessageContentEnum return the enum type of this object +func (messageDice *MessageDice) GetMessageContentEnum() MessageContentEnum { + return MessageDiceType +} + +// MessageGame A message with a game +type MessageGame struct { + tdCommon + Game *Game `json:"game"` // The game description +} + +// MessageType return the string telegram-type of MessageGame +func (messageGame *MessageGame) MessageType() string { + return "messageGame" +} + +// NewMessageGame creates a new MessageGame +// +// @param game The game description +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 +} + +// MessagePoll A message with a poll +type MessagePoll struct { + tdCommon + Poll *Poll `json:"poll"` // The poll description +} + +// MessageType return the string telegram-type of MessagePoll +func (messagePoll *MessagePoll) MessageType() string { + return "messagePoll" +} + +// NewMessagePoll creates a new MessagePoll +// +// @param poll The poll description +func NewMessagePoll(poll *Poll) *MessagePoll { + messagePollTemp := MessagePoll{ + tdCommon: tdCommon{Type: "messagePoll"}, + Poll: poll, + } + + return &messagePollTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messagePoll *MessagePoll) GetMessageContentEnum() MessageContentEnum { + return MessagePollType +} + +// MessageInvoice A message with an invoice from a bot +type MessageInvoice struct { + tdCommon + Title string `json:"title"` // Product title + Description string `json:"description"` // Product 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 smallest units 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 Product description +// @param photo Product photo; may be null +// @param currency Currency for the product price +// @param totalAmount Product total price in the smallest units 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 + IsVideo bool `json:"is_video"` // True, if the call was a video call + 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 isVideo True, if the call was a video call +// @param discardReason Reason why the call was discarded +// @param duration Call duration, in seconds +func NewMessageCall(isVideo bool, discardReason CallDiscardReason, duration int32) *MessageCall { + messageCallTemp := MessageCall{ + tdCommon: tdCommon{Type: "messageCall"}, + IsVideo: isVideo, + 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 + IsVideo bool `json:"is_video"` // True, if the call was a video call + Duration int32 `json:"duration"` // Call duration, in seconds + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + messageCall.tdCommon = tempObj.tdCommon + messageCall.IsVideo = tempObj.IsVideo + 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 +} + +// MessageVoiceChatScheduled A new voice chat was scheduled +type MessageVoiceChatScheduled struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Identifier of the voice chat. The voice chat can be received through the method getGroupCall + StartDate int32 `json:"start_date"` // Point in time (Unix timestamp) when the group call is supposed to be started by an administrator +} + +// MessageType return the string telegram-type of MessageVoiceChatScheduled +func (messageVoiceChatScheduled *MessageVoiceChatScheduled) MessageType() string { + return "messageVoiceChatScheduled" +} + +// NewMessageVoiceChatScheduled creates a new MessageVoiceChatScheduled +// +// @param groupCallID Identifier of the voice chat. The voice chat can be received through the method getGroupCall +// @param startDate Point in time (Unix timestamp) when the group call is supposed to be started by an administrator +func NewMessageVoiceChatScheduled(groupCallID int32, startDate int32) *MessageVoiceChatScheduled { + messageVoiceChatScheduledTemp := MessageVoiceChatScheduled{ + tdCommon: tdCommon{Type: "messageVoiceChatScheduled"}, + GroupCallID: groupCallID, + StartDate: startDate, + } + + return &messageVoiceChatScheduledTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageVoiceChatScheduled *MessageVoiceChatScheduled) GetMessageContentEnum() MessageContentEnum { + return MessageVoiceChatScheduledType +} + +// MessageVoiceChatStarted A newly created voice chat +type MessageVoiceChatStarted struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Identifier of the voice chat. The voice chat can be received through the method getGroupCall +} + +// MessageType return the string telegram-type of MessageVoiceChatStarted +func (messageVoiceChatStarted *MessageVoiceChatStarted) MessageType() string { + return "messageVoiceChatStarted" +} + +// NewMessageVoiceChatStarted creates a new MessageVoiceChatStarted +// +// @param groupCallID Identifier of the voice chat. The voice chat can be received through the method getGroupCall +func NewMessageVoiceChatStarted(groupCallID int32) *MessageVoiceChatStarted { + messageVoiceChatStartedTemp := MessageVoiceChatStarted{ + tdCommon: tdCommon{Type: "messageVoiceChatStarted"}, + GroupCallID: groupCallID, + } + + return &messageVoiceChatStartedTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageVoiceChatStarted *MessageVoiceChatStarted) GetMessageContentEnum() MessageContentEnum { + return MessageVoiceChatStartedType +} + +// MessageVoiceChatEnded A message with information about an ended voice chat +type MessageVoiceChatEnded struct { + tdCommon + Duration int32 `json:"duration"` // Call duration, in seconds +} + +// MessageType return the string telegram-type of MessageVoiceChatEnded +func (messageVoiceChatEnded *MessageVoiceChatEnded) MessageType() string { + return "messageVoiceChatEnded" +} + +// NewMessageVoiceChatEnded creates a new MessageVoiceChatEnded +// +// @param duration Call duration, in seconds +func NewMessageVoiceChatEnded(duration int32) *MessageVoiceChatEnded { + messageVoiceChatEndedTemp := MessageVoiceChatEnded{ + tdCommon: tdCommon{Type: "messageVoiceChatEnded"}, + Duration: duration, + } + + return &messageVoiceChatEndedTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageVoiceChatEnded *MessageVoiceChatEnded) GetMessageContentEnum() MessageContentEnum { + return MessageVoiceChatEndedType +} + +// MessageInviteVoiceChatParticipants A message with information about an invite to a voice chat +type MessageInviteVoiceChatParticipants struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Identifier of the voice chat. The voice chat can be received through the method getGroupCall + UserIDs []int64 `json:"user_ids"` // Invited user identifiers +} + +// MessageType return the string telegram-type of MessageInviteVoiceChatParticipants +func (messageInviteVoiceChatParticipants *MessageInviteVoiceChatParticipants) MessageType() string { + return "messageInviteVoiceChatParticipants" +} + +// NewMessageInviteVoiceChatParticipants creates a new MessageInviteVoiceChatParticipants +// +// @param groupCallID Identifier of the voice chat. The voice chat can be received through the method getGroupCall +// @param userIDs Invited user identifiers +func NewMessageInviteVoiceChatParticipants(groupCallID int32, userIDs []int64) *MessageInviteVoiceChatParticipants { + messageInviteVoiceChatParticipantsTemp := MessageInviteVoiceChatParticipants{ + tdCommon: tdCommon{Type: "messageInviteVoiceChatParticipants"}, + GroupCallID: groupCallID, + UserIDs: userIDs, + } + + return &messageInviteVoiceChatParticipantsTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageInviteVoiceChatParticipants *MessageInviteVoiceChatParticipants) GetMessageContentEnum() MessageContentEnum { + return MessageInviteVoiceChatParticipantsType +} + +// MessageBasicGroupChatCreate A newly created basic group +type MessageBasicGroupChatCreate struct { + tdCommon + Title string `json:"title"` // Title of the basic group + MemberUserIDs []int64 `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 []int64) *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 *ChatPhoto `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 *ChatPhoto) *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 []int64 `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 []int64) *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 int64 `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 int64) *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 int64 `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 int64) *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 int64 `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 int64) *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 or 0 +} + +// 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 or 0 +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 +} + +// MessageChatSetTheme A theme in the chat has been changed +type MessageChatSetTheme struct { + tdCommon + ThemeName string `json:"theme_name"` // If non-empty, name of a new theme set for the chat. Otherwise chat theme was reset to the default one +} + +// MessageType return the string telegram-type of MessageChatSetTheme +func (messageChatSetTheme *MessageChatSetTheme) MessageType() string { + return "messageChatSetTheme" +} + +// NewMessageChatSetTheme creates a new MessageChatSetTheme +// +// @param themeName If non-empty, name of a new theme set for the chat. Otherwise chat theme was reset to the default one +func NewMessageChatSetTheme(themeName string) *MessageChatSetTheme { + messageChatSetThemeTemp := MessageChatSetTheme{ + tdCommon: tdCommon{Type: "messageChatSetTheme"}, + ThemeName: themeName, + } + + return &messageChatSetThemeTemp +} + +// GetMessageContentEnum return the enum type of this object +func (messageChatSetTheme *MessageChatSetTheme) GetMessageContentEnum() MessageContentEnum { + return MessageChatSetThemeType +} + +// MessageChatSetTTL The TTL (Time To Live) setting for messages in the chat has been changed +type MessageChatSetTTL struct { + tdCommon + TTL int32 `json:"ttl"` // New message TTL setting +} + +// MessageType return the string telegram-type of MessageChatSetTTL +func (messageChatSetTTL *MessageChatSetTTL) MessageType() string { + return "messageChatSetTtl" +} + +// NewMessageChatSetTTL creates a new MessageChatSetTTL +// +// @param tTL New message TTL setting +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 + InvoiceChatID int64 `json:"invoice_chat_id"` // Identifier of the chat, containing the corresponding invoice message; 0 if unknown + 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 smallest units of the currency +} + +// MessageType return the string telegram-type of MessagePaymentSuccessful +func (messagePaymentSuccessful *MessagePaymentSuccessful) MessageType() string { + return "messagePaymentSuccessful" +} + +// NewMessagePaymentSuccessful creates a new MessagePaymentSuccessful +// +// @param invoiceChatID Identifier of the chat, containing the corresponding invoice message; 0 if unknown +// @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 smallest units of the currency +func NewMessagePaymentSuccessful(invoiceChatID int64, invoiceMessageID int64, currency string, totalAmount int64) *MessagePaymentSuccessful { + messagePaymentSuccessfulTemp := MessagePaymentSuccessful{ + tdCommon: tdCommon{Type: "messagePaymentSuccessful"}, + InvoiceChatID: invoiceChatID, + 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 + Currency string `json:"currency"` // Currency for price of the product + TotalAmount int64 `json:"total_amount"` // Total price for the product, in the smallest units 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 currency Currency for price of the product +// @param totalAmount Total price for the product, in the smallest units 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(currency string, totalAmount int64, invoicePayload []byte, shippingOptionID string, orderInfo *OrderInfo, telegramPaymentChargeID string, providerPaymentChargeID string) *MessagePaymentSuccessfulBot { + messagePaymentSuccessfulBotTemp := MessagePaymentSuccessfulBot{ + tdCommon: tdCommon{Type: "messagePaymentSuccessfulBot"}, + 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 +} + +// MessageProximityAlertTriggered A user in the chat came within proximity alert range +type MessageProximityAlertTriggered struct { + tdCommon + Traveler MessageSender `json:"traveler"` // The user or chat, which triggered the proximity alert + Watcher MessageSender `json:"watcher"` // The user or chat, which subscribed for the proximity alert + Distance int32 `json:"distance"` // The distance between the users +} + +// MessageType return the string telegram-type of MessageProximityAlertTriggered +func (messageProximityAlertTriggered *MessageProximityAlertTriggered) MessageType() string { + return "messageProximityAlertTriggered" +} + +// NewMessageProximityAlertTriggered creates a new MessageProximityAlertTriggered +// +// @param traveler The user or chat, which triggered the proximity alert +// @param watcher The user or chat, which subscribed for the proximity alert +// @param distance The distance between the users +func NewMessageProximityAlertTriggered(traveler MessageSender, watcher MessageSender, distance int32) *MessageProximityAlertTriggered { + messageProximityAlertTriggeredTemp := MessageProximityAlertTriggered{ + tdCommon: tdCommon{Type: "messageProximityAlertTriggered"}, + Traveler: traveler, + Watcher: watcher, + Distance: distance, + } + + return &messageProximityAlertTriggeredTemp +} + +// UnmarshalJSON unmarshal to json +func (messageProximityAlertTriggered *MessageProximityAlertTriggered) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Distance int32 `json:"distance"` // The distance between the users + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + messageProximityAlertTriggered.tdCommon = tempObj.tdCommon + messageProximityAlertTriggered.Distance = tempObj.Distance + + fieldTraveler, _ := unmarshalMessageSender(objMap["traveler"]) + messageProximityAlertTriggered.Traveler = fieldTraveler + + fieldWatcher, _ := unmarshalMessageSender(objMap["watcher"]) + messageProximityAlertTriggered.Watcher = fieldWatcher + + return nil +} + +// GetMessageContentEnum return the enum type of this object +func (messageProximityAlertTriggered *MessageProximityAlertTriggered) GetMessageContentEnum() MessageContentEnum { + return MessageProximityAlertTriggeredType +} + +// MessageUnsupported Message content that is not supported in the current TDLib version +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 +} diff --git a/tdlib/messageCopyOptions.go b/tdlib/messageCopyOptions.go new file mode 100644 index 0000000..2033877 --- /dev/null +++ b/tdlib/messageCopyOptions.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// MessageCopyOptions Options to be used when a message content is copied without a link to the original message. Service messages and messageInvoice can't be copied +type MessageCopyOptions struct { + tdCommon + SendCopy bool `json:"send_copy"` // True, if content of the message needs to be copied without a link to the original message. Always true if the message is forwarded to a secret chat + ReplaceCaption bool `json:"replace_caption"` // True, if media caption of the message copy needs to be replaced. Ignored if send_copy is false + NewCaption *FormattedText `json:"new_caption"` // New message caption. Ignored if replace_caption is false +} + +// MessageType return the string telegram-type of MessageCopyOptions +func (messageCopyOptions *MessageCopyOptions) MessageType() string { + return "messageCopyOptions" +} + +// NewMessageCopyOptions creates a new MessageCopyOptions +// +// @param sendCopy True, if content of the message needs to be copied without a link to the original message. Always true if the message is forwarded to a secret chat +// @param replaceCaption True, if media caption of the message copy needs to be replaced. Ignored if send_copy is false +// @param newCaption New message caption. Ignored if replace_caption is false +func NewMessageCopyOptions(sendCopy bool, replaceCaption bool, newCaption *FormattedText) *MessageCopyOptions { + messageCopyOptionsTemp := MessageCopyOptions{ + tdCommon: tdCommon{Type: "messageCopyOptions"}, + SendCopy: sendCopy, + ReplaceCaption: replaceCaption, + NewCaption: newCaption, + } + + return &messageCopyOptionsTemp +} diff --git a/tdlib/messageFileType.go b/tdlib/messageFileType.go new file mode 100644 index 0000000..836b724 --- /dev/null +++ b/tdlib/messageFileType.go @@ -0,0 +1,136 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// MessageFileType Contains information about a file with messages exported from another app +type MessageFileType interface { + GetMessageFileTypeEnum() MessageFileTypeEnum +} + +// MessageFileTypeEnum Alias for abstract MessageFileType 'Sub-Classes', used as constant-enum here +type MessageFileTypeEnum string + +// MessageFileType enums +const ( + MessageFileTypePrivateType MessageFileTypeEnum = "messageFileTypePrivate" + MessageFileTypeGroupType MessageFileTypeEnum = "messageFileTypeGroup" + MessageFileTypeUnknownType MessageFileTypeEnum = "messageFileTypeUnknown" +) + +func unmarshalMessageFileType(rawMsg *json.RawMessage) (MessageFileType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MessageFileTypeEnum(objMap["@type"].(string)) { + case MessageFileTypePrivateType: + var messageFileTypePrivate MessageFileTypePrivate + err := json.Unmarshal(*rawMsg, &messageFileTypePrivate) + return &messageFileTypePrivate, err + + case MessageFileTypeGroupType: + var messageFileTypeGroup MessageFileTypeGroup + err := json.Unmarshal(*rawMsg, &messageFileTypeGroup) + return &messageFileTypeGroup, err + + case MessageFileTypeUnknownType: + var messageFileTypeUnknown MessageFileTypeUnknown + err := json.Unmarshal(*rawMsg, &messageFileTypeUnknown) + return &messageFileTypeUnknown, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// MessageFileTypePrivate The messages was exported from a private chat +type MessageFileTypePrivate struct { + tdCommon + Name string `json:"name"` // Name of the other party; may be empty if unrecognized +} + +// MessageType return the string telegram-type of MessageFileTypePrivate +func (messageFileTypePrivate *MessageFileTypePrivate) MessageType() string { + return "messageFileTypePrivate" +} + +// NewMessageFileTypePrivate creates a new MessageFileTypePrivate +// +// @param name Name of the other party; may be empty if unrecognized +func NewMessageFileTypePrivate(name string) *MessageFileTypePrivate { + messageFileTypePrivateTemp := MessageFileTypePrivate{ + tdCommon: tdCommon{Type: "messageFileTypePrivate"}, + Name: name, + } + + return &messageFileTypePrivateTemp +} + +// GetMessageFileTypeEnum return the enum type of this object +func (messageFileTypePrivate *MessageFileTypePrivate) GetMessageFileTypeEnum() MessageFileTypeEnum { + return MessageFileTypePrivateType +} + +// MessageFileTypeGroup The messages was exported from a group chat +type MessageFileTypeGroup struct { + tdCommon + Title string `json:"title"` // Title of the group chat; may be empty if unrecognized +} + +// MessageType return the string telegram-type of MessageFileTypeGroup +func (messageFileTypeGroup *MessageFileTypeGroup) MessageType() string { + return "messageFileTypeGroup" +} + +// NewMessageFileTypeGroup creates a new MessageFileTypeGroup +// +// @param title Title of the group chat; may be empty if unrecognized +func NewMessageFileTypeGroup(title string) *MessageFileTypeGroup { + messageFileTypeGroupTemp := MessageFileTypeGroup{ + tdCommon: tdCommon{Type: "messageFileTypeGroup"}, + Title: title, + } + + return &messageFileTypeGroupTemp +} + +// GetMessageFileTypeEnum return the enum type of this object +func (messageFileTypeGroup *MessageFileTypeGroup) GetMessageFileTypeEnum() MessageFileTypeEnum { + return MessageFileTypeGroupType +} + +// MessageFileTypeUnknown The messages was exported from a chat of unknown type +type MessageFileTypeUnknown struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageFileTypeUnknown +func (messageFileTypeUnknown *MessageFileTypeUnknown) MessageType() string { + return "messageFileTypeUnknown" +} + +// NewMessageFileTypeUnknown creates a new MessageFileTypeUnknown +// +func NewMessageFileTypeUnknown() *MessageFileTypeUnknown { + messageFileTypeUnknownTemp := MessageFileTypeUnknown{ + tdCommon: tdCommon{Type: "messageFileTypeUnknown"}, + } + + return &messageFileTypeUnknownTemp +} + +// GetMessageFileTypeEnum return the enum type of this object +func (messageFileTypeUnknown *MessageFileTypeUnknown) GetMessageFileTypeEnum() MessageFileTypeEnum { + return MessageFileTypeUnknownType +} diff --git a/tdlib/messageForwardInfo.go b/tdlib/messageForwardInfo.go new file mode 100644 index 0000000..ab3a7bd --- /dev/null +++ b/tdlib/messageForwardInfo.go @@ -0,0 +1,73 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// MessageForwardInfo Contains information about a forwarded message +type MessageForwardInfo struct { + tdCommon + Origin MessageForwardOrigin `json:"origin"` // Origin of a forwarded message + Date int32 `json:"date"` // Point in time (Unix timestamp) when the message was originally sent + PublicServiceAnnouncementType string `json:"public_service_announcement_type"` // The type of a public service announcement for the forwarded message + FromChatID int64 `json:"from_chat_id"` // For messages forwarded to the chat with the current user (Saved Messages), to the Replies bot chat, or to the channel's discussion group, the identifier of the chat from which the message was forwarded last time; 0 if unknown + FromMessageID int64 `json:"from_message_id"` // For messages forwarded to the chat with the current user (Saved Messages), to the Replies bot chat, or to the channel's discussion group, the identifier of the original message from which the new message was forwarded last time; 0 if unknown +} + +// MessageType return the string telegram-type of MessageForwardInfo +func (messageForwardInfo *MessageForwardInfo) MessageType() string { + return "messageForwardInfo" +} + +// NewMessageForwardInfo creates a new MessageForwardInfo +// +// @param origin Origin of a forwarded message +// @param date Point in time (Unix timestamp) when the message was originally sent +// @param publicServiceAnnouncementType The type of a public service announcement for the forwarded message +// @param fromChatID For messages forwarded to the chat with the current user (Saved Messages), to the Replies bot chat, or to the channel's discussion group, the identifier of the chat from which the message was forwarded last time; 0 if unknown +// @param fromMessageID For messages forwarded to the chat with the current user (Saved Messages), to the Replies bot chat, or to the channel's discussion group, the identifier of the original message from which the new message was forwarded last time; 0 if unknown +func NewMessageForwardInfo(origin MessageForwardOrigin, date int32, publicServiceAnnouncementType string, fromChatID int64, fromMessageID int64) *MessageForwardInfo { + messageForwardInfoTemp := MessageForwardInfo{ + tdCommon: tdCommon{Type: "messageForwardInfo"}, + Origin: origin, + Date: date, + PublicServiceAnnouncementType: publicServiceAnnouncementType, + FromChatID: fromChatID, + FromMessageID: fromMessageID, + } + + return &messageForwardInfoTemp +} + +// UnmarshalJSON unmarshal to json +func (messageForwardInfo *MessageForwardInfo) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Date int32 `json:"date"` // Point in time (Unix timestamp) when the message was originally sent + PublicServiceAnnouncementType string `json:"public_service_announcement_type"` // The type of a public service announcement for the forwarded message + FromChatID int64 `json:"from_chat_id"` // For messages forwarded to the chat with the current user (Saved Messages), to the Replies bot chat, or to the channel's discussion group, the identifier of the chat from which the message was forwarded last time; 0 if unknown + FromMessageID int64 `json:"from_message_id"` // For messages forwarded to the chat with the current user (Saved Messages), to the Replies bot chat, or to the channel's discussion group, the identifier of the original message from which the new message was forwarded last time; 0 if unknown + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + messageForwardInfo.tdCommon = tempObj.tdCommon + messageForwardInfo.Date = tempObj.Date + messageForwardInfo.PublicServiceAnnouncementType = tempObj.PublicServiceAnnouncementType + messageForwardInfo.FromChatID = tempObj.FromChatID + messageForwardInfo.FromMessageID = tempObj.FromMessageID + + fieldOrigin, _ := unmarshalMessageForwardOrigin(objMap["origin"]) + messageForwardInfo.Origin = fieldOrigin + + return nil +} diff --git a/tdlib/messageForwardOrigin.go b/tdlib/messageForwardOrigin.go new file mode 100644 index 0000000..02b3299 --- /dev/null +++ b/tdlib/messageForwardOrigin.go @@ -0,0 +1,216 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// MessageForwardOrigin Contains information about the origin of a forwarded message +type MessageForwardOrigin interface { + GetMessageForwardOriginEnum() MessageForwardOriginEnum +} + +// MessageForwardOriginEnum Alias for abstract MessageForwardOrigin 'Sub-Classes', used as constant-enum here +type MessageForwardOriginEnum string + +// MessageForwardOrigin enums +const ( + MessageForwardOriginUserType MessageForwardOriginEnum = "messageForwardOriginUser" + MessageForwardOriginChatType MessageForwardOriginEnum = "messageForwardOriginChat" + MessageForwardOriginHiddenUserType MessageForwardOriginEnum = "messageForwardOriginHiddenUser" + MessageForwardOriginChannelType MessageForwardOriginEnum = "messageForwardOriginChannel" + MessageForwardOriginMessageImportType MessageForwardOriginEnum = "messageForwardOriginMessageImport" +) + +func unmarshalMessageForwardOrigin(rawMsg *json.RawMessage) (MessageForwardOrigin, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MessageForwardOriginEnum(objMap["@type"].(string)) { + case MessageForwardOriginUserType: + var messageForwardOriginUser MessageForwardOriginUser + err := json.Unmarshal(*rawMsg, &messageForwardOriginUser) + return &messageForwardOriginUser, err + + case MessageForwardOriginChatType: + var messageForwardOriginChat MessageForwardOriginChat + err := json.Unmarshal(*rawMsg, &messageForwardOriginChat) + return &messageForwardOriginChat, err + + case MessageForwardOriginHiddenUserType: + var messageForwardOriginHiddenUser MessageForwardOriginHiddenUser + err := json.Unmarshal(*rawMsg, &messageForwardOriginHiddenUser) + return &messageForwardOriginHiddenUser, err + + case MessageForwardOriginChannelType: + var messageForwardOriginChannel MessageForwardOriginChannel + err := json.Unmarshal(*rawMsg, &messageForwardOriginChannel) + return &messageForwardOriginChannel, err + + case MessageForwardOriginMessageImportType: + var messageForwardOriginMessageImport MessageForwardOriginMessageImport + err := json.Unmarshal(*rawMsg, &messageForwardOriginMessageImport) + return &messageForwardOriginMessageImport, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// MessageForwardOriginUser The message was originally sent by a known user +type MessageForwardOriginUser struct { + tdCommon + SenderUserID int64 `json:"sender_user_id"` // Identifier of the user that originally sent the message +} + +// MessageType return the string telegram-type of MessageForwardOriginUser +func (messageForwardOriginUser *MessageForwardOriginUser) MessageType() string { + return "messageForwardOriginUser" +} + +// NewMessageForwardOriginUser creates a new MessageForwardOriginUser +// +// @param senderUserID Identifier of the user that originally sent the message +func NewMessageForwardOriginUser(senderUserID int64) *MessageForwardOriginUser { + messageForwardOriginUserTemp := MessageForwardOriginUser{ + tdCommon: tdCommon{Type: "messageForwardOriginUser"}, + SenderUserID: senderUserID, + } + + return &messageForwardOriginUserTemp +} + +// GetMessageForwardOriginEnum return the enum type of this object +func (messageForwardOriginUser *MessageForwardOriginUser) GetMessageForwardOriginEnum() MessageForwardOriginEnum { + return MessageForwardOriginUserType +} + +// MessageForwardOriginChat The message was originally sent by an anonymous chat administrator on behalf of the chat +type MessageForwardOriginChat struct { + tdCommon + SenderChatID int64 `json:"sender_chat_id"` // Identifier of the chat that originally sent the message + AuthorSignature string `json:"author_signature"` // Original message author signature +} + +// MessageType return the string telegram-type of MessageForwardOriginChat +func (messageForwardOriginChat *MessageForwardOriginChat) MessageType() string { + return "messageForwardOriginChat" +} + +// NewMessageForwardOriginChat creates a new MessageForwardOriginChat +// +// @param senderChatID Identifier of the chat that originally sent the message +// @param authorSignature Original message author signature +func NewMessageForwardOriginChat(senderChatID int64, authorSignature string) *MessageForwardOriginChat { + messageForwardOriginChatTemp := MessageForwardOriginChat{ + tdCommon: tdCommon{Type: "messageForwardOriginChat"}, + SenderChatID: senderChatID, + AuthorSignature: authorSignature, + } + + return &messageForwardOriginChatTemp +} + +// GetMessageForwardOriginEnum return the enum type of this object +func (messageForwardOriginChat *MessageForwardOriginChat) GetMessageForwardOriginEnum() MessageForwardOriginEnum { + return MessageForwardOriginChatType +} + +// MessageForwardOriginHiddenUser The message was originally sent by a user, which is hidden by their privacy settings +type MessageForwardOriginHiddenUser struct { + tdCommon + SenderName string `json:"sender_name"` // Name of the sender +} + +// MessageType return the string telegram-type of MessageForwardOriginHiddenUser +func (messageForwardOriginHiddenUser *MessageForwardOriginHiddenUser) MessageType() string { + return "messageForwardOriginHiddenUser" +} + +// NewMessageForwardOriginHiddenUser creates a new MessageForwardOriginHiddenUser +// +// @param senderName Name of the sender +func NewMessageForwardOriginHiddenUser(senderName string) *MessageForwardOriginHiddenUser { + messageForwardOriginHiddenUserTemp := MessageForwardOriginHiddenUser{ + tdCommon: tdCommon{Type: "messageForwardOriginHiddenUser"}, + SenderName: senderName, + } + + return &messageForwardOriginHiddenUserTemp +} + +// GetMessageForwardOriginEnum return the enum type of this object +func (messageForwardOriginHiddenUser *MessageForwardOriginHiddenUser) GetMessageForwardOriginEnum() MessageForwardOriginEnum { + return MessageForwardOriginHiddenUserType +} + +// MessageForwardOriginChannel The message was originally a post in a channel +type MessageForwardOriginChannel struct { + tdCommon + ChatID int64 `json:"chat_id"` // Identifier of the chat from which the message was originally forwarded + MessageID int64 `json:"message_id"` // Message identifier of the original message + AuthorSignature string `json:"author_signature"` // Original post author signature +} + +// MessageType return the string telegram-type of MessageForwardOriginChannel +func (messageForwardOriginChannel *MessageForwardOriginChannel) MessageType() string { + return "messageForwardOriginChannel" +} + +// NewMessageForwardOriginChannel creates a new MessageForwardOriginChannel +// +// @param chatID Identifier of the chat from which the message was originally forwarded +// @param messageID Message identifier of the original message +// @param authorSignature Original post author signature +func NewMessageForwardOriginChannel(chatID int64, messageID int64, authorSignature string) *MessageForwardOriginChannel { + messageForwardOriginChannelTemp := MessageForwardOriginChannel{ + tdCommon: tdCommon{Type: "messageForwardOriginChannel"}, + ChatID: chatID, + MessageID: messageID, + AuthorSignature: authorSignature, + } + + return &messageForwardOriginChannelTemp +} + +// GetMessageForwardOriginEnum return the enum type of this object +func (messageForwardOriginChannel *MessageForwardOriginChannel) GetMessageForwardOriginEnum() MessageForwardOriginEnum { + return MessageForwardOriginChannelType +} + +// MessageForwardOriginMessageImport The message was imported from an exported message history +type MessageForwardOriginMessageImport struct { + tdCommon + SenderName string `json:"sender_name"` // Name of the sender +} + +// MessageType return the string telegram-type of MessageForwardOriginMessageImport +func (messageForwardOriginMessageImport *MessageForwardOriginMessageImport) MessageType() string { + return "messageForwardOriginMessageImport" +} + +// NewMessageForwardOriginMessageImport creates a new MessageForwardOriginMessageImport +// +// @param senderName Name of the sender +func NewMessageForwardOriginMessageImport(senderName string) *MessageForwardOriginMessageImport { + messageForwardOriginMessageImportTemp := MessageForwardOriginMessageImport{ + tdCommon: tdCommon{Type: "messageForwardOriginMessageImport"}, + SenderName: senderName, + } + + return &messageForwardOriginMessageImportTemp +} + +// GetMessageForwardOriginEnum return the enum type of this object +func (messageForwardOriginMessageImport *MessageForwardOriginMessageImport) GetMessageForwardOriginEnum() MessageForwardOriginEnum { + return MessageForwardOriginMessageImportType +} diff --git a/tdlib/messageInteractionInfo.go b/tdlib/messageInteractionInfo.go new file mode 100644 index 0000000..12871c8 --- /dev/null +++ b/tdlib/messageInteractionInfo.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// MessageInteractionInfo Contains information about interactions with a message +type MessageInteractionInfo struct { + tdCommon + ViewCount int32 `json:"view_count"` // Number of times the message was viewed + ForwardCount int32 `json:"forward_count"` // Number of times the message was forwarded + ReplyInfo *MessageReplyInfo `json:"reply_info"` // Contains information about direct or indirect replies to the message; may be null. Currently, available only in channels with a discussion supergroup and discussion supergroups for messages, which are not replies itself +} + +// MessageType return the string telegram-type of MessageInteractionInfo +func (messageInteractionInfo *MessageInteractionInfo) MessageType() string { + return "messageInteractionInfo" +} + +// NewMessageInteractionInfo creates a new MessageInteractionInfo +// +// @param viewCount Number of times the message was viewed +// @param forwardCount Number of times the message was forwarded +// @param replyInfo Contains information about direct or indirect replies to the message; may be null. Currently, available only in channels with a discussion supergroup and discussion supergroups for messages, which are not replies itself +func NewMessageInteractionInfo(viewCount int32, forwardCount int32, replyInfo *MessageReplyInfo) *MessageInteractionInfo { + messageInteractionInfoTemp := MessageInteractionInfo{ + tdCommon: tdCommon{Type: "messageInteractionInfo"}, + ViewCount: viewCount, + ForwardCount: forwardCount, + ReplyInfo: replyInfo, + } + + return &messageInteractionInfoTemp +} diff --git a/tdlib/messageLink.go b/tdlib/messageLink.go new file mode 100644 index 0000000..0342765 --- /dev/null +++ b/tdlib/messageLink.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// MessageLink Contains an HTTPS link to a message in a supergroup or channel +type MessageLink struct { + tdCommon + Link string `json:"link"` // Message link + IsPublic bool `json:"is_public"` // True, if the link will work for non-members of the chat +} + +// MessageType return the string telegram-type of MessageLink +func (messageLink *MessageLink) MessageType() string { + return "messageLink" +} + +// NewMessageLink creates a new MessageLink +// +// @param link Message link +// @param isPublic True, if the link will work for non-members of the chat +func NewMessageLink(link string, isPublic bool) *MessageLink { + messageLinkTemp := MessageLink{ + tdCommon: tdCommon{Type: "messageLink"}, + Link: link, + IsPublic: isPublic, + } + + return &messageLinkTemp +} diff --git a/tdlib/messageLinkInfo.go b/tdlib/messageLinkInfo.go new file mode 100644 index 0000000..b2fef9c --- /dev/null +++ b/tdlib/messageLinkInfo.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// MessageLinkInfo Contains information about a link to a message in a chat +type MessageLinkInfo struct { + tdCommon + IsPublic bool `json:"is_public"` // True, if the link is a public link for a message in a chat + ChatID int64 `json:"chat_id"` // If found, identifier of the chat to which the message belongs, 0 otherwise + Message *Message `json:"message"` // If found, the linked message; may be null + MediaTimestamp int32 `json:"media_timestamp"` // Timestamp from which the video/audio/video note/voice note playing should start, in seconds; 0 if not specified. The media can be in the message content or in its web page preview + ForAlbum bool `json:"for_album"` // True, if the whole media album to which the message belongs is linked + ForComment bool `json:"for_comment"` // True, if the message is linked as a channel post comment or from a message thread +} + +// MessageType return the string telegram-type of MessageLinkInfo +func (messageLinkInfo *MessageLinkInfo) MessageType() string { + return "messageLinkInfo" +} + +// NewMessageLinkInfo creates a new MessageLinkInfo +// +// @param isPublic True, if the link is a public link for a message in a chat +// @param chatID If found, identifier of the chat to which the message belongs, 0 otherwise +// @param message If found, the linked message; may be null +// @param mediaTimestamp Timestamp from which the video/audio/video note/voice note playing should start, in seconds; 0 if not specified. The media can be in the message content or in its web page preview +// @param forAlbum True, if the whole media album to which the message belongs is linked +// @param forComment True, if the message is linked as a channel post comment or from a message thread +func NewMessageLinkInfo(isPublic bool, chatID int64, message *Message, mediaTimestamp int32, forAlbum bool, forComment bool) *MessageLinkInfo { + messageLinkInfoTemp := MessageLinkInfo{ + tdCommon: tdCommon{Type: "messageLinkInfo"}, + IsPublic: isPublic, + ChatID: chatID, + Message: message, + MediaTimestamp: mediaTimestamp, + ForAlbum: forAlbum, + ForComment: forComment, + } + + return &messageLinkInfoTemp +} diff --git a/tdlib/messageReplyInfo.go b/tdlib/messageReplyInfo.go new file mode 100644 index 0000000..52bc4c0 --- /dev/null +++ b/tdlib/messageReplyInfo.go @@ -0,0 +1,68 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// MessageReplyInfo Contains information about replies to a message +type MessageReplyInfo struct { + tdCommon + ReplyCount int32 `json:"reply_count"` // Number of times the message was directly or indirectly replied + RecentRepliers []MessageSender `json:"recent_repliers"` // Recent repliers to the message; available in channels with a discussion supergroup + LastReadInboxMessageID int64 `json:"last_read_inbox_message_id"` // Identifier of the last read incoming reply to the message + LastReadOutboxMessageID int64 `json:"last_read_outbox_message_id"` // Identifier of the last read outgoing reply to the message + LastMessageID int64 `json:"last_message_id"` // Identifier of the last reply to the message +} + +// MessageType return the string telegram-type of MessageReplyInfo +func (messageReplyInfo *MessageReplyInfo) MessageType() string { + return "messageReplyInfo" +} + +// NewMessageReplyInfo creates a new MessageReplyInfo +// +// @param replyCount Number of times the message was directly or indirectly replied +// @param recentRepliers Recent repliers to the message; available in channels with a discussion supergroup +// @param lastReadInboxMessageID Identifier of the last read incoming reply to the message +// @param lastReadOutboxMessageID Identifier of the last read outgoing reply to the message +// @param lastMessageID Identifier of the last reply to the message +func NewMessageReplyInfo(replyCount int32, recentRepliers []MessageSender, lastReadInboxMessageID int64, lastReadOutboxMessageID int64, lastMessageID int64) *MessageReplyInfo { + messageReplyInfoTemp := MessageReplyInfo{ + tdCommon: tdCommon{Type: "messageReplyInfo"}, + ReplyCount: replyCount, + RecentRepliers: recentRepliers, + LastReadInboxMessageID: lastReadInboxMessageID, + LastReadOutboxMessageID: lastReadOutboxMessageID, + LastMessageID: lastMessageID, + } + + return &messageReplyInfoTemp +} + +// UnmarshalJSON unmarshal to json +func (messageReplyInfo *MessageReplyInfo) UnmarshalJSON(data []byte) error { + var tmp struct { + ReplyCount int32 `json:"reply_count"` + RecentRepliers []*json.RawMessage `json:"recent_repliers"` + LastReadInboxMessageId int64 `json:"last_read_inbox_message_id"` + LastReadOutboxMessageId int64 `json:"last_read_outbox_message_id"` + LastMessageId int64 `json:"last_message_id"` + } + + err := json.Unmarshal(data, &tmp) + if err != nil { + return err + } + + messageReplyInfo.ReplyCount = tmp.ReplyCount + messageReplyInfo.LastReadInboxMessageID = tmp.LastReadInboxMessageId + messageReplyInfo.LastReadOutboxMessageID = tmp.LastReadOutboxMessageId + messageReplyInfo.LastMessageID = tmp.LastMessageId + + fieldRecentRepliers, _ := unmarshalListOfMessageSender(tmp.RecentRepliers) + messageReplyInfo.RecentRepliers = fieldRecentRepliers + + return nil +} diff --git a/tdlib/messageSchedulingState.go b/tdlib/messageSchedulingState.go new file mode 100644 index 0000000..a223f01 --- /dev/null +++ b/tdlib/messageSchedulingState.go @@ -0,0 +1,102 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// MessageSchedulingState Contains information about the time when a scheduled message will be sent +type MessageSchedulingState interface { + GetMessageSchedulingStateEnum() MessageSchedulingStateEnum +} + +// MessageSchedulingStateEnum Alias for abstract MessageSchedulingState 'Sub-Classes', used as constant-enum here +type MessageSchedulingStateEnum string + +// MessageSchedulingState enums +const ( + MessageSchedulingStateSendAtDateType MessageSchedulingStateEnum = "messageSchedulingStateSendAtDate" + MessageSchedulingStateSendWhenOnlineType MessageSchedulingStateEnum = "messageSchedulingStateSendWhenOnline" +) + +func unmarshalMessageSchedulingState(rawMsg *json.RawMessage) (MessageSchedulingState, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MessageSchedulingStateEnum(objMap["@type"].(string)) { + case MessageSchedulingStateSendAtDateType: + var messageSchedulingStateSendAtDate MessageSchedulingStateSendAtDate + err := json.Unmarshal(*rawMsg, &messageSchedulingStateSendAtDate) + return &messageSchedulingStateSendAtDate, err + + case MessageSchedulingStateSendWhenOnlineType: + var messageSchedulingStateSendWhenOnline MessageSchedulingStateSendWhenOnline + err := json.Unmarshal(*rawMsg, &messageSchedulingStateSendWhenOnline) + return &messageSchedulingStateSendWhenOnline, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// MessageSchedulingStateSendAtDate The message will be sent at the specified date +type MessageSchedulingStateSendAtDate struct { + tdCommon + SendDate int32 `json:"send_date"` // Date the message will be sent. The date must be within 367 days in the future +} + +// MessageType return the string telegram-type of MessageSchedulingStateSendAtDate +func (messageSchedulingStateSendAtDate *MessageSchedulingStateSendAtDate) MessageType() string { + return "messageSchedulingStateSendAtDate" +} + +// NewMessageSchedulingStateSendAtDate creates a new MessageSchedulingStateSendAtDate +// +// @param sendDate Date the message will be sent. The date must be within 367 days in the future +func NewMessageSchedulingStateSendAtDate(sendDate int32) *MessageSchedulingStateSendAtDate { + messageSchedulingStateSendAtDateTemp := MessageSchedulingStateSendAtDate{ + tdCommon: tdCommon{Type: "messageSchedulingStateSendAtDate"}, + SendDate: sendDate, + } + + return &messageSchedulingStateSendAtDateTemp +} + +// GetMessageSchedulingStateEnum return the enum type of this object +func (messageSchedulingStateSendAtDate *MessageSchedulingStateSendAtDate) GetMessageSchedulingStateEnum() MessageSchedulingStateEnum { + return MessageSchedulingStateSendAtDateType +} + +// MessageSchedulingStateSendWhenOnline The message will be sent when the peer will be online. Applicable to private chats only and when the exact online status of the peer is known +type MessageSchedulingStateSendWhenOnline struct { + tdCommon +} + +// MessageType return the string telegram-type of MessageSchedulingStateSendWhenOnline +func (messageSchedulingStateSendWhenOnline *MessageSchedulingStateSendWhenOnline) MessageType() string { + return "messageSchedulingStateSendWhenOnline" +} + +// NewMessageSchedulingStateSendWhenOnline creates a new MessageSchedulingStateSendWhenOnline +// +func NewMessageSchedulingStateSendWhenOnline() *MessageSchedulingStateSendWhenOnline { + messageSchedulingStateSendWhenOnlineTemp := MessageSchedulingStateSendWhenOnline{ + tdCommon: tdCommon{Type: "messageSchedulingStateSendWhenOnline"}, + } + + return &messageSchedulingStateSendWhenOnlineTemp +} + +// GetMessageSchedulingStateEnum return the enum type of this object +func (messageSchedulingStateSendWhenOnline *MessageSchedulingStateSendWhenOnline) GetMessageSchedulingStateEnum() MessageSchedulingStateEnum { + return MessageSchedulingStateSendWhenOnlineType +} diff --git a/tdlib/messageSendOptions.go b/tdlib/messageSendOptions.go new file mode 100644 index 0000000..40d8c1a --- /dev/null +++ b/tdlib/messageSendOptions.go @@ -0,0 +1,64 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// MessageSendOptions Options to be used when a message is sent +type MessageSendOptions struct { + tdCommon + DisableNotification bool `json:"disable_notification"` // Pass true to disable notification for the message + FromBackground bool `json:"from_background"` // Pass true if the message is sent from the background + SchedulingState MessageSchedulingState `json:"scheduling_state"` // Message scheduling state. Messages sent to a secret chat, live location messages and self-destructing messages can't be scheduled +} + +// MessageType return the string telegram-type of MessageSendOptions +func (messageSendOptions *MessageSendOptions) MessageType() string { + return "messageSendOptions" +} + +// NewMessageSendOptions creates a new MessageSendOptions +// +// @param disableNotification Pass true to disable notification for the message +// @param fromBackground Pass true if the message is sent from the background +// @param schedulingState Message scheduling state. Messages sent to a secret chat, live location messages and self-destructing messages can't be scheduled +func NewMessageSendOptions(disableNotification bool, fromBackground bool, schedulingState MessageSchedulingState) *MessageSendOptions { + messageSendOptionsTemp := MessageSendOptions{ + tdCommon: tdCommon{Type: "messageSendOptions"}, + DisableNotification: disableNotification, + FromBackground: fromBackground, + SchedulingState: schedulingState, + } + + return &messageSendOptionsTemp +} + +// UnmarshalJSON unmarshal to json +func (messageSendOptions *MessageSendOptions) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + DisableNotification bool `json:"disable_notification"` // Pass true to disable notification for the message + FromBackground bool `json:"from_background"` // Pass true if the message is sent from the background + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + messageSendOptions.tdCommon = tempObj.tdCommon + messageSendOptions.DisableNotification = tempObj.DisableNotification + messageSendOptions.FromBackground = tempObj.FromBackground + + fieldSchedulingState, _ := unmarshalMessageSchedulingState(objMap["scheduling_state"]) + messageSendOptions.SchedulingState = fieldSchedulingState + + return nil +} diff --git a/tdlib/messageSender.go b/tdlib/messageSender.go new file mode 100644 index 0000000..0edd696 --- /dev/null +++ b/tdlib/messageSender.go @@ -0,0 +1,132 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// MessageSender Contains information about the sender of a message +type MessageSender interface { + GetMessageSenderEnum() MessageSenderEnum +} + +// MessageSenderEnum Alias for abstract MessageSender 'Sub-Classes', used as constant-enum here +type MessageSenderEnum string + +// MessageSender enums +const ( + MessageSenderUserType MessageSenderEnum = "messageSenderUser" + MessageSenderChatType MessageSenderEnum = "messageSenderChat" +) +// UnmarshalJSON unmarshal to json + +func unmarshalMessageSender(rawMsg *json.RawMessage) (MessageSender, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch MessageSenderEnum(objMap["@type"].(string)) { + case MessageSenderUserType: + var messageSenderUser MessageSenderUser + err := json.Unmarshal(*rawMsg, &messageSenderUser) + return &messageSenderUser, err + + case MessageSenderChatType: + var messageSenderChat MessageSenderChat + err := json.Unmarshal(*rawMsg, &messageSenderChat) + return &messageSenderChat, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +func unmarshalListOfMessageSender(rawMsgs []*json.RawMessage) ([]MessageSender, error) { + messageSenders := make([]MessageSender, len(rawMsgs)) + var err error + for i, rawMsg := range rawMsgs { + messageSenders[i], err = unmarshalMessageSender(rawMsg) + if err != nil { + return nil, err + } + } + return messageSenders, nil +} + +func unmarshalListOfInteractionInfo(rawMsgs []*json.RawMessage) ([]MessageSender, error) { + messageSenders := make([]MessageSender, len(rawMsgs)) + var err error + for i, rawMsg := range rawMsgs { + messageSenders[i], err = unmarshalMessageSender(rawMsg) + if err != nil { + return nil, err + } + } + return messageSenders, nil +} + + + +// MessageSenderUser The message was sent by a known user +type MessageSenderUser struct { + tdCommon + UserID int64 `json:"user_id"` // Identifier of the user that sent the message +} + +// MessageType return the string telegram-type of MessageSenderUser +func (messageSenderUser *MessageSenderUser) MessageType() string { + return "messageSenderUser" +} + +// NewMessageSenderUser creates a new MessageSenderUser +// +// @param userID Identifier of the user that sent the message +func NewMessageSenderUser(userID int64) *MessageSenderUser { + messageSenderUserTemp := MessageSenderUser{ + tdCommon: tdCommon{Type: "messageSenderUser"}, + UserID: userID, + } + + return &messageSenderUserTemp +} + +// GetMessageSenderEnum return the enum type of this object +func (messageSenderUser *MessageSenderUser) GetMessageSenderEnum() MessageSenderEnum { + return MessageSenderUserType +} + +// MessageSenderChat The message was sent on behalf of a chat +type MessageSenderChat struct { + tdCommon + ChatID int64 `json:"chat_id"` // Identifier of the chat that sent the message +} + +// MessageType return the string telegram-type of MessageSenderChat +func (messageSenderChat *MessageSenderChat) MessageType() string { + return "messageSenderChat" +} + +// NewMessageSenderChat creates a new MessageSenderChat +// +// @param chatID Identifier of the chat that sent the message +func NewMessageSenderChat(chatID int64) *MessageSenderChat { + messageSenderChatTemp := MessageSenderChat{ + tdCommon: tdCommon{Type: "messageSenderChat"}, + ChatID: chatID, + } + + return &messageSenderChatTemp +} + +// GetMessageSenderEnum return the enum type of this object +func (messageSenderChat *MessageSenderChat) GetMessageSenderEnum() MessageSenderEnum { + return MessageSenderChatType +} diff --git a/tdlib/messageSenders.go b/tdlib/messageSenders.go new file mode 100644 index 0000000..84860d5 --- /dev/null +++ b/tdlib/messageSenders.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// MessageSenders Represents a list of message senders +type MessageSenders struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of messages senders found + Senders []MessageSender `json:"senders"` // List of message senders +} + +// MessageType return the string telegram-type of MessageSenders +func (messageSenders *MessageSenders) MessageType() string { + return "messageSenders" +} + +// NewMessageSenders creates a new MessageSenders +// +// @param totalCount Approximate total count of messages senders found +// @param senders List of message senders +func NewMessageSenders(totalCount int32, senders []MessageSender) *MessageSenders { + messageSendersTemp := MessageSenders{ + tdCommon: tdCommon{Type: "messageSenders"}, + TotalCount: totalCount, + Senders: senders, + } + + return &messageSendersTemp +} diff --git a/tdlib/messageSendingState.go b/tdlib/messageSendingState.go new file mode 100644 index 0000000..b22e9cc --- /dev/null +++ b/tdlib/messageSendingState.go @@ -0,0 +1,111 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// MessageSendingState Contains information about the sending state of the message +type MessageSendingState interface { + GetMessageSendingStateEnum() MessageSendingStateEnum +} + +// MessageSendingStateEnum Alias for abstract MessageSendingState 'Sub-Classes', used as constant-enum here +type MessageSendingStateEnum string + +// MessageSendingState enums +const ( + MessageSendingStatePendingType MessageSendingStateEnum = "messageSendingStatePending" + MessageSendingStateFailedType MessageSendingStateEnum = "messageSendingStateFailed" +) + +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)) + } +} + +// 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 + ErrorCode int32 `json:"error_code"` // An error code; 0 if unknown + ErrorMessage string `json:"error_message"` // Error message + CanRetry bool `json:"can_retry"` // True, if the message can be re-sent + RetryAfter float64 `json:"retry_after"` // Time left before the message can be re-sent, in seconds. No update is sent when this field changes +} + +// MessageType return the string telegram-type of MessageSendingStateFailed +func (messageSendingStateFailed *MessageSendingStateFailed) MessageType() string { + return "messageSendingStateFailed" +} + +// NewMessageSendingStateFailed creates a new MessageSendingStateFailed +// +// @param errorCode An error code; 0 if unknown +// @param errorMessage Error message +// @param canRetry True, if the message can be re-sent +// @param retryAfter Time left before the message can be re-sent, in seconds. No update is sent when this field changes +func NewMessageSendingStateFailed(errorCode int32, errorMessage string, canRetry bool, retryAfter float64) *MessageSendingStateFailed { + messageSendingStateFailedTemp := MessageSendingStateFailed{ + tdCommon: tdCommon{Type: "messageSendingStateFailed"}, + ErrorCode: errorCode, + ErrorMessage: errorMessage, + CanRetry: canRetry, + RetryAfter: retryAfter, + } + + return &messageSendingStateFailedTemp +} + +// GetMessageSendingStateEnum return the enum type of this object +func (messageSendingStateFailed *MessageSendingStateFailed) GetMessageSendingStateEnum() MessageSendingStateEnum { + return MessageSendingStateFailedType +} diff --git a/tdlib/messageStatistics.go b/tdlib/messageStatistics.go new file mode 100644 index 0000000..be48c4a --- /dev/null +++ b/tdlib/messageStatistics.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// MessageStatistics A detailed statistics about a message +type MessageStatistics struct { + tdCommon + MessageInteractionGraph StatisticalGraph `json:"message_interaction_graph"` // A graph containing number of message views and shares +} + +// MessageType return the string telegram-type of MessageStatistics +func (messageStatistics *MessageStatistics) MessageType() string { + return "messageStatistics" +} + +// NewMessageStatistics creates a new MessageStatistics +// +// @param messageInteractionGraph A graph containing number of message views and shares +func NewMessageStatistics(messageInteractionGraph StatisticalGraph) *MessageStatistics { + messageStatisticsTemp := MessageStatistics{ + tdCommon: tdCommon{Type: "messageStatistics"}, + MessageInteractionGraph: messageInteractionGraph, + } + + return &messageStatisticsTemp +} + +// UnmarshalJSON unmarshal to json +func (messageStatistics *MessageStatistics) 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 + } + + messageStatistics.tdCommon = tempObj.tdCommon + + fieldMessageInteractionGraph, _ := unmarshalStatisticalGraph(objMap["message_interaction_graph"]) + messageStatistics.MessageInteractionGraph = fieldMessageInteractionGraph + + return nil +} diff --git a/tdlib/messageThreadInfo.go b/tdlib/messageThreadInfo.go new file mode 100644 index 0000000..671aca3 --- /dev/null +++ b/tdlib/messageThreadInfo.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// MessageThreadInfo Contains information about a message thread +type MessageThreadInfo struct { + tdCommon + ChatID int64 `json:"chat_id"` // Identifier of the chat to which the message thread belongs + MessageThreadID int64 `json:"message_thread_id"` // Message thread identifier, unique within the chat + ReplyInfo *MessageReplyInfo `json:"reply_info"` // Contains information about the message thread + UnreadMessageCount int32 `json:"unread_message_count"` // Approximate number of unread messages in the message thread + Messages []Message `json:"messages"` // The messages from which the thread starts. The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id) + DraftMessage *DraftMessage `json:"draft_message"` // A draft of a message in the message thread; may be null +} + +// MessageType return the string telegram-type of MessageThreadInfo +func (messageThreadInfo *MessageThreadInfo) MessageType() string { + return "messageThreadInfo" +} + +// NewMessageThreadInfo creates a new MessageThreadInfo +// +// @param chatID Identifier of the chat to which the message thread belongs +// @param messageThreadID Message thread identifier, unique within the chat +// @param replyInfo Contains information about the message thread +// @param unreadMessageCount Approximate number of unread messages in the message thread +// @param messages The messages from which the thread starts. The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id) +// @param draftMessage A draft of a message in the message thread; may be null +func NewMessageThreadInfo(chatID int64, messageThreadID int64, replyInfo *MessageReplyInfo, unreadMessageCount int32, messages []Message, draftMessage *DraftMessage) *MessageThreadInfo { + messageThreadInfoTemp := MessageThreadInfo{ + tdCommon: tdCommon{Type: "messageThreadInfo"}, + ChatID: chatID, + MessageThreadID: messageThreadID, + ReplyInfo: replyInfo, + UnreadMessageCount: unreadMessageCount, + Messages: messages, + DraftMessage: draftMessage, + } + + return &messageThreadInfoTemp +} diff --git a/tdlib/messages.go b/tdlib/messages.go new file mode 100644 index 0000000..57a08af --- /dev/null +++ b/tdlib/messages.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/minithumbnail.go b/tdlib/minithumbnail.go new file mode 100644 index 0000000..19cbccc --- /dev/null +++ b/tdlib/minithumbnail.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Minithumbnail Thumbnail image of a very poor quality and low resolution +type Minithumbnail struct { + tdCommon + Width int32 `json:"width"` // Thumbnail width, usually doesn't exceed 40 + Height int32 `json:"height"` // Thumbnail height, usually doesn't exceed 40 + Data []byte `json:"data"` // The thumbnail in JPEG format +} + +// MessageType return the string telegram-type of Minithumbnail +func (minithumbnail *Minithumbnail) MessageType() string { + return "minithumbnail" +} + +// NewMinithumbnail creates a new Minithumbnail +// +// @param width Thumbnail width, usually doesn't exceed 40 +// @param height Thumbnail height, usually doesn't exceed 40 +// @param data The thumbnail in JPEG format +func NewMinithumbnail(width int32, height int32, data []byte) *Minithumbnail { + minithumbnailTemp := Minithumbnail{ + tdCommon: tdCommon{Type: "minithumbnail"}, + Width: width, + Height: height, + Data: data, + } + + return &minithumbnailTemp +} diff --git a/tdlib/networkStatistics.go b/tdlib/networkStatistics.go new file mode 100644 index 0000000..b04388b --- /dev/null +++ b/tdlib/networkStatistics.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// NetworkStatistics A full list of available network statistic entries +type NetworkStatistics struct { + tdCommon + SinceDate int32 `json:"since_date"` // Point in time (Unix timestamp) from which the statistics are collected + 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) from which the statistics are collected +// @param entries Network statistics entries +func NewNetworkStatistics(sinceDate int32, entries []NetworkStatisticsEntry) *NetworkStatistics { + networkStatisticsTemp := NetworkStatistics{ + tdCommon: tdCommon{Type: "networkStatistics"}, + SinceDate: sinceDate, + Entries: entries, + } + + return &networkStatisticsTemp +} diff --git a/tdlib/networkStatisticsEntry.go b/tdlib/networkStatisticsEntry.go new file mode 100644 index 0000000..0af8283 --- /dev/null +++ b/tdlib/networkStatisticsEntry.go @@ -0,0 +1,182 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// NetworkStatisticsEntry Contains statistics about network usage +type NetworkStatisticsEntry interface { + GetNetworkStatisticsEntryEnum() NetworkStatisticsEntryEnum +} + +// NetworkStatisticsEntryEnum Alias for abstract NetworkStatisticsEntry 'Sub-Classes', used as constant-enum here +type NetworkStatisticsEntryEnum string + +// NetworkStatisticsEntry enums +const ( + NetworkStatisticsEntryFileType NetworkStatisticsEntryEnum = "networkStatisticsEntryFile" + NetworkStatisticsEntryCallType NetworkStatisticsEntryEnum = "networkStatisticsEntryCall" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/networkType.go b/tdlib/networkType.go new file mode 100644 index 0000000..aee8275 --- /dev/null +++ b/tdlib/networkType.go @@ -0,0 +1,192 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// NetworkType Represents the type of a network +type NetworkType interface { + GetNetworkTypeEnum() NetworkTypeEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/notification.go b/tdlib/notification.go new file mode 100644 index 0000000..d087a69 --- /dev/null +++ b/tdlib/notification.go @@ -0,0 +1,69 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// Notification Contains information about a notification +type Notification struct { + tdCommon + ID int32 `json:"id"` // Unique persistent identifier of this notification + Date int32 `json:"date"` // Notification date + IsSilent bool `json:"is_silent"` // True, if the notification was initially silent + Type NotificationType `json:"type"` // Notification type +} + +// MessageType return the string telegram-type of Notification +func (notification *Notification) MessageType() string { + return "notification" +} + +// NewNotification creates a new Notification +// +// @param iD Unique persistent identifier of this notification +// @param date Notification date +// @param isSilent True, if the notification was initially silent +// @param typeParam Notification type +func NewNotification(iD int32, date int32, isSilent bool, typeParam NotificationType) *Notification { + notificationTemp := Notification{ + tdCommon: tdCommon{Type: "notification"}, + ID: iD, + Date: date, + IsSilent: isSilent, + Type: typeParam, + } + + return ¬ificationTemp +} + +// UnmarshalJSON unmarshal to json +func (notification *Notification) 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 persistent identifier of this notification + Date int32 `json:"date"` // Notification date + IsSilent bool `json:"is_silent"` // True, if the notification was initially silent + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + notification.tdCommon = tempObj.tdCommon + notification.ID = tempObj.ID + notification.Date = tempObj.Date + notification.IsSilent = tempObj.IsSilent + + fieldType, _ := unmarshalNotificationType(objMap["type"]) + notification.Type = fieldType + + return nil +} diff --git a/tdlib/notificationGroup.go b/tdlib/notificationGroup.go new file mode 100644 index 0000000..65fd900 --- /dev/null +++ b/tdlib/notificationGroup.go @@ -0,0 +1,73 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// NotificationGroup Describes a group of notifications +type NotificationGroup struct { + tdCommon + ID int32 `json:"id"` // Unique persistent auto-incremented from 1 identifier of the notification group + Type NotificationGroupType `json:"type"` // Type of the group + ChatID int64 `json:"chat_id"` // Identifier of a chat to which all notifications in the group belong + TotalCount int32 `json:"total_count"` // Total number of active notifications in the group + Notifications []Notification `json:"notifications"` // The list of active notifications +} + +// MessageType return the string telegram-type of NotificationGroup +func (notificationGroup *NotificationGroup) MessageType() string { + return "notificationGroup" +} + +// NewNotificationGroup creates a new NotificationGroup +// +// @param iD Unique persistent auto-incremented from 1 identifier of the notification group +// @param typeParam Type of the group +// @param chatID Identifier of a chat to which all notifications in the group belong +// @param totalCount Total number of active notifications in the group +// @param notifications The list of active notifications +func NewNotificationGroup(iD int32, typeParam NotificationGroupType, chatID int64, totalCount int32, notifications []Notification) *NotificationGroup { + notificationGroupTemp := NotificationGroup{ + tdCommon: tdCommon{Type: "notificationGroup"}, + ID: iD, + Type: typeParam, + ChatID: chatID, + TotalCount: totalCount, + Notifications: notifications, + } + + return ¬ificationGroupTemp +} + +// UnmarshalJSON unmarshal to json +func (notificationGroup *NotificationGroup) 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 persistent auto-incremented from 1 identifier of the notification group + ChatID int64 `json:"chat_id"` // Identifier of a chat to which all notifications in the group belong + TotalCount int32 `json:"total_count"` // Total number of active notifications in the group + Notifications []Notification `json:"notifications"` // The list of active notifications + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + notificationGroup.tdCommon = tempObj.tdCommon + notificationGroup.ID = tempObj.ID + notificationGroup.ChatID = tempObj.ChatID + notificationGroup.TotalCount = tempObj.TotalCount + notificationGroup.Notifications = tempObj.Notifications + + fieldType, _ := unmarshalNotificationGroupType(objMap["type"]) + notificationGroup.Type = fieldType + + return nil +} diff --git a/tdlib/notificationGroupType.go b/tdlib/notificationGroupType.go new file mode 100644 index 0000000..10c449b --- /dev/null +++ b/tdlib/notificationGroupType.go @@ -0,0 +1,161 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// NotificationGroupType Describes the type of notifications in a notification group +type NotificationGroupType interface { + GetNotificationGroupTypeEnum() NotificationGroupTypeEnum +} + +// NotificationGroupTypeEnum Alias for abstract NotificationGroupType 'Sub-Classes', used as constant-enum here +type NotificationGroupTypeEnum string + +// NotificationGroupType enums +const ( + NotificationGroupTypeMessagesType NotificationGroupTypeEnum = "notificationGroupTypeMessages" + NotificationGroupTypeMentionsType NotificationGroupTypeEnum = "notificationGroupTypeMentions" + NotificationGroupTypeSecretChatType NotificationGroupTypeEnum = "notificationGroupTypeSecretChat" + NotificationGroupTypeCallsType NotificationGroupTypeEnum = "notificationGroupTypeCalls" +) + +func unmarshalNotificationGroupType(rawMsg *json.RawMessage) (NotificationGroupType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch NotificationGroupTypeEnum(objMap["@type"].(string)) { + case NotificationGroupTypeMessagesType: + var notificationGroupTypeMessages NotificationGroupTypeMessages + err := json.Unmarshal(*rawMsg, ¬ificationGroupTypeMessages) + return ¬ificationGroupTypeMessages, err + + case NotificationGroupTypeMentionsType: + var notificationGroupTypeMentions NotificationGroupTypeMentions + err := json.Unmarshal(*rawMsg, ¬ificationGroupTypeMentions) + return ¬ificationGroupTypeMentions, err + + case NotificationGroupTypeSecretChatType: + var notificationGroupTypeSecretChat NotificationGroupTypeSecretChat + err := json.Unmarshal(*rawMsg, ¬ificationGroupTypeSecretChat) + return ¬ificationGroupTypeSecretChat, err + + case NotificationGroupTypeCallsType: + var notificationGroupTypeCalls NotificationGroupTypeCalls + err := json.Unmarshal(*rawMsg, ¬ificationGroupTypeCalls) + return ¬ificationGroupTypeCalls, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// NotificationGroupTypeMessages A group containing notifications of type notificationTypeNewMessage and notificationTypeNewPushMessage with ordinary unread messages +type NotificationGroupTypeMessages struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationGroupTypeMessages +func (notificationGroupTypeMessages *NotificationGroupTypeMessages) MessageType() string { + return "notificationGroupTypeMessages" +} + +// NewNotificationGroupTypeMessages creates a new NotificationGroupTypeMessages +// +func NewNotificationGroupTypeMessages() *NotificationGroupTypeMessages { + notificationGroupTypeMessagesTemp := NotificationGroupTypeMessages{ + tdCommon: tdCommon{Type: "notificationGroupTypeMessages"}, + } + + return ¬ificationGroupTypeMessagesTemp +} + +// GetNotificationGroupTypeEnum return the enum type of this object +func (notificationGroupTypeMessages *NotificationGroupTypeMessages) GetNotificationGroupTypeEnum() NotificationGroupTypeEnum { + return NotificationGroupTypeMessagesType +} + +// NotificationGroupTypeMentions A group containing notifications of type notificationTypeNewMessage and notificationTypeNewPushMessage with unread mentions of the current user, replies to their messages, or a pinned message +type NotificationGroupTypeMentions struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationGroupTypeMentions +func (notificationGroupTypeMentions *NotificationGroupTypeMentions) MessageType() string { + return "notificationGroupTypeMentions" +} + +// NewNotificationGroupTypeMentions creates a new NotificationGroupTypeMentions +// +func NewNotificationGroupTypeMentions() *NotificationGroupTypeMentions { + notificationGroupTypeMentionsTemp := NotificationGroupTypeMentions{ + tdCommon: tdCommon{Type: "notificationGroupTypeMentions"}, + } + + return ¬ificationGroupTypeMentionsTemp +} + +// GetNotificationGroupTypeEnum return the enum type of this object +func (notificationGroupTypeMentions *NotificationGroupTypeMentions) GetNotificationGroupTypeEnum() NotificationGroupTypeEnum { + return NotificationGroupTypeMentionsType +} + +// NotificationGroupTypeSecretChat A group containing a notification of type notificationTypeNewSecretChat +type NotificationGroupTypeSecretChat struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationGroupTypeSecretChat +func (notificationGroupTypeSecretChat *NotificationGroupTypeSecretChat) MessageType() string { + return "notificationGroupTypeSecretChat" +} + +// NewNotificationGroupTypeSecretChat creates a new NotificationGroupTypeSecretChat +// +func NewNotificationGroupTypeSecretChat() *NotificationGroupTypeSecretChat { + notificationGroupTypeSecretChatTemp := NotificationGroupTypeSecretChat{ + tdCommon: tdCommon{Type: "notificationGroupTypeSecretChat"}, + } + + return ¬ificationGroupTypeSecretChatTemp +} + +// GetNotificationGroupTypeEnum return the enum type of this object +func (notificationGroupTypeSecretChat *NotificationGroupTypeSecretChat) GetNotificationGroupTypeEnum() NotificationGroupTypeEnum { + return NotificationGroupTypeSecretChatType +} + +// NotificationGroupTypeCalls A group containing notifications of type notificationTypeNewCall +type NotificationGroupTypeCalls struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationGroupTypeCalls +func (notificationGroupTypeCalls *NotificationGroupTypeCalls) MessageType() string { + return "notificationGroupTypeCalls" +} + +// NewNotificationGroupTypeCalls creates a new NotificationGroupTypeCalls +// +func NewNotificationGroupTypeCalls() *NotificationGroupTypeCalls { + notificationGroupTypeCallsTemp := NotificationGroupTypeCalls{ + tdCommon: tdCommon{Type: "notificationGroupTypeCalls"}, + } + + return ¬ificationGroupTypeCallsTemp +} + +// GetNotificationGroupTypeEnum return the enum type of this object +func (notificationGroupTypeCalls *NotificationGroupTypeCalls) GetNotificationGroupTypeEnum() NotificationGroupTypeEnum { + return NotificationGroupTypeCallsType +} diff --git a/tdlib/notificationSettingsScope.go b/tdlib/notificationSettingsScope.go new file mode 100644 index 0000000..b9f7f90 --- /dev/null +++ b/tdlib/notificationSettingsScope.go @@ -0,0 +1,130 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// NotificationSettingsScope Describes the types of chats to which notification settings are relevant +type NotificationSettingsScope interface { + GetNotificationSettingsScopeEnum() NotificationSettingsScopeEnum +} + +// NotificationSettingsScopeEnum Alias for abstract NotificationSettingsScope 'Sub-Classes', used as constant-enum here +type NotificationSettingsScopeEnum string + +// NotificationSettingsScope enums +const ( + NotificationSettingsScopePrivateChatsType NotificationSettingsScopeEnum = "notificationSettingsScopePrivateChats" + NotificationSettingsScopeGroupChatsType NotificationSettingsScopeEnum = "notificationSettingsScopeGroupChats" + NotificationSettingsScopeChannelChatsType NotificationSettingsScopeEnum = "notificationSettingsScopeChannelChats" +) + +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 + + case NotificationSettingsScopeChannelChatsType: + var notificationSettingsScopeChannelChats NotificationSettingsScopeChannelChats + err := json.Unmarshal(*rawMsg, ¬ificationSettingsScopeChannelChats) + return ¬ificationSettingsScopeChannelChats, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 and supergroups 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 +} + +// NotificationSettingsScopeChannelChats Notification settings applied to all channels when the corresponding chat setting has a default value +type NotificationSettingsScopeChannelChats struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationSettingsScopeChannelChats +func (notificationSettingsScopeChannelChats *NotificationSettingsScopeChannelChats) MessageType() string { + return "notificationSettingsScopeChannelChats" +} + +// NewNotificationSettingsScopeChannelChats creates a new NotificationSettingsScopeChannelChats +// +func NewNotificationSettingsScopeChannelChats() *NotificationSettingsScopeChannelChats { + notificationSettingsScopeChannelChatsTemp := NotificationSettingsScopeChannelChats{ + tdCommon: tdCommon{Type: "notificationSettingsScopeChannelChats"}, + } + + return ¬ificationSettingsScopeChannelChatsTemp +} + +// GetNotificationSettingsScopeEnum return the enum type of this object +func (notificationSettingsScopeChannelChats *NotificationSettingsScopeChannelChats) GetNotificationSettingsScopeEnum() NotificationSettingsScopeEnum { + return NotificationSettingsScopeChannelChatsType +} diff --git a/tdlib/notificationType.go b/tdlib/notificationType.go new file mode 100644 index 0000000..b821a62 --- /dev/null +++ b/tdlib/notificationType.go @@ -0,0 +1,215 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// NotificationType Contains detailed information about a notification +type NotificationType interface { + GetNotificationTypeEnum() NotificationTypeEnum +} + +// NotificationTypeEnum Alias for abstract NotificationType 'Sub-Classes', used as constant-enum here +type NotificationTypeEnum string + +// NotificationType enums +const ( + NotificationTypeNewMessageType NotificationTypeEnum = "notificationTypeNewMessage" + NotificationTypeNewSecretChatType NotificationTypeEnum = "notificationTypeNewSecretChat" + NotificationTypeNewCallType NotificationTypeEnum = "notificationTypeNewCall" + NotificationTypeNewPushMessageType NotificationTypeEnum = "notificationTypeNewPushMessage" +) + +func unmarshalNotificationType(rawMsg *json.RawMessage) (NotificationType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch NotificationTypeEnum(objMap["@type"].(string)) { + case NotificationTypeNewMessageType: + var notificationTypeNewMessage NotificationTypeNewMessage + err := json.Unmarshal(*rawMsg, ¬ificationTypeNewMessage) + return ¬ificationTypeNewMessage, err + + case NotificationTypeNewSecretChatType: + var notificationTypeNewSecretChat NotificationTypeNewSecretChat + err := json.Unmarshal(*rawMsg, ¬ificationTypeNewSecretChat) + return ¬ificationTypeNewSecretChat, err + + case NotificationTypeNewCallType: + var notificationTypeNewCall NotificationTypeNewCall + err := json.Unmarshal(*rawMsg, ¬ificationTypeNewCall) + return ¬ificationTypeNewCall, err + + case NotificationTypeNewPushMessageType: + var notificationTypeNewPushMessage NotificationTypeNewPushMessage + err := json.Unmarshal(*rawMsg, ¬ificationTypeNewPushMessage) + return ¬ificationTypeNewPushMessage, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// NotificationTypeNewMessage New message was received +type NotificationTypeNewMessage struct { + tdCommon + Message *Message `json:"message"` // The message +} + +// MessageType return the string telegram-type of NotificationTypeNewMessage +func (notificationTypeNewMessage *NotificationTypeNewMessage) MessageType() string { + return "notificationTypeNewMessage" +} + +// NewNotificationTypeNewMessage creates a new NotificationTypeNewMessage +// +// @param message The message +func NewNotificationTypeNewMessage(message *Message) *NotificationTypeNewMessage { + notificationTypeNewMessageTemp := NotificationTypeNewMessage{ + tdCommon: tdCommon{Type: "notificationTypeNewMessage"}, + Message: message, + } + + return ¬ificationTypeNewMessageTemp +} + +// GetNotificationTypeEnum return the enum type of this object +func (notificationTypeNewMessage *NotificationTypeNewMessage) GetNotificationTypeEnum() NotificationTypeEnum { + return NotificationTypeNewMessageType +} + +// NotificationTypeNewSecretChat New secret chat was created +type NotificationTypeNewSecretChat struct { + tdCommon +} + +// MessageType return the string telegram-type of NotificationTypeNewSecretChat +func (notificationTypeNewSecretChat *NotificationTypeNewSecretChat) MessageType() string { + return "notificationTypeNewSecretChat" +} + +// NewNotificationTypeNewSecretChat creates a new NotificationTypeNewSecretChat +// +func NewNotificationTypeNewSecretChat() *NotificationTypeNewSecretChat { + notificationTypeNewSecretChatTemp := NotificationTypeNewSecretChat{ + tdCommon: tdCommon{Type: "notificationTypeNewSecretChat"}, + } + + return ¬ificationTypeNewSecretChatTemp +} + +// GetNotificationTypeEnum return the enum type of this object +func (notificationTypeNewSecretChat *NotificationTypeNewSecretChat) GetNotificationTypeEnum() NotificationTypeEnum { + return NotificationTypeNewSecretChatType +} + +// NotificationTypeNewCall New call was received +type NotificationTypeNewCall struct { + tdCommon + CallID int32 `json:"call_id"` // Call identifier +} + +// MessageType return the string telegram-type of NotificationTypeNewCall +func (notificationTypeNewCall *NotificationTypeNewCall) MessageType() string { + return "notificationTypeNewCall" +} + +// NewNotificationTypeNewCall creates a new NotificationTypeNewCall +// +// @param callID Call identifier +func NewNotificationTypeNewCall(callID int32) *NotificationTypeNewCall { + notificationTypeNewCallTemp := NotificationTypeNewCall{ + tdCommon: tdCommon{Type: "notificationTypeNewCall"}, + CallID: callID, + } + + return ¬ificationTypeNewCallTemp +} + +// GetNotificationTypeEnum return the enum type of this object +func (notificationTypeNewCall *NotificationTypeNewCall) GetNotificationTypeEnum() NotificationTypeEnum { + return NotificationTypeNewCallType +} + +// NotificationTypeNewPushMessage New message was received through a push notification +type NotificationTypeNewPushMessage struct { + tdCommon + MessageID int64 `json:"message_id"` // The message identifier. The message will not be available in the chat history, but the ID can be used in viewMessages, or as reply_to_message_id + Sender MessageSender `json:"sender"` // The sender of the message. Corresponding user or chat may be inaccessible + SenderName string `json:"sender_name"` // Name of the sender + IsOutgoing bool `json:"is_outgoing"` // True, if the message is outgoing + Content PushMessageContent `json:"content"` // Push message content +} + +// MessageType return the string telegram-type of NotificationTypeNewPushMessage +func (notificationTypeNewPushMessage *NotificationTypeNewPushMessage) MessageType() string { + return "notificationTypeNewPushMessage" +} + +// NewNotificationTypeNewPushMessage creates a new NotificationTypeNewPushMessage +// +// @param messageID The message identifier. The message will not be available in the chat history, but the ID can be used in viewMessages, or as reply_to_message_id +// @param sender The sender of the message. Corresponding user or chat may be inaccessible +// @param senderName Name of the sender +// @param isOutgoing True, if the message is outgoing +// @param content Push message content +func NewNotificationTypeNewPushMessage(messageID int64, sender MessageSender, senderName string, isOutgoing bool, content PushMessageContent) *NotificationTypeNewPushMessage { + notificationTypeNewPushMessageTemp := NotificationTypeNewPushMessage{ + tdCommon: tdCommon{Type: "notificationTypeNewPushMessage"}, + MessageID: messageID, + Sender: sender, + SenderName: senderName, + IsOutgoing: isOutgoing, + Content: content, + } + + return ¬ificationTypeNewPushMessageTemp +} + +// UnmarshalJSON unmarshal to json +func (notificationTypeNewPushMessage *NotificationTypeNewPushMessage) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + MessageID int64 `json:"message_id"` // The message identifier. The message will not be available in the chat history, but the ID can be used in viewMessages, or as reply_to_message_id + SenderName string `json:"sender_name"` // Name of the sender + IsOutgoing bool `json:"is_outgoing"` // True, if the message is outgoing + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + notificationTypeNewPushMessage.tdCommon = tempObj.tdCommon + notificationTypeNewPushMessage.MessageID = tempObj.MessageID + notificationTypeNewPushMessage.SenderName = tempObj.SenderName + notificationTypeNewPushMessage.IsOutgoing = tempObj.IsOutgoing + + fieldSender, _ := unmarshalMessageSender(objMap["sender"]) + notificationTypeNewPushMessage.Sender = fieldSender + + fieldContent, _ := unmarshalPushMessageContent(objMap["content"]) + notificationTypeNewPushMessage.Content = fieldContent + + return nil +} + +// GetNotificationTypeEnum return the enum type of this object +func (notificationTypeNewPushMessage *NotificationTypeNewPushMessage) GetNotificationTypeEnum() NotificationTypeEnum { + return NotificationTypeNewPushMessageType +} diff --git a/tdlib/ok.go b/tdlib/ok.go new file mode 100644 index 0000000..1f77fa4 --- /dev/null +++ b/tdlib/ok.go @@ -0,0 +1,23 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/optionValue.go b/tdlib/optionValue.go new file mode 100644 index 0000000..a48f606 --- /dev/null +++ b/tdlib/optionValue.go @@ -0,0 +1,170 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// OptionValue Represents the value of an option +type OptionValue interface { + GetOptionValueEnum() OptionValueEnum +} + +// 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" +) + +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)) + } +} + +// OptionValueBoolean Represents a 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 Represents 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 Represents an integer option +type OptionValueInteger struct { + tdCommon + Value JSONInt64 `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 JSONInt64) *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 Represents 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 +} diff --git a/tdlib/orderInfo.go b/tdlib/orderInfo.go new file mode 100644 index 0000000..e8a6c85 --- /dev/null +++ b/tdlib/orderInfo.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/pageBlock.go b/tdlib/pageBlock.go new file mode 100644 index 0000000..bc8b113 --- /dev/null +++ b/tdlib/pageBlock.go @@ -0,0 +1,1504 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PageBlock Describes a block of an instant view web page +type PageBlock interface { + GetPageBlockEnum() PageBlockEnum +} + +// 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" + PageBlockKickerType PageBlockEnum = "pageBlockKicker" + 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" + PageBlockVoiceNoteType PageBlockEnum = "pageBlockVoiceNote" + PageBlockCoverType PageBlockEnum = "pageBlockCover" + PageBlockEmbeddedType PageBlockEnum = "pageBlockEmbedded" + PageBlockEmbeddedPostType PageBlockEnum = "pageBlockEmbeddedPost" + PageBlockCollageType PageBlockEnum = "pageBlockCollage" + PageBlockSlideshowType PageBlockEnum = "pageBlockSlideshow" + PageBlockChatLinkType PageBlockEnum = "pageBlockChatLink" + PageBlockTableType PageBlockEnum = "pageBlockTable" + PageBlockDetailsType PageBlockEnum = "pageBlockDetails" + PageBlockRelatedArticlesType PageBlockEnum = "pageBlockRelatedArticles" + PageBlockMapType PageBlockEnum = "pageBlockMap" +) + +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 PageBlockKickerType: + var pageBlockKicker PageBlockKicker + err := json.Unmarshal(*rawMsg, &pageBlockKicker) + return &pageBlockKicker, 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 PageBlockVoiceNoteType: + var pageBlockVoiceNote PageBlockVoiceNote + err := json.Unmarshal(*rawMsg, &pageBlockVoiceNote) + return &pageBlockVoiceNote, 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 + + case PageBlockTableType: + var pageBlockTable PageBlockTable + err := json.Unmarshal(*rawMsg, &pageBlockTable) + return &pageBlockTable, err + + case PageBlockDetailsType: + var pageBlockDetails PageBlockDetails + err := json.Unmarshal(*rawMsg, &pageBlockDetails) + return &pageBlockDetails, err + + case PageBlockRelatedArticlesType: + var pageBlockRelatedArticles PageBlockRelatedArticles + err := json.Unmarshal(*rawMsg, &pageBlockRelatedArticles) + return &pageBlockRelatedArticles, err + + case PageBlockMapType: + var pageBlockMap PageBlockMap + err := json.Unmarshal(*rawMsg, &pageBlockMap) + return &pageBlockMap, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 +} + +// PageBlockKicker A kicker +type PageBlockKicker struct { + tdCommon + Kicker RichText `json:"kicker"` // Kicker +} + +// MessageType return the string telegram-type of PageBlockKicker +func (pageBlockKicker *PageBlockKicker) MessageType() string { + return "pageBlockKicker" +} + +// NewPageBlockKicker creates a new PageBlockKicker +// +// @param kicker Kicker +func NewPageBlockKicker(kicker RichText) *PageBlockKicker { + pageBlockKickerTemp := PageBlockKicker{ + tdCommon: tdCommon{Type: "pageBlockKicker"}, + Kicker: kicker, + } + + return &pageBlockKickerTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockKicker *PageBlockKicker) 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 + } + + pageBlockKicker.tdCommon = tempObj.tdCommon + + fieldKicker, _ := unmarshalRichText(objMap["kicker"]) + pageBlockKicker.Kicker = fieldKicker + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockKicker *PageBlockKicker) GetPageBlockEnum() PageBlockEnum { + return PageBlockKickerType +} + +// 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 data blocks +type PageBlockList struct { + tdCommon + Items []PageBlockListItem `json:"items"` // The items of the list +} + +// MessageType return the string telegram-type of PageBlockList +func (pageBlockList *PageBlockList) MessageType() string { + return "pageBlockList" +} + +// NewPageBlockList creates a new PageBlockList +// +// @param items The items of the list +func NewPageBlockList(items []PageBlockListItem) *PageBlockList { + pageBlockListTemp := PageBlockList{ + tdCommon: tdCommon{Type: "pageBlockList"}, + Items: items, + } + + 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 + Credit RichText `json:"credit"` // Quote credit +} + +// 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 credit Quote credit +func NewPageBlockBlockQuote(text RichText, credit RichText) *PageBlockBlockQuote { + pageBlockBlockQuoteTemp := PageBlockBlockQuote{ + tdCommon: tdCommon{Type: "pageBlockBlockQuote"}, + Text: text, + Credit: credit, + } + + 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 + + fieldCredit, _ := unmarshalRichText(objMap["credit"]) + pageBlockBlockQuote.Credit = fieldCredit + + 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 + Credit RichText `json:"credit"` // Quote credit +} + +// 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 credit Quote credit +func NewPageBlockPullQuote(text RichText, credit RichText) *PageBlockPullQuote { + pageBlockPullQuoteTemp := PageBlockPullQuote{ + tdCommon: tdCommon{Type: "pageBlockPullQuote"}, + Text: text, + Credit: credit, + } + + 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 + + fieldCredit, _ := unmarshalRichText(objMap["credit"]) + pageBlockPullQuote.Credit = fieldCredit + + 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 *PageBlockCaption `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 *PageBlockCaption, needAutoplay bool) *PageBlockAnimation { + pageBlockAnimationTemp := PageBlockAnimation{ + tdCommon: tdCommon{Type: "pageBlockAnimation"}, + Animation: animation, + Caption: caption, + NeedAutoplay: needAutoplay, + } + + return &pageBlockAnimationTemp +} + +// 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 *PageBlockCaption `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 *PageBlockCaption) *PageBlockAudio { + pageBlockAudioTemp := PageBlockAudio{ + tdCommon: tdCommon{Type: "pageBlockAudio"}, + Audio: audio, + Caption: caption, + } + + return &pageBlockAudioTemp +} + +// 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 *PageBlockCaption `json:"caption"` // Photo caption + URL string `json:"url"` // URL that needs to be opened when the photo is clicked +} + +// 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 +// @param uRL URL that needs to be opened when the photo is clicked +func NewPageBlockPhoto(photo *Photo, caption *PageBlockCaption, uRL string) *PageBlockPhoto { + pageBlockPhotoTemp := PageBlockPhoto{ + tdCommon: tdCommon{Type: "pageBlockPhoto"}, + Photo: photo, + Caption: caption, + URL: uRL, + } + + return &pageBlockPhotoTemp +} + +// 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 *PageBlockCaption `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 *PageBlockCaption, needAutoplay bool, isLooped bool) *PageBlockVideo { + pageBlockVideoTemp := PageBlockVideo{ + tdCommon: tdCommon{Type: "pageBlockVideo"}, + Video: video, + Caption: caption, + NeedAutoplay: needAutoplay, + IsLooped: isLooped, + } + + return &pageBlockVideoTemp +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockVideo *PageBlockVideo) GetPageBlockEnum() PageBlockEnum { + return PageBlockVideoType +} + +// PageBlockVoiceNote A voice note +type PageBlockVoiceNote struct { + tdCommon + VoiceNote *VoiceNote `json:"voice_note"` // Voice note; may be null + Caption *PageBlockCaption `json:"caption"` // Voice note caption +} + +// MessageType return the string telegram-type of PageBlockVoiceNote +func (pageBlockVoiceNote *PageBlockVoiceNote) MessageType() string { + return "pageBlockVoiceNote" +} + +// NewPageBlockVoiceNote creates a new PageBlockVoiceNote +// +// @param voiceNote Voice note; may be null +// @param caption Voice note caption +func NewPageBlockVoiceNote(voiceNote *VoiceNote, caption *PageBlockCaption) *PageBlockVoiceNote { + pageBlockVoiceNoteTemp := PageBlockVoiceNote{ + tdCommon: tdCommon{Type: "pageBlockVoiceNote"}, + VoiceNote: voiceNote, + Caption: caption, + } + + return &pageBlockVoiceNoteTemp +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockVoiceNote *PageBlockVoiceNote) GetPageBlockEnum() PageBlockEnum { + return PageBlockVoiceNoteType +} + +// 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; 0 if unknown + Height int32 `json:"height"` // Block height; 0 if unknown + Caption *PageBlockCaption `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; 0 if unknown +// @param height Block height; 0 if unknown +// @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 *PageBlockCaption, 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 +} + +// 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; may be null + 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 *PageBlockCaption `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; may be null +// @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 *PageBlockCaption) *PageBlockEmbeddedPost { + pageBlockEmbeddedPostTemp := PageBlockEmbeddedPost{ + tdCommon: tdCommon{Type: "pageBlockEmbeddedPost"}, + URL: uRL, + Author: author, + AuthorPhoto: authorPhoto, + Date: date, + PageBlocks: pageBlocks, + Caption: caption, + } + + return &pageBlockEmbeddedPostTemp +} + +// 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 *PageBlockCaption `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 *PageBlockCaption) *PageBlockCollage { + pageBlockCollageTemp := PageBlockCollage{ + tdCommon: tdCommon{Type: "pageBlockCollage"}, + PageBlocks: pageBlocks, + Caption: caption, + } + + return &pageBlockCollageTemp +} + +// 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 *PageBlockCaption `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 *PageBlockCaption) *PageBlockSlideshow { + pageBlockSlideshowTemp := PageBlockSlideshow{ + tdCommon: tdCommon{Type: "pageBlockSlideshow"}, + PageBlocks: pageBlocks, + Caption: caption, + } + + return &pageBlockSlideshowTemp +} + +// 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 *ChatPhotoInfo `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 *ChatPhotoInfo, 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 +} + +// PageBlockTable A table +type PageBlockTable struct { + tdCommon + Caption RichText `json:"caption"` // Table caption + Cells [][]PageBlockTableCell `json:"cells"` // Table cells + IsBordered bool `json:"is_bordered"` // True, if the table is bordered + IsStriped bool `json:"is_striped"` // True, if the table is striped +} + +// MessageType return the string telegram-type of PageBlockTable +func (pageBlockTable *PageBlockTable) MessageType() string { + return "pageBlockTable" +} + +// NewPageBlockTable creates a new PageBlockTable +// +// @param caption Table caption +// @param cells Table cells +// @param isBordered True, if the table is bordered +// @param isStriped True, if the table is striped +func NewPageBlockTable(caption RichText, cells [][]PageBlockTableCell, isBordered bool, isStriped bool) *PageBlockTable { + pageBlockTableTemp := PageBlockTable{ + tdCommon: tdCommon{Type: "pageBlockTable"}, + Caption: caption, + Cells: cells, + IsBordered: isBordered, + IsStriped: isStriped, + } + + return &pageBlockTableTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockTable *PageBlockTable) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Cells [][]PageBlockTableCell `json:"cells"` // Table cells + IsBordered bool `json:"is_bordered"` // True, if the table is bordered + IsStriped bool `json:"is_striped"` // True, if the table is striped + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockTable.tdCommon = tempObj.tdCommon + pageBlockTable.Cells = tempObj.Cells + pageBlockTable.IsBordered = tempObj.IsBordered + pageBlockTable.IsStriped = tempObj.IsStriped + + fieldCaption, _ := unmarshalRichText(objMap["caption"]) + pageBlockTable.Caption = fieldCaption + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockTable *PageBlockTable) GetPageBlockEnum() PageBlockEnum { + return PageBlockTableType +} + +// PageBlockDetails A collapsible block +type PageBlockDetails struct { + tdCommon + Header RichText `json:"header"` // Always visible heading for the block + PageBlocks []PageBlock `json:"page_blocks"` // Block contents + IsOpen bool `json:"is_open"` // True, if the block is open by default +} + +// MessageType return the string telegram-type of PageBlockDetails +func (pageBlockDetails *PageBlockDetails) MessageType() string { + return "pageBlockDetails" +} + +// NewPageBlockDetails creates a new PageBlockDetails +// +// @param header Always visible heading for the block +// @param pageBlocks Block contents +// @param isOpen True, if the block is open by default +func NewPageBlockDetails(header RichText, pageBlocks []PageBlock, isOpen bool) *PageBlockDetails { + pageBlockDetailsTemp := PageBlockDetails{ + tdCommon: tdCommon{Type: "pageBlockDetails"}, + Header: header, + PageBlocks: pageBlocks, + IsOpen: isOpen, + } + + return &pageBlockDetailsTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockDetails *PageBlockDetails) 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"` // Block contents + IsOpen bool `json:"is_open"` // True, if the block is open by default + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockDetails.tdCommon = tempObj.tdCommon + pageBlockDetails.PageBlocks = tempObj.PageBlocks + pageBlockDetails.IsOpen = tempObj.IsOpen + + fieldHeader, _ := unmarshalRichText(objMap["header"]) + pageBlockDetails.Header = fieldHeader + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockDetails *PageBlockDetails) GetPageBlockEnum() PageBlockEnum { + return PageBlockDetailsType +} + +// PageBlockRelatedArticles Related articles +type PageBlockRelatedArticles struct { + tdCommon + Header RichText `json:"header"` // Block header + Articles []PageBlockRelatedArticle `json:"articles"` // List of related articles +} + +// MessageType return the string telegram-type of PageBlockRelatedArticles +func (pageBlockRelatedArticles *PageBlockRelatedArticles) MessageType() string { + return "pageBlockRelatedArticles" +} + +// NewPageBlockRelatedArticles creates a new PageBlockRelatedArticles +// +// @param header Block header +// @param articles List of related articles +func NewPageBlockRelatedArticles(header RichText, articles []PageBlockRelatedArticle) *PageBlockRelatedArticles { + pageBlockRelatedArticlesTemp := PageBlockRelatedArticles{ + tdCommon: tdCommon{Type: "pageBlockRelatedArticles"}, + Header: header, + Articles: articles, + } + + return &pageBlockRelatedArticlesTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockRelatedArticles *PageBlockRelatedArticles) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + Articles []PageBlockRelatedArticle `json:"articles"` // List of related articles + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockRelatedArticles.tdCommon = tempObj.tdCommon + pageBlockRelatedArticles.Articles = tempObj.Articles + + fieldHeader, _ := unmarshalRichText(objMap["header"]) + pageBlockRelatedArticles.Header = fieldHeader + + return nil +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockRelatedArticles *PageBlockRelatedArticles) GetPageBlockEnum() PageBlockEnum { + return PageBlockRelatedArticlesType +} + +// PageBlockMap A map +type PageBlockMap struct { + tdCommon + Location *Location `json:"location"` // Location of the map center + Zoom int32 `json:"zoom"` // Map zoom level + Width int32 `json:"width"` // Map width + Height int32 `json:"height"` // Map height + Caption *PageBlockCaption `json:"caption"` // Block caption +} + +// MessageType return the string telegram-type of PageBlockMap +func (pageBlockMap *PageBlockMap) MessageType() string { + return "pageBlockMap" +} + +// NewPageBlockMap creates a new PageBlockMap +// +// @param location Location of the map center +// @param zoom Map zoom level +// @param width Map width +// @param height Map height +// @param caption Block caption +func NewPageBlockMap(location *Location, zoom int32, width int32, height int32, caption *PageBlockCaption) *PageBlockMap { + pageBlockMapTemp := PageBlockMap{ + tdCommon: tdCommon{Type: "pageBlockMap"}, + Location: location, + Zoom: zoom, + Width: width, + Height: height, + Caption: caption, + } + + return &pageBlockMapTemp +} + +// GetPageBlockEnum return the enum type of this object +func (pageBlockMap *PageBlockMap) GetPageBlockEnum() PageBlockEnum { + return PageBlockMapType +} diff --git a/tdlib/pageBlockCaption.go b/tdlib/pageBlockCaption.go new file mode 100644 index 0000000..9e30317 --- /dev/null +++ b/tdlib/pageBlockCaption.go @@ -0,0 +1,59 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// PageBlockCaption Contains a caption of an instant view web page block, consisting of a text and a trailing credit +type PageBlockCaption struct { + tdCommon + Text RichText `json:"text"` // Content of the caption + Credit RichText `json:"credit"` // Block credit (like HTML tag ) +} + +// MessageType return the string telegram-type of PageBlockCaption +func (pageBlockCaption *PageBlockCaption) MessageType() string { + return "pageBlockCaption" +} + +// NewPageBlockCaption creates a new PageBlockCaption +// +// @param text Content of the caption +// @param credit Block credit (like HTML tag ) +func NewPageBlockCaption(text RichText, credit RichText) *PageBlockCaption { + pageBlockCaptionTemp := PageBlockCaption{ + tdCommon: tdCommon{Type: "pageBlockCaption"}, + Text: text, + Credit: credit, + } + + return &pageBlockCaptionTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockCaption *PageBlockCaption) 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 + } + + pageBlockCaption.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + pageBlockCaption.Text = fieldText + + fieldCredit, _ := unmarshalRichText(objMap["credit"]) + pageBlockCaption.Credit = fieldCredit + + return nil +} diff --git a/tdlib/pageBlockHorizontalAlignment.go b/tdlib/pageBlockHorizontalAlignment.go new file mode 100644 index 0000000..514e41c --- /dev/null +++ b/tdlib/pageBlockHorizontalAlignment.go @@ -0,0 +1,130 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PageBlockHorizontalAlignment Describes a horizontal alignment of a table cell content +type PageBlockHorizontalAlignment interface { + GetPageBlockHorizontalAlignmentEnum() PageBlockHorizontalAlignmentEnum +} + +// PageBlockHorizontalAlignmentEnum Alias for abstract PageBlockHorizontalAlignment 'Sub-Classes', used as constant-enum here +type PageBlockHorizontalAlignmentEnum string + +// PageBlockHorizontalAlignment enums +const ( + PageBlockHorizontalAlignmentLeftType PageBlockHorizontalAlignmentEnum = "pageBlockHorizontalAlignmentLeft" + PageBlockHorizontalAlignmentCenterType PageBlockHorizontalAlignmentEnum = "pageBlockHorizontalAlignmentCenter" + PageBlockHorizontalAlignmentRightType PageBlockHorizontalAlignmentEnum = "pageBlockHorizontalAlignmentRight" +) + +func unmarshalPageBlockHorizontalAlignment(rawMsg *json.RawMessage) (PageBlockHorizontalAlignment, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PageBlockHorizontalAlignmentEnum(objMap["@type"].(string)) { + case PageBlockHorizontalAlignmentLeftType: + var pageBlockHorizontalAlignmentLeft PageBlockHorizontalAlignmentLeft + err := json.Unmarshal(*rawMsg, &pageBlockHorizontalAlignmentLeft) + return &pageBlockHorizontalAlignmentLeft, err + + case PageBlockHorizontalAlignmentCenterType: + var pageBlockHorizontalAlignmentCenter PageBlockHorizontalAlignmentCenter + err := json.Unmarshal(*rawMsg, &pageBlockHorizontalAlignmentCenter) + return &pageBlockHorizontalAlignmentCenter, err + + case PageBlockHorizontalAlignmentRightType: + var pageBlockHorizontalAlignmentRight PageBlockHorizontalAlignmentRight + err := json.Unmarshal(*rawMsg, &pageBlockHorizontalAlignmentRight) + return &pageBlockHorizontalAlignmentRight, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// PageBlockHorizontalAlignmentLeft The content should be left-aligned +type PageBlockHorizontalAlignmentLeft struct { + tdCommon +} + +// MessageType return the string telegram-type of PageBlockHorizontalAlignmentLeft +func (pageBlockHorizontalAlignmentLeft *PageBlockHorizontalAlignmentLeft) MessageType() string { + return "pageBlockHorizontalAlignmentLeft" +} + +// NewPageBlockHorizontalAlignmentLeft creates a new PageBlockHorizontalAlignmentLeft +// +func NewPageBlockHorizontalAlignmentLeft() *PageBlockHorizontalAlignmentLeft { + pageBlockHorizontalAlignmentLeftTemp := PageBlockHorizontalAlignmentLeft{ + tdCommon: tdCommon{Type: "pageBlockHorizontalAlignmentLeft"}, + } + + return &pageBlockHorizontalAlignmentLeftTemp +} + +// GetPageBlockHorizontalAlignmentEnum return the enum type of this object +func (pageBlockHorizontalAlignmentLeft *PageBlockHorizontalAlignmentLeft) GetPageBlockHorizontalAlignmentEnum() PageBlockHorizontalAlignmentEnum { + return PageBlockHorizontalAlignmentLeftType +} + +// PageBlockHorizontalAlignmentCenter The content should be center-aligned +type PageBlockHorizontalAlignmentCenter struct { + tdCommon +} + +// MessageType return the string telegram-type of PageBlockHorizontalAlignmentCenter +func (pageBlockHorizontalAlignmentCenter *PageBlockHorizontalAlignmentCenter) MessageType() string { + return "pageBlockHorizontalAlignmentCenter" +} + +// NewPageBlockHorizontalAlignmentCenter creates a new PageBlockHorizontalAlignmentCenter +// +func NewPageBlockHorizontalAlignmentCenter() *PageBlockHorizontalAlignmentCenter { + pageBlockHorizontalAlignmentCenterTemp := PageBlockHorizontalAlignmentCenter{ + tdCommon: tdCommon{Type: "pageBlockHorizontalAlignmentCenter"}, + } + + return &pageBlockHorizontalAlignmentCenterTemp +} + +// GetPageBlockHorizontalAlignmentEnum return the enum type of this object +func (pageBlockHorizontalAlignmentCenter *PageBlockHorizontalAlignmentCenter) GetPageBlockHorizontalAlignmentEnum() PageBlockHorizontalAlignmentEnum { + return PageBlockHorizontalAlignmentCenterType +} + +// PageBlockHorizontalAlignmentRight The content should be right-aligned +type PageBlockHorizontalAlignmentRight struct { + tdCommon +} + +// MessageType return the string telegram-type of PageBlockHorizontalAlignmentRight +func (pageBlockHorizontalAlignmentRight *PageBlockHorizontalAlignmentRight) MessageType() string { + return "pageBlockHorizontalAlignmentRight" +} + +// NewPageBlockHorizontalAlignmentRight creates a new PageBlockHorizontalAlignmentRight +// +func NewPageBlockHorizontalAlignmentRight() *PageBlockHorizontalAlignmentRight { + pageBlockHorizontalAlignmentRightTemp := PageBlockHorizontalAlignmentRight{ + tdCommon: tdCommon{Type: "pageBlockHorizontalAlignmentRight"}, + } + + return &pageBlockHorizontalAlignmentRightTemp +} + +// GetPageBlockHorizontalAlignmentEnum return the enum type of this object +func (pageBlockHorizontalAlignmentRight *PageBlockHorizontalAlignmentRight) GetPageBlockHorizontalAlignmentEnum() PageBlockHorizontalAlignmentEnum { + return PageBlockHorizontalAlignmentRightType +} diff --git a/tdlib/pageBlockListItem.go b/tdlib/pageBlockListItem.go new file mode 100644 index 0000000..7afc98a --- /dev/null +++ b/tdlib/pageBlockListItem.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PageBlockListItem Describes an item of a list page block +type PageBlockListItem struct { + tdCommon + Label string `json:"label"` // Item label + PageBlocks []PageBlock `json:"page_blocks"` // Item blocks +} + +// MessageType return the string telegram-type of PageBlockListItem +func (pageBlockListItem *PageBlockListItem) MessageType() string { + return "pageBlockListItem" +} + +// NewPageBlockListItem creates a new PageBlockListItem +// +// @param label Item label +// @param pageBlocks Item blocks +func NewPageBlockListItem(label string, pageBlocks []PageBlock) *PageBlockListItem { + pageBlockListItemTemp := PageBlockListItem{ + tdCommon: tdCommon{Type: "pageBlockListItem"}, + Label: label, + PageBlocks: pageBlocks, + } + + return &pageBlockListItemTemp +} diff --git a/tdlib/pageBlockRelatedArticle.go b/tdlib/pageBlockRelatedArticle.go new file mode 100644 index 0000000..ced9461 --- /dev/null +++ b/tdlib/pageBlockRelatedArticle.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PageBlockRelatedArticle Contains information about a related article +type PageBlockRelatedArticle struct { + tdCommon + URL string `json:"url"` // Related article URL + Title string `json:"title"` // Article title; may be empty + Description string `json:"description"` // Article description; may be empty + Photo *Photo `json:"photo"` // Article photo; may be null + Author string `json:"author"` // Article author; may be empty + 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 PageBlockRelatedArticle +func (pageBlockRelatedArticle *PageBlockRelatedArticle) MessageType() string { + return "pageBlockRelatedArticle" +} + +// NewPageBlockRelatedArticle creates a new PageBlockRelatedArticle +// +// @param uRL Related article URL +// @param title Article title; may be empty +// @param description Article description; may be empty +// @param photo Article photo; may be null +// @param author Article author; may be empty +// @param publishDate Point in time (Unix timestamp) when the article was published; 0 if unknown +func NewPageBlockRelatedArticle(uRL string, title string, description string, photo *Photo, author string, publishDate int32) *PageBlockRelatedArticle { + pageBlockRelatedArticleTemp := PageBlockRelatedArticle{ + tdCommon: tdCommon{Type: "pageBlockRelatedArticle"}, + URL: uRL, + Title: title, + Description: description, + Photo: photo, + Author: author, + PublishDate: publishDate, + } + + return &pageBlockRelatedArticleTemp +} diff --git a/tdlib/pageBlockTableCell.go b/tdlib/pageBlockTableCell.go new file mode 100644 index 0000000..f076255 --- /dev/null +++ b/tdlib/pageBlockTableCell.go @@ -0,0 +1,81 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// PageBlockTableCell Represents a cell of a table +type PageBlockTableCell struct { + tdCommon + Text RichText `json:"text"` // Cell text; may be null. If the text is null, then the cell should be invisible + IsHeader bool `json:"is_header"` // True, if it is a header cell + Colspan int32 `json:"colspan"` // The number of columns the cell should span + Rowspan int32 `json:"rowspan"` // The number of rows the cell should span + Align PageBlockHorizontalAlignment `json:"align"` // Horizontal cell content alignment + Valign PageBlockVerticalAlignment `json:"valign"` // Vertical cell content alignment +} + +// MessageType return the string telegram-type of PageBlockTableCell +func (pageBlockTableCell *PageBlockTableCell) MessageType() string { + return "pageBlockTableCell" +} + +// NewPageBlockTableCell creates a new PageBlockTableCell +// +// @param text Cell text; may be null. If the text is null, then the cell should be invisible +// @param isHeader True, if it is a header cell +// @param colspan The number of columns the cell should span +// @param rowspan The number of rows the cell should span +// @param align Horizontal cell content alignment +// @param valign Vertical cell content alignment +func NewPageBlockTableCell(text RichText, isHeader bool, colspan int32, rowspan int32, align PageBlockHorizontalAlignment, valign PageBlockVerticalAlignment) *PageBlockTableCell { + pageBlockTableCellTemp := PageBlockTableCell{ + tdCommon: tdCommon{Type: "pageBlockTableCell"}, + Text: text, + IsHeader: isHeader, + Colspan: colspan, + Rowspan: rowspan, + Align: align, + Valign: valign, + } + + return &pageBlockTableCellTemp +} + +// UnmarshalJSON unmarshal to json +func (pageBlockTableCell *PageBlockTableCell) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + IsHeader bool `json:"is_header"` // True, if it is a header cell + Colspan int32 `json:"colspan"` // The number of columns the cell should span + Rowspan int32 `json:"rowspan"` // The number of rows the cell should span + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + pageBlockTableCell.tdCommon = tempObj.tdCommon + pageBlockTableCell.IsHeader = tempObj.IsHeader + pageBlockTableCell.Colspan = tempObj.Colspan + pageBlockTableCell.Rowspan = tempObj.Rowspan + + fieldText, _ := unmarshalRichText(objMap["text"]) + pageBlockTableCell.Text = fieldText + + fieldAlign, _ := unmarshalPageBlockHorizontalAlignment(objMap["align"]) + pageBlockTableCell.Align = fieldAlign + + fieldValign, _ := unmarshalPageBlockVerticalAlignment(objMap["valign"]) + pageBlockTableCell.Valign = fieldValign + + return nil +} diff --git a/tdlib/pageBlockVerticalAlignment.go b/tdlib/pageBlockVerticalAlignment.go new file mode 100644 index 0000000..ea28c60 --- /dev/null +++ b/tdlib/pageBlockVerticalAlignment.go @@ -0,0 +1,130 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PageBlockVerticalAlignment Describes a Vertical alignment of a table cell content +type PageBlockVerticalAlignment interface { + GetPageBlockVerticalAlignmentEnum() PageBlockVerticalAlignmentEnum +} + +// PageBlockVerticalAlignmentEnum Alias for abstract PageBlockVerticalAlignment 'Sub-Classes', used as constant-enum here +type PageBlockVerticalAlignmentEnum string + +// PageBlockVerticalAlignment enums +const ( + PageBlockVerticalAlignmentTopType PageBlockVerticalAlignmentEnum = "pageBlockVerticalAlignmentTop" + PageBlockVerticalAlignmentMiddleType PageBlockVerticalAlignmentEnum = "pageBlockVerticalAlignmentMiddle" + PageBlockVerticalAlignmentBottomType PageBlockVerticalAlignmentEnum = "pageBlockVerticalAlignmentBottom" +) + +func unmarshalPageBlockVerticalAlignment(rawMsg *json.RawMessage) (PageBlockVerticalAlignment, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PageBlockVerticalAlignmentEnum(objMap["@type"].(string)) { + case PageBlockVerticalAlignmentTopType: + var pageBlockVerticalAlignmentTop PageBlockVerticalAlignmentTop + err := json.Unmarshal(*rawMsg, &pageBlockVerticalAlignmentTop) + return &pageBlockVerticalAlignmentTop, err + + case PageBlockVerticalAlignmentMiddleType: + var pageBlockVerticalAlignmentMiddle PageBlockVerticalAlignmentMiddle + err := json.Unmarshal(*rawMsg, &pageBlockVerticalAlignmentMiddle) + return &pageBlockVerticalAlignmentMiddle, err + + case PageBlockVerticalAlignmentBottomType: + var pageBlockVerticalAlignmentBottom PageBlockVerticalAlignmentBottom + err := json.Unmarshal(*rawMsg, &pageBlockVerticalAlignmentBottom) + return &pageBlockVerticalAlignmentBottom, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// PageBlockVerticalAlignmentTop The content should be top-aligned +type PageBlockVerticalAlignmentTop struct { + tdCommon +} + +// MessageType return the string telegram-type of PageBlockVerticalAlignmentTop +func (pageBlockVerticalAlignmentTop *PageBlockVerticalAlignmentTop) MessageType() string { + return "pageBlockVerticalAlignmentTop" +} + +// NewPageBlockVerticalAlignmentTop creates a new PageBlockVerticalAlignmentTop +// +func NewPageBlockVerticalAlignmentTop() *PageBlockVerticalAlignmentTop { + pageBlockVerticalAlignmentTopTemp := PageBlockVerticalAlignmentTop{ + tdCommon: tdCommon{Type: "pageBlockVerticalAlignmentTop"}, + } + + return &pageBlockVerticalAlignmentTopTemp +} + +// GetPageBlockVerticalAlignmentEnum return the enum type of this object +func (pageBlockVerticalAlignmentTop *PageBlockVerticalAlignmentTop) GetPageBlockVerticalAlignmentEnum() PageBlockVerticalAlignmentEnum { + return PageBlockVerticalAlignmentTopType +} + +// PageBlockVerticalAlignmentMiddle The content should be middle-aligned +type PageBlockVerticalAlignmentMiddle struct { + tdCommon +} + +// MessageType return the string telegram-type of PageBlockVerticalAlignmentMiddle +func (pageBlockVerticalAlignmentMiddle *PageBlockVerticalAlignmentMiddle) MessageType() string { + return "pageBlockVerticalAlignmentMiddle" +} + +// NewPageBlockVerticalAlignmentMiddle creates a new PageBlockVerticalAlignmentMiddle +// +func NewPageBlockVerticalAlignmentMiddle() *PageBlockVerticalAlignmentMiddle { + pageBlockVerticalAlignmentMiddleTemp := PageBlockVerticalAlignmentMiddle{ + tdCommon: tdCommon{Type: "pageBlockVerticalAlignmentMiddle"}, + } + + return &pageBlockVerticalAlignmentMiddleTemp +} + +// GetPageBlockVerticalAlignmentEnum return the enum type of this object +func (pageBlockVerticalAlignmentMiddle *PageBlockVerticalAlignmentMiddle) GetPageBlockVerticalAlignmentEnum() PageBlockVerticalAlignmentEnum { + return PageBlockVerticalAlignmentMiddleType +} + +// PageBlockVerticalAlignmentBottom The content should be bottom-aligned +type PageBlockVerticalAlignmentBottom struct { + tdCommon +} + +// MessageType return the string telegram-type of PageBlockVerticalAlignmentBottom +func (pageBlockVerticalAlignmentBottom *PageBlockVerticalAlignmentBottom) MessageType() string { + return "pageBlockVerticalAlignmentBottom" +} + +// NewPageBlockVerticalAlignmentBottom creates a new PageBlockVerticalAlignmentBottom +// +func NewPageBlockVerticalAlignmentBottom() *PageBlockVerticalAlignmentBottom { + pageBlockVerticalAlignmentBottomTemp := PageBlockVerticalAlignmentBottom{ + tdCommon: tdCommon{Type: "pageBlockVerticalAlignmentBottom"}, + } + + return &pageBlockVerticalAlignmentBottomTemp +} + +// GetPageBlockVerticalAlignmentEnum return the enum type of this object +func (pageBlockVerticalAlignmentBottom *PageBlockVerticalAlignmentBottom) GetPageBlockVerticalAlignmentEnum() PageBlockVerticalAlignmentEnum { + return PageBlockVerticalAlignmentBottomType +} diff --git a/tdlib/passportAuthorizationForm.go b/tdlib/passportAuthorizationForm.go new file mode 100644 index 0000000..9c120c3 --- /dev/null +++ b/tdlib/passportAuthorizationForm.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 must be provided to complete the form + PrivacyPolicyURL string `json:"privacy_policy_url"` // URL for the privacy policy of the service; may 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 must be provided to complete the form +// @param privacyPolicyURL URL for the privacy policy of the service; may be empty +func NewPassportAuthorizationForm(iD int32, requiredElements []PassportRequiredElement, privacyPolicyURL string) *PassportAuthorizationForm { + passportAuthorizationFormTemp := PassportAuthorizationForm{ + tdCommon: tdCommon{Type: "passportAuthorizationForm"}, + ID: iD, + RequiredElements: requiredElements, + PrivacyPolicyURL: privacyPolicyURL, + } + + return &passportAuthorizationFormTemp +} diff --git a/tdlib/passportElement.go b/tdlib/passportElement.go new file mode 100644 index 0000000..4938fe8 --- /dev/null +++ b/tdlib/passportElement.go @@ -0,0 +1,479 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PassportElement Contains information about a Telegram Passport element +type PassportElement interface { + GetPassportElementEnum() PassportElementEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/passportElementError.go b/tdlib/passportElementError.go new file mode 100644 index 0000000..0947b7b --- /dev/null +++ b/tdlib/passportElementError.go @@ -0,0 +1,65 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/passportElementErrorSource.go b/tdlib/passportElementErrorSource.go new file mode 100644 index 0000000..f2f6147 --- /dev/null +++ b/tdlib/passportElementErrorSource.go @@ -0,0 +1,325 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PassportElementErrorSource Contains the description of an error in a Telegram Passport element +type PassportElementErrorSource interface { + GetPassportElementErrorSourceEnum() PassportElementErrorSourceEnum +} + +// 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" +) + +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)) + } +} + +// 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 + FileIndex int32 `json:"file_index"` // Index of a file with the error +} + +// MessageType return the string telegram-type of PassportElementErrorSourceTranslationFile +func (passportElementErrorSourceTranslationFile *PassportElementErrorSourceTranslationFile) MessageType() string { + return "passportElementErrorSourceTranslationFile" +} + +// NewPassportElementErrorSourceTranslationFile creates a new PassportElementErrorSourceTranslationFile +// +// @param fileIndex Index of a file with the error +func NewPassportElementErrorSourceTranslationFile(fileIndex int32) *PassportElementErrorSourceTranslationFile { + passportElementErrorSourceTranslationFileTemp := PassportElementErrorSourceTranslationFile{ + tdCommon: tdCommon{Type: "passportElementErrorSourceTranslationFile"}, + FileIndex: fileIndex, + } + + 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 + FileIndex int32 `json:"file_index"` // Index of a file with the error +} + +// MessageType return the string telegram-type of PassportElementErrorSourceFile +func (passportElementErrorSourceFile *PassportElementErrorSourceFile) MessageType() string { + return "passportElementErrorSourceFile" +} + +// NewPassportElementErrorSourceFile creates a new PassportElementErrorSourceFile +// +// @param fileIndex Index of a file with the error +func NewPassportElementErrorSourceFile(fileIndex int32) *PassportElementErrorSourceFile { + passportElementErrorSourceFileTemp := PassportElementErrorSourceFile{ + tdCommon: tdCommon{Type: "passportElementErrorSourceFile"}, + FileIndex: fileIndex, + } + + 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 +} diff --git a/tdlib/passportElementType.go b/tdlib/passportElementType.go new file mode 100644 index 0000000..8298e94 --- /dev/null +++ b/tdlib/passportElementType.go @@ -0,0 +1,440 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PassportElementType Contains the type of a Telegram Passport element +type PassportElementType interface { + GetPassportElementTypeEnum() PassportElementTypeEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/passportElements.go b/tdlib/passportElements.go new file mode 100644 index 0000000..650f4d9 --- /dev/null +++ b/tdlib/passportElements.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/passportElementsWithErrors.go b/tdlib/passportElementsWithErrors.go new file mode 100644 index 0000000..cad2111 --- /dev/null +++ b/tdlib/passportElementsWithErrors.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PassportElementsWithErrors Contains information about a Telegram Passport elements and corresponding errors +type PassportElementsWithErrors struct { + tdCommon + Elements []PassportElement `json:"elements"` // Telegram Passport elements + Errors []PassportElementError `json:"errors"` // Errors in the elements that are already available +} + +// MessageType return the string telegram-type of PassportElementsWithErrors +func (passportElementsWithErrors *PassportElementsWithErrors) MessageType() string { + return "passportElementsWithErrors" +} + +// NewPassportElementsWithErrors creates a new PassportElementsWithErrors +// +// @param elements Telegram Passport elements +// @param errors Errors in the elements that are already available +func NewPassportElementsWithErrors(elements []PassportElement, errors []PassportElementError) *PassportElementsWithErrors { + passportElementsWithErrorsTemp := PassportElementsWithErrors{ + tdCommon: tdCommon{Type: "passportElementsWithErrors"}, + Elements: elements, + Errors: errors, + } + + return &passportElementsWithErrorsTemp +} diff --git a/tdlib/passportRequiredElement.go b/tdlib/passportRequiredElement.go new file mode 100644 index 0000000..2f084b8 --- /dev/null +++ b/tdlib/passportRequiredElement.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/passportSuitableElement.go b/tdlib/passportSuitableElement.go new file mode 100644 index 0000000..d979dae --- /dev/null +++ b/tdlib/passportSuitableElement.go @@ -0,0 +1,68 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/passwordState.go b/tdlib/passwordState.go new file mode 100644 index 0000000..3d70097 --- /dev/null +++ b/tdlib/passwordState.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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; may 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 + RecoveryEmailAddressCodeInfo *EmailAddressAuthenticationCodeInfo `json:"recovery_email_address_code_info"` // Information about the recovery email address to which the confirmation email was sent; may be null + PendingResetDate int32 `json:"pending_reset_date"` // If not 0, point in time (Unix timestamp) after which the password can be reset immediately using resetPassword +} + +// 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; may be empty +// @param hasRecoveryEmailAddress True, if a recovery email is set +// @param hasPassportData True, if some Telegram Passport elements were saved +// @param recoveryEmailAddressCodeInfo Information about the recovery email address to which the confirmation email was sent; may be null +// @param pendingResetDate If not 0, point in time (Unix timestamp) after which the password can be reset immediately using resetPassword +func NewPasswordState(hasPassword bool, passwordHint string, hasRecoveryEmailAddress bool, hasPassportData bool, recoveryEmailAddressCodeInfo *EmailAddressAuthenticationCodeInfo, pendingResetDate int32) *PasswordState { + passwordStateTemp := PasswordState{ + tdCommon: tdCommon{Type: "passwordState"}, + HasPassword: hasPassword, + PasswordHint: passwordHint, + HasRecoveryEmailAddress: hasRecoveryEmailAddress, + HasPassportData: hasPassportData, + RecoveryEmailAddressCodeInfo: recoveryEmailAddressCodeInfo, + PendingResetDate: pendingResetDate, + } + + return &passwordStateTemp +} diff --git a/tdlib/paymentForm.go b/tdlib/paymentForm.go new file mode 100644 index 0000000..adff26a --- /dev/null +++ b/tdlib/paymentForm.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PaymentForm Contains information about an invoice payment form +type PaymentForm struct { + tdCommon + ID JSONInt64 `json:"id"` // The payment form identifier + Invoice *Invoice `json:"invoice"` // Full information of the invoice + URL string `json:"url"` // Payment form URL + SellerBotUserID int64 `json:"seller_bot_user_id"` // User identifier of the seller bot + PaymentsProviderUserID int64 `json:"payments_provider_user_id"` // User identifier of the payment provider bot + 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 iD The payment form identifier +// @param invoice Full information of the invoice +// @param uRL Payment form URL +// @param sellerBotUserID User identifier of the seller bot +// @param paymentsProviderUserID User identifier of the payment provider bot +// @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(iD JSONInt64, invoice *Invoice, uRL string, sellerBotUserID int64, paymentsProviderUserID int64, paymentsProvider *PaymentsProviderStripe, savedOrderInfo *OrderInfo, savedCredentials *SavedCredentials, canSaveCredentials bool, needPassword bool) *PaymentForm { + paymentFormTemp := PaymentForm{ + tdCommon: tdCommon{Type: "paymentForm"}, + ID: iD, + Invoice: invoice, + URL: uRL, + SellerBotUserID: sellerBotUserID, + PaymentsProviderUserID: paymentsProviderUserID, + PaymentsProvider: paymentsProvider, + SavedOrderInfo: savedOrderInfo, + SavedCredentials: savedCredentials, + CanSaveCredentials: canSaveCredentials, + NeedPassword: needPassword, + } + + return &paymentFormTemp +} diff --git a/tdlib/paymentFormTheme.go b/tdlib/paymentFormTheme.go new file mode 100644 index 0000000..751b28c --- /dev/null +++ b/tdlib/paymentFormTheme.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PaymentFormTheme Theme colors for a payment form +type PaymentFormTheme struct { + tdCommon + BackgroundColor int32 `json:"background_color"` // A color of the payment form background in the RGB24 format + TextColor int32 `json:"text_color"` // A color of text in the RGB24 format + HintColor int32 `json:"hint_color"` // A color of hints in the RGB24 format + LinkColor int32 `json:"link_color"` // A color of links in the RGB24 format + ButtonColor int32 `json:"button_color"` // A color of thebuttons in the RGB24 format + ButtonTextColor int32 `json:"button_text_color"` // A color of text on the buttons in the RGB24 format +} + +// MessageType return the string telegram-type of PaymentFormTheme +func (paymentFormTheme *PaymentFormTheme) MessageType() string { + return "paymentFormTheme" +} + +// NewPaymentFormTheme creates a new PaymentFormTheme +// +// @param backgroundColor A color of the payment form background in the RGB24 format +// @param textColor A color of text in the RGB24 format +// @param hintColor A color of hints in the RGB24 format +// @param linkColor A color of links in the RGB24 format +// @param buttonColor A color of thebuttons in the RGB24 format +// @param buttonTextColor A color of text on the buttons in the RGB24 format +func NewPaymentFormTheme(backgroundColor int32, textColor int32, hintColor int32, linkColor int32, buttonColor int32, buttonTextColor int32) *PaymentFormTheme { + paymentFormThemeTemp := PaymentFormTheme{ + tdCommon: tdCommon{Type: "paymentFormTheme"}, + BackgroundColor: backgroundColor, + TextColor: textColor, + HintColor: hintColor, + LinkColor: linkColor, + ButtonColor: buttonColor, + ButtonTextColor: buttonTextColor, + } + + return &paymentFormThemeTemp +} diff --git a/tdlib/paymentReceipt.go b/tdlib/paymentReceipt.go new file mode 100644 index 0000000..43093b5 --- /dev/null +++ b/tdlib/paymentReceipt.go @@ -0,0 +1,56 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PaymentReceipt Contains information about a successful payment +type PaymentReceipt struct { + tdCommon + Title string `json:"title"` // Product title + Description string `json:"description"` // Product description + Photo *Photo `json:"photo"` // Product photo; may be null + Date int32 `json:"date"` // Point in time (Unix timestamp) when the payment was made + SellerBotUserID int64 `json:"seller_bot_user_id"` // User identifier of the seller bot + PaymentsProviderUserID int64 `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"` // 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 chosen by the buyer + TipAmount int64 `json:"tip_amount"` // The amount of tip chosen by the buyer in the smallest units of the currency +} + +// MessageType return the string telegram-type of PaymentReceipt +func (paymentReceipt *PaymentReceipt) MessageType() string { + return "paymentReceipt" +} + +// NewPaymentReceipt creates a new PaymentReceipt +// +// @param title Product title +// @param description Product description +// @param photo Product photo; may be null +// @param date Point in time (Unix timestamp) when the payment was made +// @param sellerBotUserID User identifier of the seller bot +// @param paymentsProviderUserID User identifier of the payment provider bot +// @param invoice Contains information about the invoice +// @param orderInfo Order information; may be null +// @param shippingOption Chosen shipping option; may be null +// @param credentialsTitle Title of the saved credentials chosen by the buyer +// @param tipAmount The amount of tip chosen by the buyer in the smallest units of the currency +func NewPaymentReceipt(title string, description string, photo *Photo, date int32, sellerBotUserID int64, paymentsProviderUserID int64, invoice *Invoice, orderInfo *OrderInfo, shippingOption *ShippingOption, credentialsTitle string, tipAmount int64) *PaymentReceipt { + paymentReceiptTemp := PaymentReceipt{ + tdCommon: tdCommon{Type: "paymentReceipt"}, + Title: title, + Description: description, + Photo: photo, + Date: date, + SellerBotUserID: sellerBotUserID, + PaymentsProviderUserID: paymentsProviderUserID, + Invoice: invoice, + OrderInfo: orderInfo, + ShippingOption: shippingOption, + CredentialsTitle: credentialsTitle, + TipAmount: tipAmount, + } + + return &paymentReceiptTemp +} diff --git a/tdlib/paymentResult.go b/tdlib/paymentResult.go new file mode 100644 index 0000000..b36f6eb --- /dev/null +++ b/tdlib/paymentResult.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 non-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 non-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 +} diff --git a/tdlib/paymentsProviderStripe.go b/tdlib/paymentsProviderStripe.go new file mode 100644 index 0000000..c340628 --- /dev/null +++ b/tdlib/paymentsProviderStripe.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/personalDetails.go b/tdlib/personalDetails.go new file mode 100644 index 0000000..0bc77a9 --- /dev/null +++ b/tdlib/personalDetails.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/personalDocument.go b/tdlib/personalDocument.go new file mode 100644 index 0000000..02bbf26 --- /dev/null +++ b/tdlib/personalDocument.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/phoneNumberAuthenticationSettings.go b/tdlib/phoneNumberAuthenticationSettings.go new file mode 100644 index 0000000..1599e22 --- /dev/null +++ b/tdlib/phoneNumberAuthenticationSettings.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PhoneNumberAuthenticationSettings Contains settings for the authentication of the user's phone number +type PhoneNumberAuthenticationSettings struct { + tdCommon + AllowFlashCall bool `json:"allow_flash_call"` // Pass true if the authentication code may be sent via flash call to the specified phone number + IsCurrentPhoneNumber bool `json:"is_current_phone_number"` // Pass true if the authenticated phone number is used on the current device + AllowSmsRetrieverAPI bool `json:"allow_sms_retriever_api"` // For official applications only. True, if the application can use Android SMS Retriever API (requires Google Play Services >= 10.2) to automatically receive the authentication code from the SMS. See https://developers.google.com/identity/sms-retriever/ for more details +} + +// MessageType return the string telegram-type of PhoneNumberAuthenticationSettings +func (phoneNumberAuthenticationSettings *PhoneNumberAuthenticationSettings) MessageType() string { + return "phoneNumberAuthenticationSettings" +} + +// NewPhoneNumberAuthenticationSettings creates a new PhoneNumberAuthenticationSettings +// +// @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 authenticated phone number is used on the current device +// @param allowSmsRetrieverAPI For official applications only. True, if the application can use Android SMS Retriever API (requires Google Play Services >= 10.2) to automatically receive the authentication code from the SMS. See https://developers.google.com/identity/sms-retriever/ for more details +func NewPhoneNumberAuthenticationSettings(allowFlashCall bool, isCurrentPhoneNumber bool, allowSmsRetrieverAPI bool) *PhoneNumberAuthenticationSettings { + phoneNumberAuthenticationSettingsTemp := PhoneNumberAuthenticationSettings{ + tdCommon: tdCommon{Type: "phoneNumberAuthenticationSettings"}, + AllowFlashCall: allowFlashCall, + IsCurrentPhoneNumber: isCurrentPhoneNumber, + AllowSmsRetrieverAPI: allowSmsRetrieverAPI, + } + + return &phoneNumberAuthenticationSettingsTemp +} diff --git a/tdlib/phoneNumberInfo.go b/tdlib/phoneNumberInfo.go new file mode 100644 index 0000000..c36fac9 --- /dev/null +++ b/tdlib/phoneNumberInfo.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PhoneNumberInfo Contains information about a phone number +type PhoneNumberInfo struct { + tdCommon + Country *CountryInfo `json:"country"` // Information about the country to which the phone number belongs; may be null + CountryCallingCode string `json:"country_calling_code"` // The part of the phone number denoting country calling code or its part + FormattedPhoneNumber string `json:"formatted_phone_number"` // The phone number without country calling code formatted accordingly to local rules. Expected digits are returned as '-', but even more digits might be entered by the user +} + +// MessageType return the string telegram-type of PhoneNumberInfo +func (phoneNumberInfo *PhoneNumberInfo) MessageType() string { + return "phoneNumberInfo" +} + +// NewPhoneNumberInfo creates a new PhoneNumberInfo +// +// @param country Information about the country to which the phone number belongs; may be null +// @param countryCallingCode The part of the phone number denoting country calling code or its part +// @param formattedPhoneNumber The phone number without country calling code formatted accordingly to local rules. Expected digits are returned as '-', but even more digits might be entered by the user +func NewPhoneNumberInfo(country *CountryInfo, countryCallingCode string, formattedPhoneNumber string) *PhoneNumberInfo { + phoneNumberInfoTemp := PhoneNumberInfo{ + tdCommon: tdCommon{Type: "phoneNumberInfo"}, + Country: country, + CountryCallingCode: countryCallingCode, + FormattedPhoneNumber: formattedPhoneNumber, + } + + return &phoneNumberInfoTemp +} diff --git a/tdlib/photo.go b/tdlib/photo.go new file mode 100644 index 0000000..145c4c1 --- /dev/null +++ b/tdlib/photo.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Photo Describes a photo +type Photo struct { + tdCommon + HasStickers bool `json:"has_stickers"` // True, if stickers were added to the photo. The list of corresponding sticker sets can be received using getAttachedStickerSets + Minithumbnail *Minithumbnail `json:"minithumbnail"` // Photo minithumbnail; may be null + 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 hasStickers True, if stickers were added to the photo. The list of corresponding sticker sets can be received using getAttachedStickerSets +// @param minithumbnail Photo minithumbnail; may be null +// @param sizes Available variants of the photo, in different sizes +func NewPhoto(hasStickers bool, minithumbnail *Minithumbnail, sizes []PhotoSize) *Photo { + photoTemp := Photo{ + tdCommon: tdCommon{Type: "photo"}, + HasStickers: hasStickers, + Minithumbnail: minithumbnail, + Sizes: sizes, + } + + return &photoTemp +} diff --git a/tdlib/photoSize.go b/tdlib/photoSize.go new file mode 100644 index 0000000..70a66f5 --- /dev/null +++ b/tdlib/photoSize.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PhotoSize Describes an image in JPEG format +type PhotoSize struct { + tdCommon + Type string `json:"type"` // Image type (see https://core.telegram.org/constructor/photoSize) + Photo *File `json:"photo"` // Information about the image file + Width int32 `json:"width"` // Image width + Height int32 `json:"height"` // Image height + ProgressiveSizes []int32 `json:"progressive_sizes"` // Sizes of progressive JPEG file prefixes, which can be used to preliminarily show the image; in bytes +} + +// MessageType return the string telegram-type of PhotoSize +func (photoSize *PhotoSize) MessageType() string { + return "photoSize" +} + +// NewPhotoSize creates a new PhotoSize +// +// @param typeParam Image type (see https://core.telegram.org/constructor/photoSize) +// @param photo Information about the image file +// @param width Image width +// @param height Image height +// @param progressiveSizes Sizes of progressive JPEG file prefixes, which can be used to preliminarily show the image; in bytes +func NewPhotoSize(typeParam string, photo *File, width int32, height int32, progressiveSizes []int32) *PhotoSize { + photoSizeTemp := PhotoSize{ + tdCommon: tdCommon{Type: "photoSize"}, + Type: typeParam, + Photo: photo, + Width: width, + Height: height, + ProgressiveSizes: progressiveSizes, + } + + return &photoSizeTemp +} diff --git a/tdlib/point.go b/tdlib/point.go new file mode 100644 index 0000000..0a5e174 --- /dev/null +++ b/tdlib/point.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Point A point on a Cartesian plane +type Point struct { + tdCommon + X float64 `json:"x"` // The point's first coordinate + Y float64 `json:"y"` // The point's second coordinate +} + +// MessageType return the string telegram-type of Point +func (point *Point) MessageType() string { + return "point" +} + +// NewPoint creates a new Point +// +// @param x The point's first coordinate +// @param y The point's second coordinate +func NewPoint(x float64, y float64) *Point { + pointTemp := Point{ + tdCommon: tdCommon{Type: "point"}, + X: x, + Y: y, + } + + return &pointTemp +} diff --git a/tdlib/poll.go b/tdlib/poll.go new file mode 100644 index 0000000..0ef81fb --- /dev/null +++ b/tdlib/poll.go @@ -0,0 +1,98 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// Poll Describes a poll +type Poll struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique poll identifier + Question string `json:"question"` // Poll question; 1-300 characters + Options []PollOption `json:"options"` // List of poll answer options + TotalVoterCount int32 `json:"total_voter_count"` // Total number of voters, participating in the poll + RecentVoterUserIDs []int64 `json:"recent_voter_user_ids"` // User identifiers of recent voters, if the poll is non-anonymous + IsAnonymous bool `json:"is_anonymous"` // True, if the poll is anonymous + Type PollType `json:"type"` // Type of the poll + OpenPeriod int32 `json:"open_period"` // Amount of time the poll will be active after creation, in seconds + CloseDate int32 `json:"close_date"` // Point in time (Unix timestamp) when the poll will be automatically closed + IsClosed bool `json:"is_closed"` // True, if the poll is closed +} + +// MessageType return the string telegram-type of Poll +func (poll *Poll) MessageType() string { + return "poll" +} + +// NewPoll creates a new Poll +// +// @param iD Unique poll identifier +// @param question Poll question; 1-300 characters +// @param options List of poll answer options +// @param totalVoterCount Total number of voters, participating in the poll +// @param recentVoterUserIDs User identifiers of recent voters, if the poll is non-anonymous +// @param isAnonymous True, if the poll is anonymous +// @param typeParam Type of the poll +// @param openPeriod Amount of time the poll will be active after creation, in seconds +// @param closeDate Point in time (Unix timestamp) when the poll will be automatically closed +// @param isClosed True, if the poll is closed +func NewPoll(iD JSONInt64, question string, options []PollOption, totalVoterCount int32, recentVoterUserIDs []int64, isAnonymous bool, typeParam PollType, openPeriod int32, closeDate int32, isClosed bool) *Poll { + pollTemp := Poll{ + tdCommon: tdCommon{Type: "poll"}, + ID: iD, + Question: question, + Options: options, + TotalVoterCount: totalVoterCount, + RecentVoterUserIDs: recentVoterUserIDs, + IsAnonymous: isAnonymous, + Type: typeParam, + OpenPeriod: openPeriod, + CloseDate: closeDate, + IsClosed: isClosed, + } + + return &pollTemp +} + +// UnmarshalJSON unmarshal to json +func (poll *Poll) 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 poll identifier + Question string `json:"question"` // Poll question; 1-300 characters + Options []PollOption `json:"options"` // List of poll answer options + TotalVoterCount int32 `json:"total_voter_count"` // Total number of voters, participating in the poll + RecentVoterUserIDs []int64 `json:"recent_voter_user_ids"` // User identifiers of recent voters, if the poll is non-anonymous + IsAnonymous bool `json:"is_anonymous"` // True, if the poll is anonymous + OpenPeriod int32 `json:"open_period"` // Amount of time the poll will be active after creation, in seconds + CloseDate int32 `json:"close_date"` // Point in time (Unix timestamp) when the poll will be automatically closed + IsClosed bool `json:"is_closed"` // True, if the poll is closed + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + poll.tdCommon = tempObj.tdCommon + poll.ID = tempObj.ID + poll.Question = tempObj.Question + poll.Options = tempObj.Options + poll.TotalVoterCount = tempObj.TotalVoterCount + poll.RecentVoterUserIDs = tempObj.RecentVoterUserIDs + poll.IsAnonymous = tempObj.IsAnonymous + poll.OpenPeriod = tempObj.OpenPeriod + poll.CloseDate = tempObj.CloseDate + poll.IsClosed = tempObj.IsClosed + + fieldType, _ := unmarshalPollType(objMap["type"]) + poll.Type = fieldType + + return nil +} diff --git a/tdlib/pollOption.go b/tdlib/pollOption.go new file mode 100644 index 0000000..15881e0 --- /dev/null +++ b/tdlib/pollOption.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PollOption Describes one answer option of a poll +type PollOption struct { + tdCommon + Text string `json:"text"` // Option text; 1-100 characters + VoterCount int32 `json:"voter_count"` // Number of voters for this option, available only for closed or voted polls + VotePercentage int32 `json:"vote_percentage"` // The percentage of votes for this option; 0-100 + IsChosen bool `json:"is_chosen"` // True, if the option was chosen by the user + IsBeingChosen bool `json:"is_being_chosen"` // True, if the option is being chosen by a pending setPollAnswer request +} + +// MessageType return the string telegram-type of PollOption +func (pollOption *PollOption) MessageType() string { + return "pollOption" +} + +// NewPollOption creates a new PollOption +// +// @param text Option text; 1-100 characters +// @param voterCount Number of voters for this option, available only for closed or voted polls +// @param votePercentage The percentage of votes for this option; 0-100 +// @param isChosen True, if the option was chosen by the user +// @param isBeingChosen True, if the option is being chosen by a pending setPollAnswer request +func NewPollOption(text string, voterCount int32, votePercentage int32, isChosen bool, isBeingChosen bool) *PollOption { + pollOptionTemp := PollOption{ + tdCommon: tdCommon{Type: "pollOption"}, + Text: text, + VoterCount: voterCount, + VotePercentage: votePercentage, + IsChosen: isChosen, + IsBeingChosen: isBeingChosen, + } + + return &pollOptionTemp +} diff --git a/tdlib/pollType.go b/tdlib/pollType.go new file mode 100644 index 0000000..6cfc4bd --- /dev/null +++ b/tdlib/pollType.go @@ -0,0 +1,108 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PollType Describes the type of a poll +type PollType interface { + GetPollTypeEnum() PollTypeEnum +} + +// PollTypeEnum Alias for abstract PollType 'Sub-Classes', used as constant-enum here +type PollTypeEnum string + +// PollType enums +const ( + PollTypeRegularType PollTypeEnum = "pollTypeRegular" + PollTypeQuizType PollTypeEnum = "pollTypeQuiz" +) + +func unmarshalPollType(rawMsg *json.RawMessage) (PollType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PollTypeEnum(objMap["@type"].(string)) { + case PollTypeRegularType: + var pollTypeRegular PollTypeRegular + err := json.Unmarshal(*rawMsg, &pollTypeRegular) + return &pollTypeRegular, err + + case PollTypeQuizType: + var pollTypeQuiz PollTypeQuiz + err := json.Unmarshal(*rawMsg, &pollTypeQuiz) + return &pollTypeQuiz, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// PollTypeRegular A regular poll +type PollTypeRegular struct { + tdCommon + AllowMultipleAnswers bool `json:"allow_multiple_answers"` // True, if multiple answer options can be chosen simultaneously +} + +// MessageType return the string telegram-type of PollTypeRegular +func (pollTypeRegular *PollTypeRegular) MessageType() string { + return "pollTypeRegular" +} + +// NewPollTypeRegular creates a new PollTypeRegular +// +// @param allowMultipleAnswers True, if multiple answer options can be chosen simultaneously +func NewPollTypeRegular(allowMultipleAnswers bool) *PollTypeRegular { + pollTypeRegularTemp := PollTypeRegular{ + tdCommon: tdCommon{Type: "pollTypeRegular"}, + AllowMultipleAnswers: allowMultipleAnswers, + } + + return &pollTypeRegularTemp +} + +// GetPollTypeEnum return the enum type of this object +func (pollTypeRegular *PollTypeRegular) GetPollTypeEnum() PollTypeEnum { + return PollTypeRegularType +} + +// PollTypeQuiz A poll in quiz mode, which has exactly one correct answer option and can be answered only once +type PollTypeQuiz struct { + tdCommon + CorrectOptionID int32 `json:"correct_option_id"` // 0-based identifier of the correct answer option; -1 for a yet unanswered poll + Explanation *FormattedText `json:"explanation"` // Text that is shown when the user chooses an incorrect answer or taps on the lamp icon; 0-200 characters with at most 2 line feeds; empty for a yet unanswered poll +} + +// MessageType return the string telegram-type of PollTypeQuiz +func (pollTypeQuiz *PollTypeQuiz) MessageType() string { + return "pollTypeQuiz" +} + +// NewPollTypeQuiz creates a new PollTypeQuiz +// +// @param correctOptionID 0-based identifier of the correct answer option; -1 for a yet unanswered poll +// @param explanation Text that is shown when the user chooses an incorrect answer or taps on the lamp icon; 0-200 characters with at most 2 line feeds; empty for a yet unanswered poll +func NewPollTypeQuiz(correctOptionID int32, explanation *FormattedText) *PollTypeQuiz { + pollTypeQuizTemp := PollTypeQuiz{ + tdCommon: tdCommon{Type: "pollTypeQuiz"}, + CorrectOptionID: correctOptionID, + Explanation: explanation, + } + + return &pollTypeQuizTemp +} + +// GetPollTypeEnum return the enum type of this object +func (pollTypeQuiz *PollTypeQuiz) GetPollTypeEnum() PollTypeEnum { + return PollTypeQuizType +} diff --git a/tdlib/profilePhoto.go b/tdlib/profilePhoto.go new file mode 100644 index 0000000..151d8ed --- /dev/null +++ b/tdlib/profilePhoto.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 user profile photos + Small *File `json:"small"` // A small (160x160) user profile photo. The file can be downloaded only before the photo is changed + Big *File `json:"big"` // A big (640x640) user profile photo. The file can be downloaded only before the photo is changed + Minithumbnail *Minithumbnail `json:"minithumbnail"` // User profile photo minithumbnail; may be null + HasAnimation bool `json:"has_animation"` // True, if the photo has animated variant +} + +// 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 user profile photos +// @param small A small (160x160) user profile photo. The file can be downloaded only before the photo is changed +// @param big A big (640x640) user profile photo. The file can be downloaded only before the photo is changed +// @param minithumbnail User profile photo minithumbnail; may be null +// @param hasAnimation True, if the photo has animated variant +func NewProfilePhoto(iD JSONInt64, small *File, big *File, minithumbnail *Minithumbnail, hasAnimation bool) *ProfilePhoto { + profilePhotoTemp := ProfilePhoto{ + tdCommon: tdCommon{Type: "profilePhoto"}, + ID: iD, + Small: small, + Big: big, + Minithumbnail: minithumbnail, + HasAnimation: hasAnimation, + } + + return &profilePhotoTemp +} diff --git a/tdlib/proxies.go b/tdlib/proxies.go new file mode 100644 index 0000000..8e88c21 --- /dev/null +++ b/tdlib/proxies.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/proxy.go b/tdlib/proxy.go new file mode 100644 index 0000000..82949de --- /dev/null +++ b/tdlib/proxy.go @@ -0,0 +1,79 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 +} diff --git a/tdlib/proxyType.go b/tdlib/proxyType.go new file mode 100644 index 0000000..1f3f43d --- /dev/null +++ b/tdlib/proxyType.go @@ -0,0 +1,148 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ProxyType Describes the type of a proxy server +type ProxyType interface { + GetProxyTypeEnum() ProxyTypeEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/publicChatType.go b/tdlib/publicChatType.go new file mode 100644 index 0000000..92fde73 --- /dev/null +++ b/tdlib/publicChatType.go @@ -0,0 +1,99 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PublicChatType Describes a type of public chats +type PublicChatType interface { + GetPublicChatTypeEnum() PublicChatTypeEnum +} + +// PublicChatTypeEnum Alias for abstract PublicChatType 'Sub-Classes', used as constant-enum here +type PublicChatTypeEnum string + +// PublicChatType enums +const ( + PublicChatTypeHasUsernameType PublicChatTypeEnum = "publicChatTypeHasUsername" + PublicChatTypeIsLocationBasedType PublicChatTypeEnum = "publicChatTypeIsLocationBased" +) + +func unmarshalPublicChatType(rawMsg *json.RawMessage) (PublicChatType, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PublicChatTypeEnum(objMap["@type"].(string)) { + case PublicChatTypeHasUsernameType: + var publicChatTypeHasUsername PublicChatTypeHasUsername + err := json.Unmarshal(*rawMsg, &publicChatTypeHasUsername) + return &publicChatTypeHasUsername, err + + case PublicChatTypeIsLocationBasedType: + var publicChatTypeIsLocationBased PublicChatTypeIsLocationBased + err := json.Unmarshal(*rawMsg, &publicChatTypeIsLocationBased) + return &publicChatTypeIsLocationBased, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// PublicChatTypeHasUsername The chat is public, because it has username +type PublicChatTypeHasUsername struct { + tdCommon +} + +// MessageType return the string telegram-type of PublicChatTypeHasUsername +func (publicChatTypeHasUsername *PublicChatTypeHasUsername) MessageType() string { + return "publicChatTypeHasUsername" +} + +// NewPublicChatTypeHasUsername creates a new PublicChatTypeHasUsername +// +func NewPublicChatTypeHasUsername() *PublicChatTypeHasUsername { + publicChatTypeHasUsernameTemp := PublicChatTypeHasUsername{ + tdCommon: tdCommon{Type: "publicChatTypeHasUsername"}, + } + + return &publicChatTypeHasUsernameTemp +} + +// GetPublicChatTypeEnum return the enum type of this object +func (publicChatTypeHasUsername *PublicChatTypeHasUsername) GetPublicChatTypeEnum() PublicChatTypeEnum { + return PublicChatTypeHasUsernameType +} + +// PublicChatTypeIsLocationBased The chat is public, because it is a location-based supergroup +type PublicChatTypeIsLocationBased struct { + tdCommon +} + +// MessageType return the string telegram-type of PublicChatTypeIsLocationBased +func (publicChatTypeIsLocationBased *PublicChatTypeIsLocationBased) MessageType() string { + return "publicChatTypeIsLocationBased" +} + +// NewPublicChatTypeIsLocationBased creates a new PublicChatTypeIsLocationBased +// +func NewPublicChatTypeIsLocationBased() *PublicChatTypeIsLocationBased { + publicChatTypeIsLocationBasedTemp := PublicChatTypeIsLocationBased{ + tdCommon: tdCommon{Type: "publicChatTypeIsLocationBased"}, + } + + return &publicChatTypeIsLocationBasedTemp +} + +// GetPublicChatTypeEnum return the enum type of this object +func (publicChatTypeIsLocationBased *PublicChatTypeIsLocationBased) GetPublicChatTypeEnum() PublicChatTypeEnum { + return PublicChatTypeIsLocationBasedType +} diff --git a/tdlib/pushMessageContent.go b/tdlib/pushMessageContent.go new file mode 100644 index 0000000..5f10b47 --- /dev/null +++ b/tdlib/pushMessageContent.go @@ -0,0 +1,1033 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// PushMessageContent Contains content of a push message notification +type PushMessageContent interface { + GetPushMessageContentEnum() PushMessageContentEnum +} + +// PushMessageContentEnum Alias for abstract PushMessageContent 'Sub-Classes', used as constant-enum here +type PushMessageContentEnum string + +// PushMessageContent enums +const ( + PushMessageContentHiddenType PushMessageContentEnum = "pushMessageContentHidden" + PushMessageContentAnimationType PushMessageContentEnum = "pushMessageContentAnimation" + PushMessageContentAudioType PushMessageContentEnum = "pushMessageContentAudio" + PushMessageContentContactType PushMessageContentEnum = "pushMessageContentContact" + PushMessageContentContactRegisteredType PushMessageContentEnum = "pushMessageContentContactRegistered" + PushMessageContentDocumentType PushMessageContentEnum = "pushMessageContentDocument" + PushMessageContentGameType PushMessageContentEnum = "pushMessageContentGame" + PushMessageContentGameScoreType PushMessageContentEnum = "pushMessageContentGameScore" + PushMessageContentInvoiceType PushMessageContentEnum = "pushMessageContentInvoice" + PushMessageContentLocationType PushMessageContentEnum = "pushMessageContentLocation" + PushMessageContentPhotoType PushMessageContentEnum = "pushMessageContentPhoto" + PushMessageContentPollType PushMessageContentEnum = "pushMessageContentPoll" + PushMessageContentScreenshotTakenType PushMessageContentEnum = "pushMessageContentScreenshotTaken" + PushMessageContentStickerType PushMessageContentEnum = "pushMessageContentSticker" + PushMessageContentTextType PushMessageContentEnum = "pushMessageContentText" + PushMessageContentVideoType PushMessageContentEnum = "pushMessageContentVideo" + PushMessageContentVideoNoteType PushMessageContentEnum = "pushMessageContentVideoNote" + PushMessageContentVoiceNoteType PushMessageContentEnum = "pushMessageContentVoiceNote" + PushMessageContentBasicGroupChatCreateType PushMessageContentEnum = "pushMessageContentBasicGroupChatCreate" + PushMessageContentChatAddMembersType PushMessageContentEnum = "pushMessageContentChatAddMembers" + PushMessageContentChatChangePhotoType PushMessageContentEnum = "pushMessageContentChatChangePhoto" + PushMessageContentChatChangeTitleType PushMessageContentEnum = "pushMessageContentChatChangeTitle" + PushMessageContentChatChangeThemeType PushMessageContentEnum = "pushMessageContentChatChangeTheme" + PushMessageContentChatDeleteMemberType PushMessageContentEnum = "pushMessageContentChatDeleteMember" + PushMessageContentChatJoinByLinkType PushMessageContentEnum = "pushMessageContentChatJoinByLink" + PushMessageContentMessageForwardsType PushMessageContentEnum = "pushMessageContentMessageForwards" + PushMessageContentMediaAlbumType PushMessageContentEnum = "pushMessageContentMediaAlbum" +) + +func unmarshalPushMessageContent(rawMsg *json.RawMessage) (PushMessageContent, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch PushMessageContentEnum(objMap["@type"].(string)) { + case PushMessageContentHiddenType: + var pushMessageContentHidden PushMessageContentHidden + err := json.Unmarshal(*rawMsg, &pushMessageContentHidden) + return &pushMessageContentHidden, err + + case PushMessageContentAnimationType: + var pushMessageContentAnimation PushMessageContentAnimation + err := json.Unmarshal(*rawMsg, &pushMessageContentAnimation) + return &pushMessageContentAnimation, err + + case PushMessageContentAudioType: + var pushMessageContentAudio PushMessageContentAudio + err := json.Unmarshal(*rawMsg, &pushMessageContentAudio) + return &pushMessageContentAudio, err + + case PushMessageContentContactType: + var pushMessageContentContact PushMessageContentContact + err := json.Unmarshal(*rawMsg, &pushMessageContentContact) + return &pushMessageContentContact, err + + case PushMessageContentContactRegisteredType: + var pushMessageContentContactRegistered PushMessageContentContactRegistered + err := json.Unmarshal(*rawMsg, &pushMessageContentContactRegistered) + return &pushMessageContentContactRegistered, err + + case PushMessageContentDocumentType: + var pushMessageContentDocument PushMessageContentDocument + err := json.Unmarshal(*rawMsg, &pushMessageContentDocument) + return &pushMessageContentDocument, err + + case PushMessageContentGameType: + var pushMessageContentGame PushMessageContentGame + err := json.Unmarshal(*rawMsg, &pushMessageContentGame) + return &pushMessageContentGame, err + + case PushMessageContentGameScoreType: + var pushMessageContentGameScore PushMessageContentGameScore + err := json.Unmarshal(*rawMsg, &pushMessageContentGameScore) + return &pushMessageContentGameScore, err + + case PushMessageContentInvoiceType: + var pushMessageContentInvoice PushMessageContentInvoice + err := json.Unmarshal(*rawMsg, &pushMessageContentInvoice) + return &pushMessageContentInvoice, err + + case PushMessageContentLocationType: + var pushMessageContentLocation PushMessageContentLocation + err := json.Unmarshal(*rawMsg, &pushMessageContentLocation) + return &pushMessageContentLocation, err + + case PushMessageContentPhotoType: + var pushMessageContentPhoto PushMessageContentPhoto + err := json.Unmarshal(*rawMsg, &pushMessageContentPhoto) + return &pushMessageContentPhoto, err + + case PushMessageContentPollType: + var pushMessageContentPoll PushMessageContentPoll + err := json.Unmarshal(*rawMsg, &pushMessageContentPoll) + return &pushMessageContentPoll, err + + case PushMessageContentScreenshotTakenType: + var pushMessageContentScreenshotTaken PushMessageContentScreenshotTaken + err := json.Unmarshal(*rawMsg, &pushMessageContentScreenshotTaken) + return &pushMessageContentScreenshotTaken, err + + case PushMessageContentStickerType: + var pushMessageContentSticker PushMessageContentSticker + err := json.Unmarshal(*rawMsg, &pushMessageContentSticker) + return &pushMessageContentSticker, err + + case PushMessageContentTextType: + var pushMessageContentText PushMessageContentText + err := json.Unmarshal(*rawMsg, &pushMessageContentText) + return &pushMessageContentText, err + + case PushMessageContentVideoType: + var pushMessageContentVideo PushMessageContentVideo + err := json.Unmarshal(*rawMsg, &pushMessageContentVideo) + return &pushMessageContentVideo, err + + case PushMessageContentVideoNoteType: + var pushMessageContentVideoNote PushMessageContentVideoNote + err := json.Unmarshal(*rawMsg, &pushMessageContentVideoNote) + return &pushMessageContentVideoNote, err + + case PushMessageContentVoiceNoteType: + var pushMessageContentVoiceNote PushMessageContentVoiceNote + err := json.Unmarshal(*rawMsg, &pushMessageContentVoiceNote) + return &pushMessageContentVoiceNote, err + + case PushMessageContentBasicGroupChatCreateType: + var pushMessageContentBasicGroupChatCreate PushMessageContentBasicGroupChatCreate + err := json.Unmarshal(*rawMsg, &pushMessageContentBasicGroupChatCreate) + return &pushMessageContentBasicGroupChatCreate, err + + case PushMessageContentChatAddMembersType: + var pushMessageContentChatAddMembers PushMessageContentChatAddMembers + err := json.Unmarshal(*rawMsg, &pushMessageContentChatAddMembers) + return &pushMessageContentChatAddMembers, err + + case PushMessageContentChatChangePhotoType: + var pushMessageContentChatChangePhoto PushMessageContentChatChangePhoto + err := json.Unmarshal(*rawMsg, &pushMessageContentChatChangePhoto) + return &pushMessageContentChatChangePhoto, err + + case PushMessageContentChatChangeTitleType: + var pushMessageContentChatChangeTitle PushMessageContentChatChangeTitle + err := json.Unmarshal(*rawMsg, &pushMessageContentChatChangeTitle) + return &pushMessageContentChatChangeTitle, err + + case PushMessageContentChatChangeThemeType: + var pushMessageContentChatChangeTheme PushMessageContentChatChangeTheme + err := json.Unmarshal(*rawMsg, &pushMessageContentChatChangeTheme) + return &pushMessageContentChatChangeTheme, err + + case PushMessageContentChatDeleteMemberType: + var pushMessageContentChatDeleteMember PushMessageContentChatDeleteMember + err := json.Unmarshal(*rawMsg, &pushMessageContentChatDeleteMember) + return &pushMessageContentChatDeleteMember, err + + case PushMessageContentChatJoinByLinkType: + var pushMessageContentChatJoinByLink PushMessageContentChatJoinByLink + err := json.Unmarshal(*rawMsg, &pushMessageContentChatJoinByLink) + return &pushMessageContentChatJoinByLink, err + + case PushMessageContentMessageForwardsType: + var pushMessageContentMessageForwards PushMessageContentMessageForwards + err := json.Unmarshal(*rawMsg, &pushMessageContentMessageForwards) + return &pushMessageContentMessageForwards, err + + case PushMessageContentMediaAlbumType: + var pushMessageContentMediaAlbum PushMessageContentMediaAlbum + err := json.Unmarshal(*rawMsg, &pushMessageContentMediaAlbum) + return &pushMessageContentMediaAlbum, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// PushMessageContentHidden A general message with hidden content +type PushMessageContentHidden struct { + tdCommon + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentHidden +func (pushMessageContentHidden *PushMessageContentHidden) MessageType() string { + return "pushMessageContentHidden" +} + +// NewPushMessageContentHidden creates a new PushMessageContentHidden +// +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentHidden(isPinned bool) *PushMessageContentHidden { + pushMessageContentHiddenTemp := PushMessageContentHidden{ + tdCommon: tdCommon{Type: "pushMessageContentHidden"}, + IsPinned: isPinned, + } + + return &pushMessageContentHiddenTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentHidden *PushMessageContentHidden) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentHiddenType +} + +// PushMessageContentAnimation An animation message (GIF-style). +type PushMessageContentAnimation struct { + tdCommon + Animation *Animation `json:"animation"` // Message content; may be null + Caption string `json:"caption"` // Animation caption + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentAnimation +func (pushMessageContentAnimation *PushMessageContentAnimation) MessageType() string { + return "pushMessageContentAnimation" +} + +// NewPushMessageContentAnimation creates a new PushMessageContentAnimation +// +// @param animation Message content; may be null +// @param caption Animation caption +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentAnimation(animation *Animation, caption string, isPinned bool) *PushMessageContentAnimation { + pushMessageContentAnimationTemp := PushMessageContentAnimation{ + tdCommon: tdCommon{Type: "pushMessageContentAnimation"}, + Animation: animation, + Caption: caption, + IsPinned: isPinned, + } + + return &pushMessageContentAnimationTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentAnimation *PushMessageContentAnimation) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentAnimationType +} + +// PushMessageContentAudio An audio message +type PushMessageContentAudio struct { + tdCommon + Audio *Audio `json:"audio"` // Message content; may be null + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentAudio +func (pushMessageContentAudio *PushMessageContentAudio) MessageType() string { + return "pushMessageContentAudio" +} + +// NewPushMessageContentAudio creates a new PushMessageContentAudio +// +// @param audio Message content; may be null +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentAudio(audio *Audio, isPinned bool) *PushMessageContentAudio { + pushMessageContentAudioTemp := PushMessageContentAudio{ + tdCommon: tdCommon{Type: "pushMessageContentAudio"}, + Audio: audio, + IsPinned: isPinned, + } + + return &pushMessageContentAudioTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentAudio *PushMessageContentAudio) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentAudioType +} + +// PushMessageContentContact A message with a user contact +type PushMessageContentContact struct { + tdCommon + Name string `json:"name"` // Contact's name + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentContact +func (pushMessageContentContact *PushMessageContentContact) MessageType() string { + return "pushMessageContentContact" +} + +// NewPushMessageContentContact creates a new PushMessageContentContact +// +// @param name Contact's name +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentContact(name string, isPinned bool) *PushMessageContentContact { + pushMessageContentContactTemp := PushMessageContentContact{ + tdCommon: tdCommon{Type: "pushMessageContentContact"}, + Name: name, + IsPinned: isPinned, + } + + return &pushMessageContentContactTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentContact *PushMessageContentContact) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentContactType +} + +// PushMessageContentContactRegistered A contact has registered with Telegram +type PushMessageContentContactRegistered struct { + tdCommon +} + +// MessageType return the string telegram-type of PushMessageContentContactRegistered +func (pushMessageContentContactRegistered *PushMessageContentContactRegistered) MessageType() string { + return "pushMessageContentContactRegistered" +} + +// NewPushMessageContentContactRegistered creates a new PushMessageContentContactRegistered +// +func NewPushMessageContentContactRegistered() *PushMessageContentContactRegistered { + pushMessageContentContactRegisteredTemp := PushMessageContentContactRegistered{ + tdCommon: tdCommon{Type: "pushMessageContentContactRegistered"}, + } + + return &pushMessageContentContactRegisteredTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentContactRegistered *PushMessageContentContactRegistered) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentContactRegisteredType +} + +// PushMessageContentDocument A document message (a general file) +type PushMessageContentDocument struct { + tdCommon + Document *Document `json:"document"` // Message content; may be null + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentDocument +func (pushMessageContentDocument *PushMessageContentDocument) MessageType() string { + return "pushMessageContentDocument" +} + +// NewPushMessageContentDocument creates a new PushMessageContentDocument +// +// @param document Message content; may be null +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentDocument(document *Document, isPinned bool) *PushMessageContentDocument { + pushMessageContentDocumentTemp := PushMessageContentDocument{ + tdCommon: tdCommon{Type: "pushMessageContentDocument"}, + Document: document, + IsPinned: isPinned, + } + + return &pushMessageContentDocumentTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentDocument *PushMessageContentDocument) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentDocumentType +} + +// PushMessageContentGame A message with a game +type PushMessageContentGame struct { + tdCommon + Title string `json:"title"` // Game title, empty for pinned game message + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentGame +func (pushMessageContentGame *PushMessageContentGame) MessageType() string { + return "pushMessageContentGame" +} + +// NewPushMessageContentGame creates a new PushMessageContentGame +// +// @param title Game title, empty for pinned game message +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentGame(title string, isPinned bool) *PushMessageContentGame { + pushMessageContentGameTemp := PushMessageContentGame{ + tdCommon: tdCommon{Type: "pushMessageContentGame"}, + Title: title, + IsPinned: isPinned, + } + + return &pushMessageContentGameTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentGame *PushMessageContentGame) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentGameType +} + +// PushMessageContentGameScore A new high score was achieved in a game +type PushMessageContentGameScore struct { + tdCommon + Title string `json:"title"` // Game title, empty for pinned message + Score int32 `json:"score"` // New score, 0 for pinned message + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentGameScore +func (pushMessageContentGameScore *PushMessageContentGameScore) MessageType() string { + return "pushMessageContentGameScore" +} + +// NewPushMessageContentGameScore creates a new PushMessageContentGameScore +// +// @param title Game title, empty for pinned message +// @param score New score, 0 for pinned message +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentGameScore(title string, score int32, isPinned bool) *PushMessageContentGameScore { + pushMessageContentGameScoreTemp := PushMessageContentGameScore{ + tdCommon: tdCommon{Type: "pushMessageContentGameScore"}, + Title: title, + Score: score, + IsPinned: isPinned, + } + + return &pushMessageContentGameScoreTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentGameScore *PushMessageContentGameScore) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentGameScoreType +} + +// PushMessageContentInvoice A message with an invoice from a bot +type PushMessageContentInvoice struct { + tdCommon + Price string `json:"price"` // Product price + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentInvoice +func (pushMessageContentInvoice *PushMessageContentInvoice) MessageType() string { + return "pushMessageContentInvoice" +} + +// NewPushMessageContentInvoice creates a new PushMessageContentInvoice +// +// @param price Product price +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentInvoice(price string, isPinned bool) *PushMessageContentInvoice { + pushMessageContentInvoiceTemp := PushMessageContentInvoice{ + tdCommon: tdCommon{Type: "pushMessageContentInvoice"}, + Price: price, + IsPinned: isPinned, + } + + return &pushMessageContentInvoiceTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentInvoice *PushMessageContentInvoice) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentInvoiceType +} + +// PushMessageContentLocation A message with a location +type PushMessageContentLocation struct { + tdCommon + IsLive bool `json:"is_live"` // True, if the location is live + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentLocation +func (pushMessageContentLocation *PushMessageContentLocation) MessageType() string { + return "pushMessageContentLocation" +} + +// NewPushMessageContentLocation creates a new PushMessageContentLocation +// +// @param isLive True, if the location is live +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentLocation(isLive bool, isPinned bool) *PushMessageContentLocation { + pushMessageContentLocationTemp := PushMessageContentLocation{ + tdCommon: tdCommon{Type: "pushMessageContentLocation"}, + IsLive: isLive, + IsPinned: isPinned, + } + + return &pushMessageContentLocationTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentLocation *PushMessageContentLocation) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentLocationType +} + +// PushMessageContentPhoto A photo message +type PushMessageContentPhoto struct { + tdCommon + Photo *Photo `json:"photo"` // Message content; may be null + Caption string `json:"caption"` // Photo caption + IsSecret bool `json:"is_secret"` // True, if the photo is secret + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentPhoto +func (pushMessageContentPhoto *PushMessageContentPhoto) MessageType() string { + return "pushMessageContentPhoto" +} + +// NewPushMessageContentPhoto creates a new PushMessageContentPhoto +// +// @param photo Message content; may be null +// @param caption Photo caption +// @param isSecret True, if the photo is secret +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentPhoto(photo *Photo, caption string, isSecret bool, isPinned bool) *PushMessageContentPhoto { + pushMessageContentPhotoTemp := PushMessageContentPhoto{ + tdCommon: tdCommon{Type: "pushMessageContentPhoto"}, + Photo: photo, + Caption: caption, + IsSecret: isSecret, + IsPinned: isPinned, + } + + return &pushMessageContentPhotoTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentPhoto *PushMessageContentPhoto) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentPhotoType +} + +// PushMessageContentPoll A message with a poll +type PushMessageContentPoll struct { + tdCommon + Question string `json:"question"` // Poll question + IsRegular bool `json:"is_regular"` // True, if the poll is regular and not in quiz mode + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentPoll +func (pushMessageContentPoll *PushMessageContentPoll) MessageType() string { + return "pushMessageContentPoll" +} + +// NewPushMessageContentPoll creates a new PushMessageContentPoll +// +// @param question Poll question +// @param isRegular True, if the poll is regular and not in quiz mode +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentPoll(question string, isRegular bool, isPinned bool) *PushMessageContentPoll { + pushMessageContentPollTemp := PushMessageContentPoll{ + tdCommon: tdCommon{Type: "pushMessageContentPoll"}, + Question: question, + IsRegular: isRegular, + IsPinned: isPinned, + } + + return &pushMessageContentPollTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentPoll *PushMessageContentPoll) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentPollType +} + +// PushMessageContentScreenshotTaken A screenshot of a message in the chat has been taken +type PushMessageContentScreenshotTaken struct { + tdCommon +} + +// MessageType return the string telegram-type of PushMessageContentScreenshotTaken +func (pushMessageContentScreenshotTaken *PushMessageContentScreenshotTaken) MessageType() string { + return "pushMessageContentScreenshotTaken" +} + +// NewPushMessageContentScreenshotTaken creates a new PushMessageContentScreenshotTaken +// +func NewPushMessageContentScreenshotTaken() *PushMessageContentScreenshotTaken { + pushMessageContentScreenshotTakenTemp := PushMessageContentScreenshotTaken{ + tdCommon: tdCommon{Type: "pushMessageContentScreenshotTaken"}, + } + + return &pushMessageContentScreenshotTakenTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentScreenshotTaken *PushMessageContentScreenshotTaken) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentScreenshotTakenType +} + +// PushMessageContentSticker A message with a sticker +type PushMessageContentSticker struct { + tdCommon + Sticker *Sticker `json:"sticker"` // Message content; may be null + Emoji string `json:"emoji"` // Emoji corresponding to the sticker; may be empty + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentSticker +func (pushMessageContentSticker *PushMessageContentSticker) MessageType() string { + return "pushMessageContentSticker" +} + +// NewPushMessageContentSticker creates a new PushMessageContentSticker +// +// @param sticker Message content; may be null +// @param emoji Emoji corresponding to the sticker; may be empty +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentSticker(sticker *Sticker, emoji string, isPinned bool) *PushMessageContentSticker { + pushMessageContentStickerTemp := PushMessageContentSticker{ + tdCommon: tdCommon{Type: "pushMessageContentSticker"}, + Sticker: sticker, + Emoji: emoji, + IsPinned: isPinned, + } + + return &pushMessageContentStickerTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentSticker *PushMessageContentSticker) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentStickerType +} + +// PushMessageContentText A text message +type PushMessageContentText struct { + tdCommon + Text string `json:"text"` // Message text + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentText +func (pushMessageContentText *PushMessageContentText) MessageType() string { + return "pushMessageContentText" +} + +// NewPushMessageContentText creates a new PushMessageContentText +// +// @param text Message text +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentText(text string, isPinned bool) *PushMessageContentText { + pushMessageContentTextTemp := PushMessageContentText{ + tdCommon: tdCommon{Type: "pushMessageContentText"}, + Text: text, + IsPinned: isPinned, + } + + return &pushMessageContentTextTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentText *PushMessageContentText) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentTextType +} + +// PushMessageContentVideo A video message +type PushMessageContentVideo struct { + tdCommon + Video *Video `json:"video"` // Message content; may be null + Caption string `json:"caption"` // Video caption + IsSecret bool `json:"is_secret"` // True, if the video is secret + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentVideo +func (pushMessageContentVideo *PushMessageContentVideo) MessageType() string { + return "pushMessageContentVideo" +} + +// NewPushMessageContentVideo creates a new PushMessageContentVideo +// +// @param video Message content; may be null +// @param caption Video caption +// @param isSecret True, if the video is secret +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentVideo(video *Video, caption string, isSecret bool, isPinned bool) *PushMessageContentVideo { + pushMessageContentVideoTemp := PushMessageContentVideo{ + tdCommon: tdCommon{Type: "pushMessageContentVideo"}, + Video: video, + Caption: caption, + IsSecret: isSecret, + IsPinned: isPinned, + } + + return &pushMessageContentVideoTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentVideo *PushMessageContentVideo) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentVideoType +} + +// PushMessageContentVideoNote A video note message +type PushMessageContentVideoNote struct { + tdCommon + VideoNote *VideoNote `json:"video_note"` // Message content; may be null + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentVideoNote +func (pushMessageContentVideoNote *PushMessageContentVideoNote) MessageType() string { + return "pushMessageContentVideoNote" +} + +// NewPushMessageContentVideoNote creates a new PushMessageContentVideoNote +// +// @param videoNote Message content; may be null +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentVideoNote(videoNote *VideoNote, isPinned bool) *PushMessageContentVideoNote { + pushMessageContentVideoNoteTemp := PushMessageContentVideoNote{ + tdCommon: tdCommon{Type: "pushMessageContentVideoNote"}, + VideoNote: videoNote, + IsPinned: isPinned, + } + + return &pushMessageContentVideoNoteTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentVideoNote *PushMessageContentVideoNote) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentVideoNoteType +} + +// PushMessageContentVoiceNote A voice note message +type PushMessageContentVoiceNote struct { + tdCommon + VoiceNote *VoiceNote `json:"voice_note"` // Message content; may be null + IsPinned bool `json:"is_pinned"` // True, if the message is a pinned message with the specified content +} + +// MessageType return the string telegram-type of PushMessageContentVoiceNote +func (pushMessageContentVoiceNote *PushMessageContentVoiceNote) MessageType() string { + return "pushMessageContentVoiceNote" +} + +// NewPushMessageContentVoiceNote creates a new PushMessageContentVoiceNote +// +// @param voiceNote Message content; may be null +// @param isPinned True, if the message is a pinned message with the specified content +func NewPushMessageContentVoiceNote(voiceNote *VoiceNote, isPinned bool) *PushMessageContentVoiceNote { + pushMessageContentVoiceNoteTemp := PushMessageContentVoiceNote{ + tdCommon: tdCommon{Type: "pushMessageContentVoiceNote"}, + VoiceNote: voiceNote, + IsPinned: isPinned, + } + + return &pushMessageContentVoiceNoteTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentVoiceNote *PushMessageContentVoiceNote) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentVoiceNoteType +} + +// PushMessageContentBasicGroupChatCreate A newly created basic group +type PushMessageContentBasicGroupChatCreate struct { + tdCommon +} + +// MessageType return the string telegram-type of PushMessageContentBasicGroupChatCreate +func (pushMessageContentBasicGroupChatCreate *PushMessageContentBasicGroupChatCreate) MessageType() string { + return "pushMessageContentBasicGroupChatCreate" +} + +// NewPushMessageContentBasicGroupChatCreate creates a new PushMessageContentBasicGroupChatCreate +// +func NewPushMessageContentBasicGroupChatCreate() *PushMessageContentBasicGroupChatCreate { + pushMessageContentBasicGroupChatCreateTemp := PushMessageContentBasicGroupChatCreate{ + tdCommon: tdCommon{Type: "pushMessageContentBasicGroupChatCreate"}, + } + + return &pushMessageContentBasicGroupChatCreateTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentBasicGroupChatCreate *PushMessageContentBasicGroupChatCreate) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentBasicGroupChatCreateType +} + +// PushMessageContentChatAddMembers New chat members were invited to a group +type PushMessageContentChatAddMembers struct { + tdCommon + MemberName string `json:"member_name"` // Name of the added member + IsCurrentUser bool `json:"is_current_user"` // True, if the current user was added to the group + IsReturned bool `json:"is_returned"` // True, if the user has returned to the group themselves +} + +// MessageType return the string telegram-type of PushMessageContentChatAddMembers +func (pushMessageContentChatAddMembers *PushMessageContentChatAddMembers) MessageType() string { + return "pushMessageContentChatAddMembers" +} + +// NewPushMessageContentChatAddMembers creates a new PushMessageContentChatAddMembers +// +// @param memberName Name of the added member +// @param isCurrentUser True, if the current user was added to the group +// @param isReturned True, if the user has returned to the group themselves +func NewPushMessageContentChatAddMembers(memberName string, isCurrentUser bool, isReturned bool) *PushMessageContentChatAddMembers { + pushMessageContentChatAddMembersTemp := PushMessageContentChatAddMembers{ + tdCommon: tdCommon{Type: "pushMessageContentChatAddMembers"}, + MemberName: memberName, + IsCurrentUser: isCurrentUser, + IsReturned: isReturned, + } + + return &pushMessageContentChatAddMembersTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentChatAddMembers *PushMessageContentChatAddMembers) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentChatAddMembersType +} + +// PushMessageContentChatChangePhoto A chat photo was edited +type PushMessageContentChatChangePhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of PushMessageContentChatChangePhoto +func (pushMessageContentChatChangePhoto *PushMessageContentChatChangePhoto) MessageType() string { + return "pushMessageContentChatChangePhoto" +} + +// NewPushMessageContentChatChangePhoto creates a new PushMessageContentChatChangePhoto +// +func NewPushMessageContentChatChangePhoto() *PushMessageContentChatChangePhoto { + pushMessageContentChatChangePhotoTemp := PushMessageContentChatChangePhoto{ + tdCommon: tdCommon{Type: "pushMessageContentChatChangePhoto"}, + } + + return &pushMessageContentChatChangePhotoTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentChatChangePhoto *PushMessageContentChatChangePhoto) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentChatChangePhotoType +} + +// PushMessageContentChatChangeTitle A chat title was edited +type PushMessageContentChatChangeTitle struct { + tdCommon + Title string `json:"title"` // New chat title +} + +// MessageType return the string telegram-type of PushMessageContentChatChangeTitle +func (pushMessageContentChatChangeTitle *PushMessageContentChatChangeTitle) MessageType() string { + return "pushMessageContentChatChangeTitle" +} + +// NewPushMessageContentChatChangeTitle creates a new PushMessageContentChatChangeTitle +// +// @param title New chat title +func NewPushMessageContentChatChangeTitle(title string) *PushMessageContentChatChangeTitle { + pushMessageContentChatChangeTitleTemp := PushMessageContentChatChangeTitle{ + tdCommon: tdCommon{Type: "pushMessageContentChatChangeTitle"}, + Title: title, + } + + return &pushMessageContentChatChangeTitleTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentChatChangeTitle *PushMessageContentChatChangeTitle) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentChatChangeTitleType +} + +// PushMessageContentChatChangeTheme A chat theme was edited +type PushMessageContentChatChangeTheme struct { + tdCommon + ThemeName string `json:"theme_name"` // If non-empty, name of a new theme set for the chat. Otherwise chat theme was reset to the default one +} + +// MessageType return the string telegram-type of PushMessageContentChatChangeTheme +func (pushMessageContentChatChangeTheme *PushMessageContentChatChangeTheme) MessageType() string { + return "pushMessageContentChatChangeTheme" +} + +// NewPushMessageContentChatChangeTheme creates a new PushMessageContentChatChangeTheme +// +// @param themeName If non-empty, name of a new theme set for the chat. Otherwise chat theme was reset to the default one +func NewPushMessageContentChatChangeTheme(themeName string) *PushMessageContentChatChangeTheme { + pushMessageContentChatChangeThemeTemp := PushMessageContentChatChangeTheme{ + tdCommon: tdCommon{Type: "pushMessageContentChatChangeTheme"}, + ThemeName: themeName, + } + + return &pushMessageContentChatChangeThemeTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentChatChangeTheme *PushMessageContentChatChangeTheme) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentChatChangeThemeType +} + +// PushMessageContentChatDeleteMember A chat member was deleted +type PushMessageContentChatDeleteMember struct { + tdCommon + MemberName string `json:"member_name"` // Name of the deleted member + IsCurrentUser bool `json:"is_current_user"` // True, if the current user was deleted from the group + IsLeft bool `json:"is_left"` // True, if the user has left the group themselves +} + +// MessageType return the string telegram-type of PushMessageContentChatDeleteMember +func (pushMessageContentChatDeleteMember *PushMessageContentChatDeleteMember) MessageType() string { + return "pushMessageContentChatDeleteMember" +} + +// NewPushMessageContentChatDeleteMember creates a new PushMessageContentChatDeleteMember +// +// @param memberName Name of the deleted member +// @param isCurrentUser True, if the current user was deleted from the group +// @param isLeft True, if the user has left the group themselves +func NewPushMessageContentChatDeleteMember(memberName string, isCurrentUser bool, isLeft bool) *PushMessageContentChatDeleteMember { + pushMessageContentChatDeleteMemberTemp := PushMessageContentChatDeleteMember{ + tdCommon: tdCommon{Type: "pushMessageContentChatDeleteMember"}, + MemberName: memberName, + IsCurrentUser: isCurrentUser, + IsLeft: isLeft, + } + + return &pushMessageContentChatDeleteMemberTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentChatDeleteMember *PushMessageContentChatDeleteMember) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentChatDeleteMemberType +} + +// PushMessageContentChatJoinByLink A new member joined the chat by invite link +type PushMessageContentChatJoinByLink struct { + tdCommon +} + +// MessageType return the string telegram-type of PushMessageContentChatJoinByLink +func (pushMessageContentChatJoinByLink *PushMessageContentChatJoinByLink) MessageType() string { + return "pushMessageContentChatJoinByLink" +} + +// NewPushMessageContentChatJoinByLink creates a new PushMessageContentChatJoinByLink +// +func NewPushMessageContentChatJoinByLink() *PushMessageContentChatJoinByLink { + pushMessageContentChatJoinByLinkTemp := PushMessageContentChatJoinByLink{ + tdCommon: tdCommon{Type: "pushMessageContentChatJoinByLink"}, + } + + return &pushMessageContentChatJoinByLinkTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentChatJoinByLink *PushMessageContentChatJoinByLink) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentChatJoinByLinkType +} + +// PushMessageContentMessageForwards A forwarded messages +type PushMessageContentMessageForwards struct { + tdCommon + TotalCount int32 `json:"total_count"` // Number of forwarded messages +} + +// MessageType return the string telegram-type of PushMessageContentMessageForwards +func (pushMessageContentMessageForwards *PushMessageContentMessageForwards) MessageType() string { + return "pushMessageContentMessageForwards" +} + +// NewPushMessageContentMessageForwards creates a new PushMessageContentMessageForwards +// +// @param totalCount Number of forwarded messages +func NewPushMessageContentMessageForwards(totalCount int32) *PushMessageContentMessageForwards { + pushMessageContentMessageForwardsTemp := PushMessageContentMessageForwards{ + tdCommon: tdCommon{Type: "pushMessageContentMessageForwards"}, + TotalCount: totalCount, + } + + return &pushMessageContentMessageForwardsTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentMessageForwards *PushMessageContentMessageForwards) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentMessageForwardsType +} + +// PushMessageContentMediaAlbum A media album +type PushMessageContentMediaAlbum struct { + tdCommon + TotalCount int32 `json:"total_count"` // Number of messages in the album + HasPhotos bool `json:"has_photos"` // True, if the album has at least one photo + HasVideos bool `json:"has_videos"` // True, if the album has at least one video + HasAudios bool `json:"has_audios"` // True, if the album has at least one audio file + HasDocuments bool `json:"has_documents"` // True, if the album has at least one document +} + +// MessageType return the string telegram-type of PushMessageContentMediaAlbum +func (pushMessageContentMediaAlbum *PushMessageContentMediaAlbum) MessageType() string { + return "pushMessageContentMediaAlbum" +} + +// NewPushMessageContentMediaAlbum creates a new PushMessageContentMediaAlbum +// +// @param totalCount Number of messages in the album +// @param hasPhotos True, if the album has at least one photo +// @param hasVideos True, if the album has at least one video +// @param hasAudios True, if the album has at least one audio file +// @param hasDocuments True, if the album has at least one document +func NewPushMessageContentMediaAlbum(totalCount int32, hasPhotos bool, hasVideos bool, hasAudios bool, hasDocuments bool) *PushMessageContentMediaAlbum { + pushMessageContentMediaAlbumTemp := PushMessageContentMediaAlbum{ + tdCommon: tdCommon{Type: "pushMessageContentMediaAlbum"}, + TotalCount: totalCount, + HasPhotos: hasPhotos, + HasVideos: hasVideos, + HasAudios: hasAudios, + HasDocuments: hasDocuments, + } + + return &pushMessageContentMediaAlbumTemp +} + +// GetPushMessageContentEnum return the enum type of this object +func (pushMessageContentMediaAlbum *PushMessageContentMediaAlbum) GetPushMessageContentEnum() PushMessageContentEnum { + return PushMessageContentMediaAlbumType +} diff --git a/tdlib/pushReceiverID.go b/tdlib/pushReceiverID.go new file mode 100644 index 0000000..328a260 --- /dev/null +++ b/tdlib/pushReceiverID.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// PushReceiverID Contains a globally unique push receiver identifier, which can be used to identify which account has received a push notification +type PushReceiverID struct { + tdCommon + ID JSONInt64 `json:"id"` // The globally unique identifier of push notification subscription +} + +// MessageType return the string telegram-type of PushReceiverID +func (pushReceiverID *PushReceiverID) MessageType() string { + return "pushReceiverId" +} + +// NewPushReceiverID creates a new PushReceiverID +// +// @param iD The globally unique identifier of push notification subscription +func NewPushReceiverID(iD JSONInt64) *PushReceiverID { + pushReceiverIDTemp := PushReceiverID{ + tdCommon: tdCommon{Type: "pushReceiverId"}, + ID: iD, + } + + return &pushReceiverIDTemp +} diff --git a/tdlib/recommendedChatFilter.go b/tdlib/recommendedChatFilter.go new file mode 100644 index 0000000..252e44c --- /dev/null +++ b/tdlib/recommendedChatFilter.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// RecommendedChatFilter Describes a recommended chat filter +type RecommendedChatFilter struct { + tdCommon + Filter *ChatFilter `json:"filter"` // The chat filter + Description string `json:"description"` // Chat filter description +} + +// MessageType return the string telegram-type of RecommendedChatFilter +func (recommendedChatFilter *RecommendedChatFilter) MessageType() string { + return "recommendedChatFilter" +} + +// NewRecommendedChatFilter creates a new RecommendedChatFilter +// +// @param filter The chat filter +// @param description Chat filter description +func NewRecommendedChatFilter(filter *ChatFilter, description string) *RecommendedChatFilter { + recommendedChatFilterTemp := RecommendedChatFilter{ + tdCommon: tdCommon{Type: "recommendedChatFilter"}, + Filter: filter, + Description: description, + } + + return &recommendedChatFilterTemp +} diff --git a/tdlib/recommendedChatFilters.go b/tdlib/recommendedChatFilters.go new file mode 100644 index 0000000..a810f90 --- /dev/null +++ b/tdlib/recommendedChatFilters.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// RecommendedChatFilters Contains a list of recommended chat filters +type RecommendedChatFilters struct { + tdCommon + ChatFilters []RecommendedChatFilter `json:"chat_filters"` // List of recommended chat filters +} + +// MessageType return the string telegram-type of RecommendedChatFilters +func (recommendedChatFilters *RecommendedChatFilters) MessageType() string { + return "recommendedChatFilters" +} + +// NewRecommendedChatFilters creates a new RecommendedChatFilters +// +// @param chatFilters List of recommended chat filters +func NewRecommendedChatFilters(chatFilters []RecommendedChatFilter) *RecommendedChatFilters { + recommendedChatFiltersTemp := RecommendedChatFilters{ + tdCommon: tdCommon{Type: "recommendedChatFilters"}, + ChatFilters: chatFilters, + } + + return &recommendedChatFiltersTemp +} diff --git a/tdlib/recoveryEmailAddress.go b/tdlib/recoveryEmailAddress.go new file mode 100644 index 0000000..13ca6c0 --- /dev/null +++ b/tdlib/recoveryEmailAddress.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/remoteFile.go b/tdlib/remoteFile.go new file mode 100644 index 0000000..c256c8d --- /dev/null +++ b/tdlib/remoteFile.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// RemoteFile Represents a remote file +type RemoteFile struct { + tdCommon + ID string `json:"id"` // Remote file identifier; may be empty. Can be used by the current user across application restarts or even from other devices. Uniquely identifies a file, but a file can have a lot of different valid identifiers. 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. If downloadFile is called on such a file or if it is sent to a secret chat, TDLib starts a file generation process by sending updateFileGenerationStart to the application with the HTTP URL in the original_path and "#url#" as the conversion string. Application should generate the file by downloading it to the specified location + UniqueID string `json:"unique_id"` // Unique file identifier; may be empty if unknown. The unique file identifier which is the same for the same file even for different users and is persistent over time + 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, in bytes; 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 by the current user across application restarts or even from other devices. Uniquely identifies a file, but a file can have a lot of different valid identifiers. 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. If downloadFile is called on such a file or if it is sent to a secret chat, TDLib starts a file generation process by sending updateFileGenerationStart to the application with the HTTP URL in the original_path and "#url#" as the conversion string. Application should generate the file by downloading it to the specified location +// @param uniqueID Unique file identifier; may be empty if unknown. The unique file identifier which is the same for the same file even for different users and is persistent over time +// @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, in bytes; 0 if unknown +func NewRemoteFile(iD string, uniqueID string, isUploadingActive bool, isUploadingCompleted bool, uploadedSize int32) *RemoteFile { + remoteFileTemp := RemoteFile{ + tdCommon: tdCommon{Type: "remoteFile"}, + ID: iD, + UniqueID: uniqueID, + IsUploadingActive: isUploadingActive, + IsUploadingCompleted: isUploadingCompleted, + UploadedSize: uploadedSize, + } + + return &remoteFileTemp +} diff --git a/tdlib/replyMarkup.go b/tdlib/replyMarkup.go new file mode 100644 index 0000000..274ae10 --- /dev/null +++ b/tdlib/replyMarkup.go @@ -0,0 +1,188 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// 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 +} + +// 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" +) + +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)) + } +} + +// ReplyMarkupRemoveKeyboard Instructs application 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 application 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 + InputFieldPlaceholder string `json:"input_field_placeholder"` // If non-empty, the placeholder to be shown in the input field when the reply is active; 0-64 characters +} + +// 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 +// @param inputFieldPlaceholder If non-empty, the placeholder to be shown in the input field when the reply is active; 0-64 characters +func NewReplyMarkupForceReply(isPersonal bool, inputFieldPlaceholder string) *ReplyMarkupForceReply { + replyMarkupForceReplyTemp := ReplyMarkupForceReply{ + tdCommon: tdCommon{Type: "replyMarkupForceReply"}, + IsPersonal: isPersonal, + InputFieldPlaceholder: inputFieldPlaceholder, + } + + 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 application needs to resize the keyboard vertically + OneTime bool `json:"one_time"` // True, if the application 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 + InputFieldPlaceholder string `json:"input_field_placeholder"` // If non-empty, the placeholder to be shown in the input field when the keyboard is active; 0-64 characters +} + +// 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 application needs to resize the keyboard vertically +// @param oneTime True, if the application 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 +// @param inputFieldPlaceholder If non-empty, the placeholder to be shown in the input field when the keyboard is active; 0-64 characters +func NewReplyMarkupShowKeyboard(rows [][]KeyboardButton, resizeKeyboard bool, oneTime bool, isPersonal bool, inputFieldPlaceholder string) *ReplyMarkupShowKeyboard { + replyMarkupShowKeyboardTemp := ReplyMarkupShowKeyboard{ + tdCommon: tdCommon{Type: "replyMarkupShowKeyboard"}, + Rows: rows, + ResizeKeyboard: resizeKeyboard, + OneTime: oneTime, + IsPersonal: isPersonal, + InputFieldPlaceholder: inputFieldPlaceholder, + } + + 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 +} diff --git a/tdlib/resetPasswordResult.go b/tdlib/resetPasswordResult.go new file mode 100644 index 0000000..48f7867 --- /dev/null +++ b/tdlib/resetPasswordResult.go @@ -0,0 +1,136 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ResetPasswordResult Represents result of 2-step verification password reset +type ResetPasswordResult interface { + GetResetPasswordResultEnum() ResetPasswordResultEnum +} + +// ResetPasswordResultEnum Alias for abstract ResetPasswordResult 'Sub-Classes', used as constant-enum here +type ResetPasswordResultEnum string + +// ResetPasswordResult enums +const ( + ResetPasswordResultOkType ResetPasswordResultEnum = "resetPasswordResultOk" + ResetPasswordResultPendingType ResetPasswordResultEnum = "resetPasswordResultPending" + ResetPasswordResultDeclinedType ResetPasswordResultEnum = "resetPasswordResultDeclined" +) + +func unmarshalResetPasswordResult(rawMsg *json.RawMessage) (ResetPasswordResult, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ResetPasswordResultEnum(objMap["@type"].(string)) { + case ResetPasswordResultOkType: + var resetPasswordResultOk ResetPasswordResultOk + err := json.Unmarshal(*rawMsg, &resetPasswordResultOk) + return &resetPasswordResultOk, err + + case ResetPasswordResultPendingType: + var resetPasswordResultPending ResetPasswordResultPending + err := json.Unmarshal(*rawMsg, &resetPasswordResultPending) + return &resetPasswordResultPending, err + + case ResetPasswordResultDeclinedType: + var resetPasswordResultDeclined ResetPasswordResultDeclined + err := json.Unmarshal(*rawMsg, &resetPasswordResultDeclined) + return &resetPasswordResultDeclined, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// ResetPasswordResultOk The password was reset +type ResetPasswordResultOk struct { + tdCommon +} + +// MessageType return the string telegram-type of ResetPasswordResultOk +func (resetPasswordResultOk *ResetPasswordResultOk) MessageType() string { + return "resetPasswordResultOk" +} + +// NewResetPasswordResultOk creates a new ResetPasswordResultOk +// +func NewResetPasswordResultOk() *ResetPasswordResultOk { + resetPasswordResultOkTemp := ResetPasswordResultOk{ + tdCommon: tdCommon{Type: "resetPasswordResultOk"}, + } + + return &resetPasswordResultOkTemp +} + +// GetResetPasswordResultEnum return the enum type of this object +func (resetPasswordResultOk *ResetPasswordResultOk) GetResetPasswordResultEnum() ResetPasswordResultEnum { + return ResetPasswordResultOkType +} + +// ResetPasswordResultPending The password reset request is pending +type ResetPasswordResultPending struct { + tdCommon + PendingResetDate int32 `json:"pending_reset_date"` // Point in time (Unix timestamp) after which the password can be reset immediately using resetPassword +} + +// MessageType return the string telegram-type of ResetPasswordResultPending +func (resetPasswordResultPending *ResetPasswordResultPending) MessageType() string { + return "resetPasswordResultPending" +} + +// NewResetPasswordResultPending creates a new ResetPasswordResultPending +// +// @param pendingResetDate Point in time (Unix timestamp) after which the password can be reset immediately using resetPassword +func NewResetPasswordResultPending(pendingResetDate int32) *ResetPasswordResultPending { + resetPasswordResultPendingTemp := ResetPasswordResultPending{ + tdCommon: tdCommon{Type: "resetPasswordResultPending"}, + PendingResetDate: pendingResetDate, + } + + return &resetPasswordResultPendingTemp +} + +// GetResetPasswordResultEnum return the enum type of this object +func (resetPasswordResultPending *ResetPasswordResultPending) GetResetPasswordResultEnum() ResetPasswordResultEnum { + return ResetPasswordResultPendingType +} + +// ResetPasswordResultDeclined The password reset request was declined +type ResetPasswordResultDeclined struct { + tdCommon + RetryDate int32 `json:"retry_date"` // Point in time (Unix timestamp) when the password reset can be retried +} + +// MessageType return the string telegram-type of ResetPasswordResultDeclined +func (resetPasswordResultDeclined *ResetPasswordResultDeclined) MessageType() string { + return "resetPasswordResultDeclined" +} + +// NewResetPasswordResultDeclined creates a new ResetPasswordResultDeclined +// +// @param retryDate Point in time (Unix timestamp) when the password reset can be retried +func NewResetPasswordResultDeclined(retryDate int32) *ResetPasswordResultDeclined { + resetPasswordResultDeclinedTemp := ResetPasswordResultDeclined{ + tdCommon: tdCommon{Type: "resetPasswordResultDeclined"}, + RetryDate: retryDate, + } + + return &resetPasswordResultDeclinedTemp +} + +// GetResetPasswordResultEnum return the enum type of this object +func (resetPasswordResultDeclined *ResetPasswordResultDeclined) GetResetPasswordResultEnum() ResetPasswordResultEnum { + return ResetPasswordResultDeclinedType +} diff --git a/tdlib/richText.go b/tdlib/richText.go new file mode 100644 index 0000000..8206dcd --- /dev/null +++ b/tdlib/richText.go @@ -0,0 +1,960 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// RichText Describes a text object inside an instant-view web page +type RichText interface { + GetRichTextEnum() RichTextEnum +} + +// 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" + RichTextSubscriptType RichTextEnum = "richTextSubscript" + RichTextSuperscriptType RichTextEnum = "richTextSuperscript" + RichTextMarkedType RichTextEnum = "richTextMarked" + RichTextPhoneNumberType RichTextEnum = "richTextPhoneNumber" + RichTextIconType RichTextEnum = "richTextIcon" + RichTextReferenceType RichTextEnum = "richTextReference" + RichTextAnchorType RichTextEnum = "richTextAnchor" + RichTextAnchorLinkType RichTextEnum = "richTextAnchorLink" + RichTextsType RichTextEnum = "richTexts" +) + +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 RichTextSubscriptType: + var richTextSubscript RichTextSubscript + err := json.Unmarshal(*rawMsg, &richTextSubscript) + return &richTextSubscript, err + + case RichTextSuperscriptType: + var richTextSuperscript RichTextSuperscript + err := json.Unmarshal(*rawMsg, &richTextSuperscript) + return &richTextSuperscript, err + + case RichTextMarkedType: + var richTextMarked RichTextMarked + err := json.Unmarshal(*rawMsg, &richTextMarked) + return &richTextMarked, err + + case RichTextPhoneNumberType: + var richTextPhoneNumber RichTextPhoneNumber + err := json.Unmarshal(*rawMsg, &richTextPhoneNumber) + return &richTextPhoneNumber, err + + case RichTextIconType: + var richTextIcon RichTextIcon + err := json.Unmarshal(*rawMsg, &richTextIcon) + return &richTextIcon, err + + case RichTextReferenceType: + var richTextReference RichTextReference + err := json.Unmarshal(*rawMsg, &richTextReference) + return &richTextReference, err + + case RichTextAnchorType: + var richTextAnchor RichTextAnchor + err := json.Unmarshal(*rawMsg, &richTextAnchor) + return &richTextAnchor, err + + case RichTextAnchorLinkType: + var richTextAnchorLink RichTextAnchorLink + err := json.Unmarshal(*rawMsg, &richTextAnchorLink) + return &richTextAnchorLink, 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)) + } +} + +// 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 strikethrough 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 + IsCached bool `json:"is_cached"` // True, if the URL has cached instant view server-side +} + +// 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 +// @param isCached True, if the URL has cached instant view server-side +func NewRichTextURL(text RichText, uRL string, isCached bool) *RichTextURL { + richTextURLTemp := RichTextURL{ + tdCommon: tdCommon{Type: "richTextUrl"}, + Text: text, + URL: uRL, + IsCached: isCached, + } + + 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 + IsCached bool `json:"is_cached"` // True, if the URL has cached instant view server-side + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextURL.tdCommon = tempObj.tdCommon + richTextURL.URL = tempObj.URL + richTextURL.IsCached = tempObj.IsCached + + 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 +} + +// RichTextSubscript A subscript rich text +type RichTextSubscript struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextSubscript +func (richTextSubscript *RichTextSubscript) MessageType() string { + return "richTextSubscript" +} + +// NewRichTextSubscript creates a new RichTextSubscript +// +// @param text Text +func NewRichTextSubscript(text RichText) *RichTextSubscript { + richTextSubscriptTemp := RichTextSubscript{ + tdCommon: tdCommon{Type: "richTextSubscript"}, + Text: text, + } + + return &richTextSubscriptTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextSubscript *RichTextSubscript) 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 + } + + richTextSubscript.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextSubscript.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextSubscript *RichTextSubscript) GetRichTextEnum() RichTextEnum { + return RichTextSubscriptType +} + +// RichTextSuperscript A superscript rich text +type RichTextSuperscript struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextSuperscript +func (richTextSuperscript *RichTextSuperscript) MessageType() string { + return "richTextSuperscript" +} + +// NewRichTextSuperscript creates a new RichTextSuperscript +// +// @param text Text +func NewRichTextSuperscript(text RichText) *RichTextSuperscript { + richTextSuperscriptTemp := RichTextSuperscript{ + tdCommon: tdCommon{Type: "richTextSuperscript"}, + Text: text, + } + + return &richTextSuperscriptTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextSuperscript *RichTextSuperscript) 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 + } + + richTextSuperscript.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextSuperscript.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextSuperscript *RichTextSuperscript) GetRichTextEnum() RichTextEnum { + return RichTextSuperscriptType +} + +// RichTextMarked A marked rich text +type RichTextMarked struct { + tdCommon + Text RichText `json:"text"` // Text +} + +// MessageType return the string telegram-type of RichTextMarked +func (richTextMarked *RichTextMarked) MessageType() string { + return "richTextMarked" +} + +// NewRichTextMarked creates a new RichTextMarked +// +// @param text Text +func NewRichTextMarked(text RichText) *RichTextMarked { + richTextMarkedTemp := RichTextMarked{ + tdCommon: tdCommon{Type: "richTextMarked"}, + Text: text, + } + + return &richTextMarkedTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextMarked *RichTextMarked) 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 + } + + richTextMarked.tdCommon = tempObj.tdCommon + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextMarked.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextMarked *RichTextMarked) GetRichTextEnum() RichTextEnum { + return RichTextMarkedType +} + +// RichTextPhoneNumber A rich text phone number +type RichTextPhoneNumber struct { + tdCommon + Text RichText `json:"text"` // Text + PhoneNumber string `json:"phone_number"` // Phone number +} + +// MessageType return the string telegram-type of RichTextPhoneNumber +func (richTextPhoneNumber *RichTextPhoneNumber) MessageType() string { + return "richTextPhoneNumber" +} + +// NewRichTextPhoneNumber creates a new RichTextPhoneNumber +// +// @param text Text +// @param phoneNumber Phone number +func NewRichTextPhoneNumber(text RichText, phoneNumber string) *RichTextPhoneNumber { + richTextPhoneNumberTemp := RichTextPhoneNumber{ + tdCommon: tdCommon{Type: "richTextPhoneNumber"}, + Text: text, + PhoneNumber: phoneNumber, + } + + return &richTextPhoneNumberTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextPhoneNumber *RichTextPhoneNumber) 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"` // Phone number + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextPhoneNumber.tdCommon = tempObj.tdCommon + richTextPhoneNumber.PhoneNumber = tempObj.PhoneNumber + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextPhoneNumber.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextPhoneNumber *RichTextPhoneNumber) GetRichTextEnum() RichTextEnum { + return RichTextPhoneNumberType +} + +// RichTextIcon A small image inside the text +type RichTextIcon struct { + tdCommon + Document *Document `json:"document"` // The image represented as a document. The image can be in GIF, JPEG or PNG format + Width int32 `json:"width"` // Width of a bounding box in which the image should be shown; 0 if unknown + Height int32 `json:"height"` // Height of a bounding box in which the image should be shown; 0 if unknown +} + +// MessageType return the string telegram-type of RichTextIcon +func (richTextIcon *RichTextIcon) MessageType() string { + return "richTextIcon" +} + +// NewRichTextIcon creates a new RichTextIcon +// +// @param document The image represented as a document. The image can be in GIF, JPEG or PNG format +// @param width Width of a bounding box in which the image should be shown; 0 if unknown +// @param height Height of a bounding box in which the image should be shown; 0 if unknown +func NewRichTextIcon(document *Document, width int32, height int32) *RichTextIcon { + richTextIconTemp := RichTextIcon{ + tdCommon: tdCommon{Type: "richTextIcon"}, + Document: document, + Width: width, + Height: height, + } + + return &richTextIconTemp +} + +// GetRichTextEnum return the enum type of this object +func (richTextIcon *RichTextIcon) GetRichTextEnum() RichTextEnum { + return RichTextIconType +} + +// RichTextReference A reference to a richTexts object on the same web page +type RichTextReference struct { + tdCommon + Text RichText `json:"text"` // The text + AnchorName string `json:"anchor_name"` // The name of a richTextAnchor object, which is the first element of the target richTexts object + URL string `json:"url"` // An HTTP URL, opening the reference +} + +// MessageType return the string telegram-type of RichTextReference +func (richTextReference *RichTextReference) MessageType() string { + return "richTextReference" +} + +// NewRichTextReference creates a new RichTextReference +// +// @param text The text +// @param anchorName The name of a richTextAnchor object, which is the first element of the target richTexts object +// @param uRL An HTTP URL, opening the reference +func NewRichTextReference(text RichText, anchorName string, uRL string) *RichTextReference { + richTextReferenceTemp := RichTextReference{ + tdCommon: tdCommon{Type: "richTextReference"}, + Text: text, + AnchorName: anchorName, + URL: uRL, + } + + return &richTextReferenceTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextReference *RichTextReference) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + AnchorName string `json:"anchor_name"` // The name of a richTextAnchor object, which is the first element of the target richTexts object + URL string `json:"url"` // An HTTP URL, opening the reference + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextReference.tdCommon = tempObj.tdCommon + richTextReference.AnchorName = tempObj.AnchorName + richTextReference.URL = tempObj.URL + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextReference.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextReference *RichTextReference) GetRichTextEnum() RichTextEnum { + return RichTextReferenceType +} + +// RichTextAnchor An anchor +type RichTextAnchor struct { + tdCommon + Name string `json:"name"` // Anchor name +} + +// MessageType return the string telegram-type of RichTextAnchor +func (richTextAnchor *RichTextAnchor) MessageType() string { + return "richTextAnchor" +} + +// NewRichTextAnchor creates a new RichTextAnchor +// +// @param name Anchor name +func NewRichTextAnchor(name string) *RichTextAnchor { + richTextAnchorTemp := RichTextAnchor{ + tdCommon: tdCommon{Type: "richTextAnchor"}, + Name: name, + } + + return &richTextAnchorTemp +} + +// GetRichTextEnum return the enum type of this object +func (richTextAnchor *RichTextAnchor) GetRichTextEnum() RichTextEnum { + return RichTextAnchorType +} + +// RichTextAnchorLink A link to an anchor on the same web page +type RichTextAnchorLink struct { + tdCommon + Text RichText `json:"text"` // The link text + AnchorName string `json:"anchor_name"` // The anchor name. If the name is empty, the link should bring back to top + URL string `json:"url"` // An HTTP URL, opening the anchor +} + +// MessageType return the string telegram-type of RichTextAnchorLink +func (richTextAnchorLink *RichTextAnchorLink) MessageType() string { + return "richTextAnchorLink" +} + +// NewRichTextAnchorLink creates a new RichTextAnchorLink +// +// @param text The link text +// @param anchorName The anchor name. If the name is empty, the link should bring back to top +// @param uRL An HTTP URL, opening the anchor +func NewRichTextAnchorLink(text RichText, anchorName string, uRL string) *RichTextAnchorLink { + richTextAnchorLinkTemp := RichTextAnchorLink{ + tdCommon: tdCommon{Type: "richTextAnchorLink"}, + Text: text, + AnchorName: anchorName, + URL: uRL, + } + + return &richTextAnchorLinkTemp +} + +// UnmarshalJSON unmarshal to json +func (richTextAnchorLink *RichTextAnchorLink) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + AnchorName string `json:"anchor_name"` // The anchor name. If the name is empty, the link should bring back to top + URL string `json:"url"` // An HTTP URL, opening the anchor + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + richTextAnchorLink.tdCommon = tempObj.tdCommon + richTextAnchorLink.AnchorName = tempObj.AnchorName + richTextAnchorLink.URL = tempObj.URL + + fieldText, _ := unmarshalRichText(objMap["text"]) + richTextAnchorLink.Text = fieldText + + return nil +} + +// GetRichTextEnum return the enum type of this object +func (richTextAnchorLink *RichTextAnchorLink) GetRichTextEnum() RichTextEnum { + return RichTextAnchorLinkType +} + +// 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 +} diff --git a/tdlib/savedCredentials.go b/tdlib/savedCredentials.go new file mode 100644 index 0000000..885cafd --- /dev/null +++ b/tdlib/savedCredentials.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/scopeNotificationSettings.go b/tdlib/scopeNotificationSettings.go new file mode 100644 index 0000000..eeed95b --- /dev/null +++ b/tdlib/scopeNotificationSettings.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + DisablePinnedMessageNotifications bool `json:"disable_pinned_message_notifications"` // True, if notifications for incoming pinned messages will be created as for an ordinary unread message + DisableMentionNotifications bool `json:"disable_mention_notifications"` // True, if notifications for messages with mentions will be created as for an ordinary unread message +} + +// 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 +// @param disablePinnedMessageNotifications True, if notifications for incoming pinned messages will be created as for an ordinary unread message +// @param disableMentionNotifications True, if notifications for messages with mentions will be created as for an ordinary unread message +func NewScopeNotificationSettings(muteFor int32, sound string, showPreview bool, disablePinnedMessageNotifications bool, disableMentionNotifications bool) *ScopeNotificationSettings { + scopeNotificationSettingsTemp := ScopeNotificationSettings{ + tdCommon: tdCommon{Type: "scopeNotificationSettings"}, + MuteFor: muteFor, + Sound: sound, + ShowPreview: showPreview, + DisablePinnedMessageNotifications: disablePinnedMessageNotifications, + DisableMentionNotifications: disableMentionNotifications, + } + + return &scopeNotificationSettingsTemp +} diff --git a/tdlib/searchMessagesFilter.go b/tdlib/searchMessagesFilter.go new file mode 100644 index 0000000..aeccc17 --- /dev/null +++ b/tdlib/searchMessagesFilter.go @@ -0,0 +1,595 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// SearchMessagesFilter Represents a filter for message search results +type SearchMessagesFilter interface { + GetSearchMessagesFilterEnum() SearchMessagesFilterEnum +} + +// 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" + SearchMessagesFilterFailedToSendType SearchMessagesFilterEnum = "searchMessagesFilterFailedToSend" + SearchMessagesFilterPinnedType SearchMessagesFilterEnum = "searchMessagesFilterPinned" +) + +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 + + case SearchMessagesFilterFailedToSendType: + var searchMessagesFilterFailedToSend SearchMessagesFilterFailedToSend + err := json.Unmarshal(*rawMsg, &searchMessagesFilterFailedToSend) + return &searchMessagesFilterFailedToSend, err + + case SearchMessagesFilterPinnedType: + var searchMessagesFilterPinned SearchMessagesFilterPinned + err := json.Unmarshal(*rawMsg, &searchMessagesFilterPinned) + return &searchMessagesFilterPinned, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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, a message thread 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 +} + +// SearchMessagesFilterFailedToSend Returns only failed to send messages. This filter can be used only if the message database is used +type SearchMessagesFilterFailedToSend struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterFailedToSend +func (searchMessagesFilterFailedToSend *SearchMessagesFilterFailedToSend) MessageType() string { + return "searchMessagesFilterFailedToSend" +} + +// NewSearchMessagesFilterFailedToSend creates a new SearchMessagesFilterFailedToSend +// +func NewSearchMessagesFilterFailedToSend() *SearchMessagesFilterFailedToSend { + searchMessagesFilterFailedToSendTemp := SearchMessagesFilterFailedToSend{ + tdCommon: tdCommon{Type: "searchMessagesFilterFailedToSend"}, + } + + return &searchMessagesFilterFailedToSendTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterFailedToSend *SearchMessagesFilterFailedToSend) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterFailedToSendType +} + +// SearchMessagesFilterPinned Returns only pinned messages +type SearchMessagesFilterPinned struct { + tdCommon +} + +// MessageType return the string telegram-type of SearchMessagesFilterPinned +func (searchMessagesFilterPinned *SearchMessagesFilterPinned) MessageType() string { + return "searchMessagesFilterPinned" +} + +// NewSearchMessagesFilterPinned creates a new SearchMessagesFilterPinned +// +func NewSearchMessagesFilterPinned() *SearchMessagesFilterPinned { + searchMessagesFilterPinnedTemp := SearchMessagesFilterPinned{ + tdCommon: tdCommon{Type: "searchMessagesFilterPinned"}, + } + + return &searchMessagesFilterPinnedTemp +} + +// GetSearchMessagesFilterEnum return the enum type of this object +func (searchMessagesFilterPinned *SearchMessagesFilterPinned) GetSearchMessagesFilterEnum() SearchMessagesFilterEnum { + return SearchMessagesFilterPinnedType +} diff --git a/tdlib/seconds.go b/tdlib/seconds.go new file mode 100644 index 0000000..35f16ad --- /dev/null +++ b/tdlib/seconds.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/secretChat.go b/tdlib/secretChat.go new file mode 100644 index 0000000..045bed0 --- /dev/null +++ b/tdlib/secretChat.go @@ -0,0 +1,78 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// SecretChat Represents a secret chat +type SecretChat struct { + tdCommon + ID int32 `json:"id"` // Secret chat identifier + UserID int64 `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 + 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 little-endian bytes, which must be split into groups of 2 bits, each denoting a pixel of one of 4 colors FFFFFF, D5E6F3, 2D5775, and 2F99C9. The pixels must be used to make a 12x12 square image filled from left to right, top to bottom. Alternatively, the first 32 bytes of the hash can be converted to the hexadecimal format and printed as 32 2-digit hex numbers + Layer int32 `json:"layer"` // Secret chat layer; determines features supported by the chat partner's application. Nested text entities and underline and strikethrough entities are supported if the layer >= 101 +} + +// 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 keyHash Hash of the currently used key for comparison with the hash of the chat partner's key. This is a string of 36 little-endian bytes, which must be split into groups of 2 bits, each denoting a pixel of one of 4 colors FFFFFF, D5E6F3, 2D5775, and 2F99C9. The pixels must be used to make a 12x12 square image filled from left to right, top to bottom. Alternatively, the first 32 bytes of the hash can be converted to the hexadecimal format and printed as 32 2-digit hex numbers +// @param layer Secret chat layer; determines features supported by the chat partner's application. Nested text entities and underline and strikethrough entities are supported if the layer >= 101 +func NewSecretChat(iD int32, userID int64, state SecretChatState, isOutbound bool, keyHash []byte, layer int32) *SecretChat { + secretChatTemp := SecretChat{ + tdCommon: tdCommon{Type: "secretChat"}, + ID: iD, + UserID: userID, + State: state, + IsOutbound: isOutbound, + 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 int64 `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 + 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 little-endian bytes, which must be split into groups of 2 bits, each denoting a pixel of one of 4 colors FFFFFF, D5E6F3, 2D5775, and 2F99C9. The pixels must be used to make a 12x12 square image filled from left to right, top to bottom. Alternatively, the first 32 bytes of the hash can be converted to the hexadecimal format and printed as 32 2-digit hex numbers + Layer int32 `json:"layer"` // Secret chat layer; determines features supported by the chat partner's application. Nested text entities and underline and strikethrough entities are supported if the layer >= 101 + }{} + 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.KeyHash = tempObj.KeyHash + secretChat.Layer = tempObj.Layer + + fieldState, _ := unmarshalSecretChatState(objMap["state"]) + secretChat.State = fieldState + + return nil +} diff --git a/tdlib/secretChatState.go b/tdlib/secretChatState.go new file mode 100644 index 0000000..d608c8e --- /dev/null +++ b/tdlib/secretChatState.go @@ -0,0 +1,130 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// SecretChatState Describes the current secret chat state +type SecretChatState interface { + GetSecretChatStateEnum() SecretChatStateEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/session.go b/tdlib/session.go new file mode 100644 index 0000000..1ab40e2 --- /dev/null +++ b/tdlib/session.go @@ -0,0 +1,68 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Session Contains information about one session in a Telegram application used by the current user. Sessions should be shown to the user in the returned order +type Session struct { + tdCommon + ID JSONInt64 `json:"id"` // Session identifier + IsCurrent bool `json:"is_current"` // True, if this session is the current session + IsPasswordPending bool `json:"is_password_pending"` // True, if a password is needed to complete authorization of the 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 isPasswordPending True, if a password is needed to complete authorization of the 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, isPasswordPending 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, + IsPasswordPending: isPasswordPending, + 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 +} diff --git a/tdlib/sessions.go b/tdlib/sessions.go new file mode 100644 index 0000000..10bb781 --- /dev/null +++ b/tdlib/sessions.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/shippingOption.go b/tdlib/shippingOption.go new file mode 100644 index 0000000..1a15b4b --- /dev/null +++ b/tdlib/shippingOption.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/sponsoredMessage.go b/tdlib/sponsoredMessage.go new file mode 100644 index 0000000..fd6f2a0 --- /dev/null +++ b/tdlib/sponsoredMessage.go @@ -0,0 +1,69 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// SponsoredMessage Describes a sponsored message +type SponsoredMessage struct { + tdCommon + ID int32 `json:"id"` // Unique sponsored message identifier + SponsorChatID int64 `json:"sponsor_chat_id"` // Chat identifier + StartParameter string `json:"start_parameter"` // Parameter for the bot start message if the sponsored chat is a chat with a bot + Content MessageContent `json:"content"` // Content of the message +} + +// MessageType return the string telegram-type of SponsoredMessage +func (sponsoredMessage *SponsoredMessage) MessageType() string { + return "sponsoredMessage" +} + +// NewSponsoredMessage creates a new SponsoredMessage +// +// @param iD Unique sponsored message identifier +// @param sponsorChatID Chat identifier +// @param startParameter Parameter for the bot start message if the sponsored chat is a chat with a bot +// @param content Content of the message +func NewSponsoredMessage(iD int32, sponsorChatID int64, startParameter string, content MessageContent) *SponsoredMessage { + sponsoredMessageTemp := SponsoredMessage{ + tdCommon: tdCommon{Type: "sponsoredMessage"}, + ID: iD, + SponsorChatID: sponsorChatID, + StartParameter: startParameter, + Content: content, + } + + return &sponsoredMessageTemp +} + +// UnmarshalJSON unmarshal to json +func (sponsoredMessage *SponsoredMessage) 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 sponsored message identifier + SponsorChatID int64 `json:"sponsor_chat_id"` // Chat identifier + StartParameter string `json:"start_parameter"` // Parameter for the bot start message if the sponsored chat is a chat with a bot + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + sponsoredMessage.tdCommon = tempObj.tdCommon + sponsoredMessage.ID = tempObj.ID + sponsoredMessage.SponsorChatID = tempObj.SponsorChatID + sponsoredMessage.StartParameter = tempObj.StartParameter + + fieldContent, _ := unmarshalMessageContent(objMap["content"]) + sponsoredMessage.Content = fieldContent + + return nil +} diff --git a/tdlib/sponsoredMessages.go b/tdlib/sponsoredMessages.go new file mode 100644 index 0000000..fb01823 --- /dev/null +++ b/tdlib/sponsoredMessages.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// SponsoredMessages Contains a list of sponsored messages +type SponsoredMessages struct { + tdCommon + Messages []SponsoredMessage `json:"messages"` // List of sponsored messages +} + +// MessageType return the string telegram-type of SponsoredMessages +func (sponsoredMessages *SponsoredMessages) MessageType() string { + return "sponsoredMessages" +} + +// NewSponsoredMessages creates a new SponsoredMessages +// +// @param messages List of sponsored messages +func NewSponsoredMessages(messages []SponsoredMessage) *SponsoredMessages { + sponsoredMessagesTemp := SponsoredMessages{ + tdCommon: tdCommon{Type: "sponsoredMessages"}, + Messages: messages, + } + + return &sponsoredMessagesTemp +} diff --git a/tdlib/statisticalGraph.go b/tdlib/statisticalGraph.go new file mode 100644 index 0000000..9335349 --- /dev/null +++ b/tdlib/statisticalGraph.go @@ -0,0 +1,142 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// StatisticalGraph Describes a statistical graph +type StatisticalGraph interface { + GetStatisticalGraphEnum() StatisticalGraphEnum +} + +// StatisticalGraphEnum Alias for abstract StatisticalGraph 'Sub-Classes', used as constant-enum here +type StatisticalGraphEnum string + +// StatisticalGraph enums +const ( + StatisticalGraphDataType StatisticalGraphEnum = "statisticalGraphData" + StatisticalGraphAsyncType StatisticalGraphEnum = "statisticalGraphAsync" + StatisticalGraphErrorType StatisticalGraphEnum = "statisticalGraphError" +) + +func unmarshalStatisticalGraph(rawMsg *json.RawMessage) (StatisticalGraph, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch StatisticalGraphEnum(objMap["@type"].(string)) { + case StatisticalGraphDataType: + var statisticalGraphData StatisticalGraphData + err := json.Unmarshal(*rawMsg, &statisticalGraphData) + return &statisticalGraphData, err + + case StatisticalGraphAsyncType: + var statisticalGraphAsync StatisticalGraphAsync + err := json.Unmarshal(*rawMsg, &statisticalGraphAsync) + return &statisticalGraphAsync, err + + case StatisticalGraphErrorType: + var statisticalGraphError StatisticalGraphError + err := json.Unmarshal(*rawMsg, &statisticalGraphError) + return &statisticalGraphError, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// StatisticalGraphData A graph data +type StatisticalGraphData struct { + tdCommon + JsonData string `json:"json_data"` // Graph data in JSON format + ZoomToken string `json:"zoom_token"` // If non-empty, a token which can be used to receive a zoomed in graph +} + +// MessageType return the string telegram-type of StatisticalGraphData +func (statisticalGraphData *StatisticalGraphData) MessageType() string { + return "statisticalGraphData" +} + +// NewStatisticalGraphData creates a new StatisticalGraphData +// +// @param jsonStringData Graph data in JSON format +// @param zoomToken If non-empty, a token which can be used to receive a zoomed in graph +func NewStatisticalGraphData(jsonStringData string, zoomToken string) *StatisticalGraphData { + statisticalGraphDataTemp := StatisticalGraphData{ + tdCommon: tdCommon{Type: "statisticalGraphData"}, + JsonData: jsonStringData, + ZoomToken: zoomToken, + } + + return &statisticalGraphDataTemp +} + +// GetStatisticalGraphEnum return the enum type of this object +func (statisticalGraphData *StatisticalGraphData) GetStatisticalGraphEnum() StatisticalGraphEnum { + return StatisticalGraphDataType +} + +// StatisticalGraphAsync The graph data to be asynchronously loaded through getStatisticalGraph +type StatisticalGraphAsync struct { + tdCommon + Token string `json:"token"` // The token to use for data loading +} + +// MessageType return the string telegram-type of StatisticalGraphAsync +func (statisticalGraphAsync *StatisticalGraphAsync) MessageType() string { + return "statisticalGraphAsync" +} + +// NewStatisticalGraphAsync creates a new StatisticalGraphAsync +// +// @param token The token to use for data loading +func NewStatisticalGraphAsync(token string) *StatisticalGraphAsync { + statisticalGraphAsyncTemp := StatisticalGraphAsync{ + tdCommon: tdCommon{Type: "statisticalGraphAsync"}, + Token: token, + } + + return &statisticalGraphAsyncTemp +} + +// GetStatisticalGraphEnum return the enum type of this object +func (statisticalGraphAsync *StatisticalGraphAsync) GetStatisticalGraphEnum() StatisticalGraphEnum { + return StatisticalGraphAsyncType +} + +// StatisticalGraphError An error message to be shown to the user instead of the graph +type StatisticalGraphError struct { + tdCommon + ErrorMessage string `json:"error_message"` // The error message +} + +// MessageType return the string telegram-type of StatisticalGraphError +func (statisticalGraphError *StatisticalGraphError) MessageType() string { + return "statisticalGraphError" +} + +// NewStatisticalGraphError creates a new StatisticalGraphError +// +// @param errorMessage The error message +func NewStatisticalGraphError(errorMessage string) *StatisticalGraphError { + statisticalGraphErrorTemp := StatisticalGraphError{ + tdCommon: tdCommon{Type: "statisticalGraphError"}, + ErrorMessage: errorMessage, + } + + return &statisticalGraphErrorTemp +} + +// GetStatisticalGraphEnum return the enum type of this object +func (statisticalGraphError *StatisticalGraphError) GetStatisticalGraphEnum() StatisticalGraphEnum { + return StatisticalGraphErrorType +} diff --git a/tdlib/statisticalValue.go b/tdlib/statisticalValue.go new file mode 100644 index 0000000..7655c4e --- /dev/null +++ b/tdlib/statisticalValue.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// StatisticalValue A value with information about its recent changes +type StatisticalValue struct { + tdCommon + Value float64 `json:"value"` // The current value + PreviousValue float64 `json:"previous_value"` // The value for the previous day + GrowthRatePercentage float64 `json:"growth_rate_percentage"` // The growth rate of the value, as a percentage +} + +// MessageType return the string telegram-type of StatisticalValue +func (statisticalValue *StatisticalValue) MessageType() string { + return "statisticalValue" +} + +// NewStatisticalValue creates a new StatisticalValue +// +// @param value The current value +// @param previousValue The value for the previous day +// @param growthRatePercentage The growth rate of the value, as a percentage +func NewStatisticalValue(value float64, previousValue float64, growthRatePercentage float64) *StatisticalValue { + statisticalValueTemp := StatisticalValue{ + tdCommon: tdCommon{Type: "statisticalValue"}, + Value: value, + PreviousValue: previousValue, + GrowthRatePercentage: growthRatePercentage, + } + + return &statisticalValueTemp +} diff --git a/tdlib/sticker.go b/tdlib/sticker.go new file mode 100644 index 0000000..da4b539 --- /dev/null +++ b/tdlib/sticker.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + IsAnimated bool `json:"is_animated"` // True, if the sticker is an animated sticker in TGS format + 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 + Outline []ClosedVectorPath `json:"outline"` // Sticker's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner + Thumbnail *Thumbnail `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 isAnimated True, if the sticker is an animated sticker in TGS format +// @param isMask True, if the sticker is a mask +// @param maskPosition Position where the mask should be placed; may be null +// @param outline Sticker's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner +// @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, isAnimated bool, isMask bool, maskPosition *MaskPosition, outline []ClosedVectorPath, thumbnail *Thumbnail, sticker *File) *Sticker { + stickerTemp := Sticker{ + tdCommon: tdCommon{Type: "sticker"}, + SetID: setID, + Width: width, + Height: height, + Emoji: emoji, + IsAnimated: isAnimated, + IsMask: isMask, + MaskPosition: maskPosition, + Outline: outline, + Thumbnail: thumbnail, + Sticker: sticker, + } + + return &stickerTemp +} diff --git a/tdlib/stickerSet.go b/tdlib/stickerSet.go new file mode 100644 index 0000000..4af95bf --- /dev/null +++ b/tdlib/stickerSet.go @@ -0,0 +1,62 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + Thumbnail *Thumbnail `json:"thumbnail"` // Sticker set thumbnail in WEBP or TGS format with width and height 100; may be null. The file can be downloaded only before the thumbnail is changed + ThumbnailOutline []ClosedVectorPath `json:"thumbnail_outline"` // Sticker set thumbnail's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner + 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 + IsAnimated bool `json:"is_animated"` // True, is the stickers in the set are animated + 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 []Emojis `json:"emojis"` // A list of emoji corresponding to the stickers in the same order. The list is only for informational purposes, because a sticker is always sent with a fixed emoji from the corresponding Sticker object +} + +// 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 thumbnail Sticker set thumbnail in WEBP or TGS format with width and height 100; may be null. The file can be downloaded only before the thumbnail is changed +// @param thumbnailOutline Sticker set thumbnail's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner +// @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 isAnimated True, is the stickers in the set are animated +// @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. The list is only for informational purposes, because a sticker is always sent with a fixed emoji from the corresponding Sticker object +func NewStickerSet(iD JSONInt64, title string, name string, thumbnail *Thumbnail, thumbnailOutline []ClosedVectorPath, isInstalled bool, isArchived bool, isOfficial bool, isAnimated bool, isMasks bool, isViewed bool, stickers []Sticker, emojis []Emojis) *StickerSet { + stickerSetTemp := StickerSet{ + tdCommon: tdCommon{Type: "stickerSet"}, + ID: iD, + Title: title, + Name: name, + Thumbnail: thumbnail, + ThumbnailOutline: thumbnailOutline, + IsInstalled: isInstalled, + IsArchived: isArchived, + IsOfficial: isOfficial, + IsAnimated: isAnimated, + IsMasks: isMasks, + IsViewed: isViewed, + Stickers: stickers, + Emojis: emojis, + } + + return &stickerSetTemp +} diff --git a/tdlib/stickerSetInfo.go b/tdlib/stickerSetInfo.go new file mode 100644 index 0000000..df55b3f --- /dev/null +++ b/tdlib/stickerSetInfo.go @@ -0,0 +1,62 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + Thumbnail *Thumbnail `json:"thumbnail"` // Sticker set thumbnail in WEBP or TGS format with width and height 100; may be null + ThumbnailOutline []ClosedVectorPath `json:"thumbnail_outline"` // Sticker set thumbnail's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner + 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 + IsAnimated bool `json:"is_animated"` // True, is the stickers in the set are animated + 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 application 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 thumbnail Sticker set thumbnail in WEBP or TGS format with width and height 100; may be null +// @param thumbnailOutline Sticker set thumbnail's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner +// @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 isAnimated True, is the stickers in the set are animated +// @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 application needs more stickers the full set should be requested +func NewStickerSetInfo(iD JSONInt64, title string, name string, thumbnail *Thumbnail, thumbnailOutline []ClosedVectorPath, isInstalled bool, isArchived bool, isOfficial bool, isAnimated bool, isMasks bool, isViewed bool, size int32, covers []Sticker) *StickerSetInfo { + stickerSetInfoTemp := StickerSetInfo{ + tdCommon: tdCommon{Type: "stickerSetInfo"}, + ID: iD, + Title: title, + Name: name, + Thumbnail: thumbnail, + ThumbnailOutline: thumbnailOutline, + IsInstalled: isInstalled, + IsArchived: isArchived, + IsOfficial: isOfficial, + IsAnimated: isAnimated, + IsMasks: isMasks, + IsViewed: isViewed, + Size: size, + Covers: covers, + } + + return &stickerSetInfoTemp +} diff --git a/tdlib/stickerSets.go b/tdlib/stickerSets.go new file mode 100644 index 0000000..1981275 --- /dev/null +++ b/tdlib/stickerSets.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/stickers.go b/tdlib/stickers.go new file mode 100644 index 0000000..4d8d146 --- /dev/null +++ b/tdlib/stickers.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/storageStatistics.go b/tdlib/storageStatistics.go new file mode 100644 index 0000000..162c06e --- /dev/null +++ b/tdlib/storageStatistics.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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, in bytes + 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, in bytes +// @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 +} diff --git a/tdlib/storageStatisticsByChat.go b/tdlib/storageStatisticsByChat.go new file mode 100644 index 0000000..574c641 --- /dev/null +++ b/tdlib/storageStatisticsByChat.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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, in bytes + 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, in bytes +// @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 +} diff --git a/tdlib/storageStatisticsByFileType.go b/tdlib/storageStatisticsByFileType.go new file mode 100644 index 0000000..d946847 --- /dev/null +++ b/tdlib/storageStatisticsByFileType.go @@ -0,0 +1,63 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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, in bytes + 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, in bytes +// @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, in bytes + 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 +} diff --git a/tdlib/storageStatisticsFast.go b/tdlib/storageStatisticsFast.go new file mode 100644 index 0000000..75742ca --- /dev/null +++ b/tdlib/storageStatisticsFast.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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, in bytes + FileCount int32 `json:"file_count"` // Approximate number of files + DatabaseSize int64 `json:"database_size"` // Size of the database + LanguagePackDatabaseSize int64 `json:"language_pack_database_size"` // Size of the language pack database + LogSize int64 `json:"log_size"` // Size of the TDLib internal log +} + +// 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, in bytes +// @param fileCount Approximate number of files +// @param databaseSize Size of the database +// @param languagePackDatabaseSize Size of the language pack database +// @param logSize Size of the TDLib internal log +func NewStorageStatisticsFast(filesSize int64, fileCount int32, databaseSize int64, languagePackDatabaseSize int64, logSize int64) *StorageStatisticsFast { + storageStatisticsFastTemp := StorageStatisticsFast{ + tdCommon: tdCommon{Type: "storageStatisticsFast"}, + FilesSize: filesSize, + FileCount: fileCount, + DatabaseSize: databaseSize, + LanguagePackDatabaseSize: languagePackDatabaseSize, + LogSize: logSize, + } + + return &storageStatisticsFastTemp +} diff --git a/tdlib/suggestedAction.go b/tdlib/suggestedAction.go new file mode 100644 index 0000000..2565917 --- /dev/null +++ b/tdlib/suggestedAction.go @@ -0,0 +1,195 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// SuggestedAction Describes an action suggested to the current user +type SuggestedAction interface { + GetSuggestedActionEnum() SuggestedActionEnum +} + +// SuggestedActionEnum Alias for abstract SuggestedAction 'Sub-Classes', used as constant-enum here +type SuggestedActionEnum string + +// SuggestedAction enums +const ( + SuggestedActionEnableArchiveAndMuteNewChatsType SuggestedActionEnum = "suggestedActionEnableArchiveAndMuteNewChats" + SuggestedActionCheckPasswordType SuggestedActionEnum = "suggestedActionCheckPassword" + SuggestedActionCheckPhoneNumberType SuggestedActionEnum = "suggestedActionCheckPhoneNumber" + SuggestedActionSeeTicksHintType SuggestedActionEnum = "suggestedActionSeeTicksHint" + SuggestedActionConvertToBroadcastGroupType SuggestedActionEnum = "suggestedActionConvertToBroadcastGroup" +) + +func unmarshalSuggestedAction(rawMsg *json.RawMessage) (SuggestedAction, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch SuggestedActionEnum(objMap["@type"].(string)) { + case SuggestedActionEnableArchiveAndMuteNewChatsType: + var suggestedActionEnableArchiveAndMuteNewChats SuggestedActionEnableArchiveAndMuteNewChats + err := json.Unmarshal(*rawMsg, &suggestedActionEnableArchiveAndMuteNewChats) + return &suggestedActionEnableArchiveAndMuteNewChats, err + + case SuggestedActionCheckPasswordType: + var suggestedActionCheckPassword SuggestedActionCheckPassword + err := json.Unmarshal(*rawMsg, &suggestedActionCheckPassword) + return &suggestedActionCheckPassword, err + + case SuggestedActionCheckPhoneNumberType: + var suggestedActionCheckPhoneNumber SuggestedActionCheckPhoneNumber + err := json.Unmarshal(*rawMsg, &suggestedActionCheckPhoneNumber) + return &suggestedActionCheckPhoneNumber, err + + case SuggestedActionSeeTicksHintType: + var suggestedActionSeeTicksHint SuggestedActionSeeTicksHint + err := json.Unmarshal(*rawMsg, &suggestedActionSeeTicksHint) + return &suggestedActionSeeTicksHint, err + + case SuggestedActionConvertToBroadcastGroupType: + var suggestedActionConvertToBroadcastGroup SuggestedActionConvertToBroadcastGroup + err := json.Unmarshal(*rawMsg, &suggestedActionConvertToBroadcastGroup) + return &suggestedActionConvertToBroadcastGroup, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// SuggestedActionEnableArchiveAndMuteNewChats Suggests the user to enable "archive_and_mute_new_chats_from_unknown_users" option +type SuggestedActionEnableArchiveAndMuteNewChats struct { + tdCommon +} + +// MessageType return the string telegram-type of SuggestedActionEnableArchiveAndMuteNewChats +func (suggestedActionEnableArchiveAndMuteNewChats *SuggestedActionEnableArchiveAndMuteNewChats) MessageType() string { + return "suggestedActionEnableArchiveAndMuteNewChats" +} + +// NewSuggestedActionEnableArchiveAndMuteNewChats creates a new SuggestedActionEnableArchiveAndMuteNewChats +// +func NewSuggestedActionEnableArchiveAndMuteNewChats() *SuggestedActionEnableArchiveAndMuteNewChats { + suggestedActionEnableArchiveAndMuteNewChatsTemp := SuggestedActionEnableArchiveAndMuteNewChats{ + tdCommon: tdCommon{Type: "suggestedActionEnableArchiveAndMuteNewChats"}, + } + + return &suggestedActionEnableArchiveAndMuteNewChatsTemp +} + +// GetSuggestedActionEnum return the enum type of this object +func (suggestedActionEnableArchiveAndMuteNewChats *SuggestedActionEnableArchiveAndMuteNewChats) GetSuggestedActionEnum() SuggestedActionEnum { + return SuggestedActionEnableArchiveAndMuteNewChatsType +} + +// SuggestedActionCheckPassword Suggests the user to check whether 2-step verification password is still remembered +type SuggestedActionCheckPassword struct { + tdCommon +} + +// MessageType return the string telegram-type of SuggestedActionCheckPassword +func (suggestedActionCheckPassword *SuggestedActionCheckPassword) MessageType() string { + return "suggestedActionCheckPassword" +} + +// NewSuggestedActionCheckPassword creates a new SuggestedActionCheckPassword +// +func NewSuggestedActionCheckPassword() *SuggestedActionCheckPassword { + suggestedActionCheckPasswordTemp := SuggestedActionCheckPassword{ + tdCommon: tdCommon{Type: "suggestedActionCheckPassword"}, + } + + return &suggestedActionCheckPasswordTemp +} + +// GetSuggestedActionEnum return the enum type of this object +func (suggestedActionCheckPassword *SuggestedActionCheckPassword) GetSuggestedActionEnum() SuggestedActionEnum { + return SuggestedActionCheckPasswordType +} + +// SuggestedActionCheckPhoneNumber Suggests the user to check whether authorization phone number is correct and change the phone number if it is inaccessible +type SuggestedActionCheckPhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of SuggestedActionCheckPhoneNumber +func (suggestedActionCheckPhoneNumber *SuggestedActionCheckPhoneNumber) MessageType() string { + return "suggestedActionCheckPhoneNumber" +} + +// NewSuggestedActionCheckPhoneNumber creates a new SuggestedActionCheckPhoneNumber +// +func NewSuggestedActionCheckPhoneNumber() *SuggestedActionCheckPhoneNumber { + suggestedActionCheckPhoneNumberTemp := SuggestedActionCheckPhoneNumber{ + tdCommon: tdCommon{Type: "suggestedActionCheckPhoneNumber"}, + } + + return &suggestedActionCheckPhoneNumberTemp +} + +// GetSuggestedActionEnum return the enum type of this object +func (suggestedActionCheckPhoneNumber *SuggestedActionCheckPhoneNumber) GetSuggestedActionEnum() SuggestedActionEnum { + return SuggestedActionCheckPhoneNumberType +} + +// SuggestedActionSeeTicksHint Suggests the user to see a hint about meaning of one and two ticks on sent message +type SuggestedActionSeeTicksHint struct { + tdCommon +} + +// MessageType return the string telegram-type of SuggestedActionSeeTicksHint +func (suggestedActionSeeTicksHint *SuggestedActionSeeTicksHint) MessageType() string { + return "suggestedActionSeeTicksHint" +} + +// NewSuggestedActionSeeTicksHint creates a new SuggestedActionSeeTicksHint +// +func NewSuggestedActionSeeTicksHint() *SuggestedActionSeeTicksHint { + suggestedActionSeeTicksHintTemp := SuggestedActionSeeTicksHint{ + tdCommon: tdCommon{Type: "suggestedActionSeeTicksHint"}, + } + + return &suggestedActionSeeTicksHintTemp +} + +// GetSuggestedActionEnum return the enum type of this object +func (suggestedActionSeeTicksHint *SuggestedActionSeeTicksHint) GetSuggestedActionEnum() SuggestedActionEnum { + return SuggestedActionSeeTicksHintType +} + +// SuggestedActionConvertToBroadcastGroup Suggests the user to convert specified supergroup to a broadcast group +type SuggestedActionConvertToBroadcastGroup struct { + tdCommon + SupergroupID int64 `json:"supergroup_id"` // Supergroup identifier +} + +// MessageType return the string telegram-type of SuggestedActionConvertToBroadcastGroup +func (suggestedActionConvertToBroadcastGroup *SuggestedActionConvertToBroadcastGroup) MessageType() string { + return "suggestedActionConvertToBroadcastGroup" +} + +// NewSuggestedActionConvertToBroadcastGroup creates a new SuggestedActionConvertToBroadcastGroup +// +// @param supergroupID Supergroup identifier +func NewSuggestedActionConvertToBroadcastGroup(supergroupID int64) *SuggestedActionConvertToBroadcastGroup { + suggestedActionConvertToBroadcastGroupTemp := SuggestedActionConvertToBroadcastGroup{ + tdCommon: tdCommon{Type: "suggestedActionConvertToBroadcastGroup"}, + SupergroupID: supergroupID, + } + + return &suggestedActionConvertToBroadcastGroupTemp +} + +// GetSuggestedActionEnum return the enum type of this object +func (suggestedActionConvertToBroadcastGroup *SuggestedActionConvertToBroadcastGroup) GetSuggestedActionEnum() SuggestedActionEnum { + return SuggestedActionConvertToBroadcastGroupType +} diff --git a/tdlib/supergroup.go b/tdlib/supergroup.go new file mode 100644 index 0000000..4812b70 --- /dev/null +++ b/tdlib/supergroup.go @@ -0,0 +1,123 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 int64 `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; custom title will be always empty + MemberCount int32 `json:"member_count"` // Number of members in the supergroup or channel; 0 if unknown. Currently it is guaranteed to be known only if the supergroup or channel was received through searchPublicChats, searchChatsNearby, getInactiveSupergroupChats, getSuitableDiscussionChats, getGroupsInCommon, or getUserPrivacySettingRules + HasLinkedChat bool `json:"has_linked_chat"` // True, if the channel has a discussion group, or the supergroup is the designated discussion group for a channel + HasLocation bool `json:"has_location"` // True, if the supergroup is connected to a location, i.e. the supergroup is a location-based supergroup + 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 + IsSlowModeEnabled bool `json:"is_slow_mode_enabled"` // True, if the slow mode is enabled in the supergroup + IsChannel bool `json:"is_channel"` // True, if the supergroup is a channel + IsBroadcastGroup bool `json:"is_broadcast_group"` // True, if the supergroup is a broadcast group, i.e. only administrators can send messages and there is no limit on number of members + IsVerified bool `json:"is_verified"` // True, if the supergroup or channel is verified + RestrictionReason string `json:"restriction_reason"` // If non-empty, contains a human-readable description of the reason why access to this supergroup or channel must be restricted + IsScam bool `json:"is_scam"` // True, if many users reported this supergroup or channel as a scam + IsFake bool `json:"is_fake"` // True, if many users reported this supergroup or channel as a fake account +} + +// 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; custom title will be always empty +// @param memberCount Number of members in the supergroup or channel; 0 if unknown. Currently it is guaranteed to be known only if the supergroup or channel was received through searchPublicChats, searchChatsNearby, getInactiveSupergroupChats, getSuitableDiscussionChats, getGroupsInCommon, or getUserPrivacySettingRules +// @param hasLinkedChat True, if the channel has a discussion group, or the supergroup is the designated discussion group for a channel +// @param hasLocation True, if the supergroup is connected to a location, i.e. the supergroup is a location-based supergroup +// @param signMessages True, if messages sent to the channel should contain information about the sender. This field is only applicable to channels +// @param isSlowModeEnabled True, if the slow mode is enabled in the supergroup +// @param isChannel True, if the supergroup is a channel +// @param isBroadcastGroup True, if the supergroup is a broadcast group, i.e. only administrators can send messages and there is no limit on number of members +// @param isVerified True, if the supergroup or channel is verified +// @param restrictionReason If non-empty, contains a human-readable description of the reason why access to this supergroup or channel must be restricted +// @param isScam True, if many users reported this supergroup or channel as a scam +// @param isFake True, if many users reported this supergroup or channel as a fake account +func NewSupergroup(iD int64, username string, date int32, status ChatMemberStatus, memberCount int32, hasLinkedChat bool, hasLocation bool, signMessages bool, isSlowModeEnabled bool, isChannel bool, isBroadcastGroup bool, isVerified bool, restrictionReason string, isScam bool, isFake bool) *Supergroup { + supergroupTemp := Supergroup{ + tdCommon: tdCommon{Type: "supergroup"}, + ID: iD, + Username: username, + Date: date, + Status: status, + MemberCount: memberCount, + HasLinkedChat: hasLinkedChat, + HasLocation: hasLocation, + SignMessages: signMessages, + IsSlowModeEnabled: isSlowModeEnabled, + IsChannel: isChannel, + IsBroadcastGroup: isBroadcastGroup, + IsVerified: isVerified, + RestrictionReason: restrictionReason, + IsScam: isScam, + IsFake: isFake, + } + + 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 int64 `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"` // Number of members in the supergroup or channel; 0 if unknown. Currently it is guaranteed to be known only if the supergroup or channel was received through searchPublicChats, searchChatsNearby, getInactiveSupergroupChats, getSuitableDiscussionChats, getGroupsInCommon, or getUserPrivacySettingRules + HasLinkedChat bool `json:"has_linked_chat"` // True, if the channel has a discussion group, or the supergroup is the designated discussion group for a channel + HasLocation bool `json:"has_location"` // True, if the supergroup is connected to a location, i.e. the supergroup is a location-based supergroup + 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 + IsSlowModeEnabled bool `json:"is_slow_mode_enabled"` // True, if the slow mode is enabled in the supergroup + IsChannel bool `json:"is_channel"` // True, if the supergroup is a channel + IsBroadcastGroup bool `json:"is_broadcast_group"` // True, if the supergroup is a broadcast group, i.e. only administrators can send messages and there is no limit on number of members + IsVerified bool `json:"is_verified"` // True, if the supergroup or channel is verified + RestrictionReason string `json:"restriction_reason"` // If non-empty, contains a human-readable description of the reason why access to this supergroup or channel must be restricted + IsScam bool `json:"is_scam"` // True, if many users reported this supergroup or channel as a scam + IsFake bool `json:"is_fake"` // True, if many users reported this supergroup or channel as a fake account + }{} + 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.HasLinkedChat = tempObj.HasLinkedChat + supergroup.HasLocation = tempObj.HasLocation + supergroup.SignMessages = tempObj.SignMessages + supergroup.IsSlowModeEnabled = tempObj.IsSlowModeEnabled + supergroup.IsChannel = tempObj.IsChannel + supergroup.IsBroadcastGroup = tempObj.IsBroadcastGroup + supergroup.IsVerified = tempObj.IsVerified + supergroup.RestrictionReason = tempObj.RestrictionReason + supergroup.IsScam = tempObj.IsScam + supergroup.IsFake = tempObj.IsFake + + fieldStatus, _ := unmarshalChatMemberStatus(objMap["status"]) + supergroup.Status = fieldStatus + + return nil +} diff --git a/tdlib/supergroupFullInfo.go b/tdlib/supergroupFullInfo.go new file mode 100644 index 0000000..db4e23c --- /dev/null +++ b/tdlib/supergroupFullInfo.go @@ -0,0 +1,86 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// SupergroupFullInfo Contains full information about a supergroup or channel +type SupergroupFullInfo struct { + tdCommon + Photo *ChatPhoto `json:"photo"` // Chat photo; may be null + Description string `json:"description"` // Supergroup or channel 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 + LinkedChatID int64 `json:"linked_chat_id"` // Chat identifier of a discussion group for the channel, or a channel, for which the supergroup is the designated discussion group; 0 if none or unknown + SlowModeDelay int32 `json:"slow_mode_delay"` // Delay between consecutive sent messages for non-administrator supergroup members, in seconds + SlowModeDelayExpiresIn float64 `json:"slow_mode_delay_expires_in"` // Time left before next message can be sent in the supergroup, in seconds. An updateSupergroupFullInfo update is not triggered when value of this field changes, but both new and old values are non-zero + 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 username can be changed + CanSetStickerSet bool `json:"can_set_sticker_set"` // True, if the supergroup sticker set can be changed + CanSetLocation bool `json:"can_set_location"` // True, if the supergroup location can be changed + CanGetStatistics bool `json:"can_get_statistics"` // True, if the supergroup or channel statistics are available + IsAllHistoryAvailable bool `json:"is_all_history_available"` // True, if new chat members will have access to old messages. In public or discussion groups and both public and private channels, old messages are always available, so this option affects only private supergroups without a linked chat. 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 + Location *ChatLocation `json:"location"` // Location to which the supergroup is connected; may be null + InviteLink *ChatInviteLink `json:"invite_link"` // Primary invite link for this chat; may be null. For chat administrators with can_invite_users right only + BotCommands []BotCommands `json:"bot_commands"` // List of commands of bots in the group + UpgradedFromBasicGroupID int64 `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 photo Chat photo; may be null +// @param description Supergroup or channel 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 linkedChatID Chat identifier of a discussion group for the channel, or a channel, for which the supergroup is the designated discussion group; 0 if none or unknown +// @param slowModeDelay Delay between consecutive sent messages for non-administrator supergroup members, in seconds +// @param slowModeDelayExpiresIn Time left before next message can be sent in the supergroup, in seconds. An updateSupergroupFullInfo update is not triggered when value of this field changes, but both new and old values are non-zero +// @param canGetMembers True, if members of the chat can be retrieved +// @param canSetUsername True, if the chat username can be changed +// @param canSetStickerSet True, if the supergroup sticker set can be changed +// @param canSetLocation True, if the supergroup location can be changed +// @param canGetStatistics True, if the supergroup or channel statistics are available +// @param isAllHistoryAvailable True, if new chat members will have access to old messages. In public or discussion groups and both public and private channels, old messages are always available, so this option affects only private supergroups without a linked chat. The value of this field is only available for chat administrators +// @param stickerSetID Identifier of the supergroup sticker set; 0 if none +// @param location Location to which the supergroup is connected; may be null +// @param inviteLink Primary invite link for this chat; may be null. For chat administrators with can_invite_users right only +// @param botCommands List of commands of bots in the group +// @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(photo *ChatPhoto, description string, memberCount int32, administratorCount int32, restrictedCount int32, bannedCount int32, linkedChatID int64, slowModeDelay int32, slowModeDelayExpiresIn float64, canGetMembers bool, canSetUsername bool, canSetStickerSet bool, canSetLocation bool, canGetStatistics bool, isAllHistoryAvailable bool, stickerSetID JSONInt64, location *ChatLocation, inviteLink *ChatInviteLink, botCommands []BotCommands, upgradedFromBasicGroupID int64, upgradedFromMaxMessageID int64) *SupergroupFullInfo { + supergroupFullInfoTemp := SupergroupFullInfo{ + tdCommon: tdCommon{Type: "supergroupFullInfo"}, + Photo: photo, + Description: description, + MemberCount: memberCount, + AdministratorCount: administratorCount, + RestrictedCount: restrictedCount, + BannedCount: bannedCount, + LinkedChatID: linkedChatID, + SlowModeDelay: slowModeDelay, + SlowModeDelayExpiresIn: slowModeDelayExpiresIn, + CanGetMembers: canGetMembers, + CanSetUsername: canSetUsername, + CanSetStickerSet: canSetStickerSet, + CanSetLocation: canSetLocation, + CanGetStatistics: canGetStatistics, + IsAllHistoryAvailable: isAllHistoryAvailable, + StickerSetID: stickerSetID, + Location: location, + InviteLink: inviteLink, + BotCommands: botCommands, + UpgradedFromBasicGroupID: upgradedFromBasicGroupID, + UpgradedFromMaxMessageID: upgradedFromMaxMessageID, + } + + return &supergroupFullInfoTemp +} diff --git a/tdlib/supergroupMembersFilter.go b/tdlib/supergroupMembersFilter.go new file mode 100644 index 0000000..f034552 --- /dev/null +++ b/tdlib/supergroupMembersFilter.go @@ -0,0 +1,303 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// SupergroupMembersFilter Specifies the kind of chat members to return in getSupergroupMembers +type SupergroupMembersFilter interface { + GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum +} + +// SupergroupMembersFilterEnum Alias for abstract SupergroupMembersFilter 'Sub-Classes', used as constant-enum here +type SupergroupMembersFilterEnum string + +// SupergroupMembersFilter enums +const ( + SupergroupMembersFilterRecentType SupergroupMembersFilterEnum = "supergroupMembersFilterRecent" + SupergroupMembersFilterContactsType SupergroupMembersFilterEnum = "supergroupMembersFilterContacts" + SupergroupMembersFilterAdministratorsType SupergroupMembersFilterEnum = "supergroupMembersFilterAdministrators" + SupergroupMembersFilterSearchType SupergroupMembersFilterEnum = "supergroupMembersFilterSearch" + SupergroupMembersFilterRestrictedType SupergroupMembersFilterEnum = "supergroupMembersFilterRestricted" + SupergroupMembersFilterBannedType SupergroupMembersFilterEnum = "supergroupMembersFilterBanned" + SupergroupMembersFilterMentionType SupergroupMembersFilterEnum = "supergroupMembersFilterMention" + SupergroupMembersFilterBotsType SupergroupMembersFilterEnum = "supergroupMembersFilterBots" +) + +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 SupergroupMembersFilterContactsType: + var supergroupMembersFilterContacts SupergroupMembersFilterContacts + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterContacts) + return &supergroupMembersFilterContacts, 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 SupergroupMembersFilterMentionType: + var supergroupMembersFilterMention SupergroupMembersFilterMention + err := json.Unmarshal(*rawMsg, &supergroupMembersFilterMention) + return &supergroupMembersFilterMention, 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)) + } +} + +// 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 +} + +// SupergroupMembersFilterContacts Returns contacts of the user, which are members of the supergroup or channel +type SupergroupMembersFilterContacts struct { + tdCommon + Query string `json:"query"` // Query to search for +} + +// MessageType return the string telegram-type of SupergroupMembersFilterContacts +func (supergroupMembersFilterContacts *SupergroupMembersFilterContacts) MessageType() string { + return "supergroupMembersFilterContacts" +} + +// NewSupergroupMembersFilterContacts creates a new SupergroupMembersFilterContacts +// +// @param query Query to search for +func NewSupergroupMembersFilterContacts(query string) *SupergroupMembersFilterContacts { + supergroupMembersFilterContactsTemp := SupergroupMembersFilterContacts{ + tdCommon: tdCommon{Type: "supergroupMembersFilterContacts"}, + Query: query, + } + + return &supergroupMembersFilterContactsTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterContacts *SupergroupMembersFilterContacts) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterContactsType +} + +// SupergroupMembersFilterAdministrators Returns the owner 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 +} + +// SupergroupMembersFilterMention Returns users which can be mentioned in the supergroup +type SupergroupMembersFilterMention struct { + tdCommon + Query string `json:"query"` // Query to search for + MessageThreadID int64 `json:"message_thread_id"` // If non-zero, the identifier of the current message thread +} + +// MessageType return the string telegram-type of SupergroupMembersFilterMention +func (supergroupMembersFilterMention *SupergroupMembersFilterMention) MessageType() string { + return "supergroupMembersFilterMention" +} + +// NewSupergroupMembersFilterMention creates a new SupergroupMembersFilterMention +// +// @param query Query to search for +// @param messageThreadID If non-zero, the identifier of the current message thread +func NewSupergroupMembersFilterMention(query string, messageThreadID int64) *SupergroupMembersFilterMention { + supergroupMembersFilterMentionTemp := SupergroupMembersFilterMention{ + tdCommon: tdCommon{Type: "supergroupMembersFilterMention"}, + Query: query, + MessageThreadID: messageThreadID, + } + + return &supergroupMembersFilterMentionTemp +} + +// GetSupergroupMembersFilterEnum return the enum type of this object +func (supergroupMembersFilterMention *SupergroupMembersFilterMention) GetSupergroupMembersFilterEnum() SupergroupMembersFilterEnum { + return SupergroupMembersFilterMentionType +} + +// 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 +} diff --git a/tdlib/tMeURL.go b/tdlib/tMeURL.go new file mode 100644 index 0000000..580ee9c --- /dev/null +++ b/tdlib/tMeURL.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/tMeURLType.go b/tdlib/tMeURLType.go new file mode 100644 index 0000000..c298f91 --- /dev/null +++ b/tdlib/tMeURLType.go @@ -0,0 +1,129 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// TMeURLType Describes the type of a URL linking to an internal Telegram entity +type TMeURLType interface { + GetTMeURLTypeEnum() TMeURLTypeEnum +} + +// TMeURLTypeEnum Alias for abstract TMeURLType 'Sub-Classes', used as constant-enum here +type TMeURLTypeEnum string + +// TMeURLType enums +const () + +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)) { + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// TMeURLTypeUser A URL linking to a user +type TMeURLTypeUser struct { + tdCommon + UserID int64 `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 int64) *TMeURLTypeUser { + tMeURLTypeUserTemp := TMeURLTypeUser{ + tdCommon: tdCommon{Type: "tMeUrlTypeUser"}, + UserID: userID, + } + + return &tMeURLTypeUserTemp +} + +// 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 +} + +// 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 +} + +// 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 +} diff --git a/tdlib/tMeURLs.go b/tdlib/tMeURLs.go new file mode 100644 index 0000000..c19e320 --- /dev/null +++ b/tdlib/tMeURLs.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/tdlibParameters.go b/tdlib/tdlibParameters.go new file mode 100644 index 0000000..a9f197e --- /dev/null +++ b/tdlib/tdlibParameters.go @@ -0,0 +1,68 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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. If empty, the version is automatically detected by TDLib + 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. If empty, the version is automatically detected by TDLib +// @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 +} diff --git a/tdlib/temporaryPasswordState.go b/tdlib/temporaryPasswordState.go new file mode 100644 index 0000000..8d866f2 --- /dev/null +++ b/tdlib/temporaryPasswordState.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/termsOfService.go b/tdlib/termsOfService.go new file mode 100644 index 0000000..6149c9f --- /dev/null +++ b/tdlib/termsOfService.go @@ -0,0 +1,32 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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"` // The minimum 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 The minimum 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 +} diff --git a/tdlib/testBytes.go b/tdlib/testBytes.go new file mode 100644 index 0000000..b7db58d --- /dev/null +++ b/tdlib/testBytes.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/testInt.go b/tdlib/testInt.go new file mode 100644 index 0000000..2577fe3 --- /dev/null +++ b/tdlib/testInt.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/testString.go b/tdlib/testString.go new file mode 100644 index 0000000..62bbf0b --- /dev/null +++ b/tdlib/testString.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/testVectorInt.go b/tdlib/testVectorInt.go new file mode 100644 index 0000000..93a2ad7 --- /dev/null +++ b/tdlib/testVectorInt.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/testVectorIntObject.go b/tdlib/testVectorIntObject.go new file mode 100644 index 0000000..3df5020 --- /dev/null +++ b/tdlib/testVectorIntObject.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/testVectorString.go b/tdlib/testVectorString.go new file mode 100644 index 0000000..6acf8a0 --- /dev/null +++ b/tdlib/testVectorString.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/testVectorStringObject.go b/tdlib/testVectorStringObject.go new file mode 100644 index 0000000..b73b56f --- /dev/null +++ b/tdlib/testVectorStringObject.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/text.go b/tdlib/text.go new file mode 100644 index 0000000..7816832 --- /dev/null +++ b/tdlib/text.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/textEntities.go b/tdlib/textEntities.go new file mode 100644 index 0000000..1ff14ba --- /dev/null +++ b/tdlib/textEntities.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/textEntity.go b/tdlib/textEntity.go new file mode 100644 index 0000000..0456bba --- /dev/null +++ b/tdlib/textEntity.go @@ -0,0 +1,64 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// 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 units + Length int32 `json:"length"` // Length of the entity, in UTF-16 code units + 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 units +// @param length Length of the entity, in UTF-16 code units +// @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 units + Length int32 `json:"length"` // Length of the entity, in UTF-16 code units + + }{} + 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 +} diff --git a/tdlib/textEntityType.go b/tdlib/textEntityType.go new file mode 100644 index 0000000..9098b7a --- /dev/null +++ b/tdlib/textEntityType.go @@ -0,0 +1,607 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// TextEntityType Represents a part of the text which must be formatted differently +type TextEntityType interface { + GetTextEntityTypeEnum() TextEntityTypeEnum +} + +// 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" + TextEntityTypePhoneNumberType TextEntityTypeEnum = "textEntityTypePhoneNumber" + TextEntityTypeBankCardNumberType TextEntityTypeEnum = "textEntityTypeBankCardNumber" + TextEntityTypeBoldType TextEntityTypeEnum = "textEntityTypeBold" + TextEntityTypeItalicType TextEntityTypeEnum = "textEntityTypeItalic" + TextEntityTypeUnderlineType TextEntityTypeEnum = "textEntityTypeUnderline" + TextEntityTypeStrikethroughType TextEntityTypeEnum = "textEntityTypeStrikethrough" + TextEntityTypeCodeType TextEntityTypeEnum = "textEntityTypeCode" + TextEntityTypePreType TextEntityTypeEnum = "textEntityTypePre" + TextEntityTypePreCodeType TextEntityTypeEnum = "textEntityTypePreCode" + TextEntityTypeTextURLType TextEntityTypeEnum = "textEntityTypeTextUrl" + TextEntityTypeMentionNameType TextEntityTypeEnum = "textEntityTypeMentionName" + TextEntityTypeMediaTimestampType TextEntityTypeEnum = "textEntityTypeMediaTimestamp" +) + +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 TextEntityTypePhoneNumberType: + var textEntityTypePhoneNumber TextEntityTypePhoneNumber + err := json.Unmarshal(*rawMsg, &textEntityTypePhoneNumber) + return &textEntityTypePhoneNumber, err + + case TextEntityTypeBankCardNumberType: + var textEntityTypeBankCardNumber TextEntityTypeBankCardNumber + err := json.Unmarshal(*rawMsg, &textEntityTypeBankCardNumber) + return &textEntityTypeBankCardNumber, 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 TextEntityTypeUnderlineType: + var textEntityTypeUnderline TextEntityTypeUnderline + err := json.Unmarshal(*rawMsg, &textEntityTypeUnderline) + return &textEntityTypeUnderline, err + + case TextEntityTypeStrikethroughType: + var textEntityTypeStrikethrough TextEntityTypeStrikethrough + err := json.Unmarshal(*rawMsg, &textEntityTypeStrikethrough) + return &textEntityTypeStrikethrough, 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 TextEntityTypeMediaTimestampType: + var textEntityTypeMediaTimestamp TextEntityTypeMediaTimestamp + err := json.Unmarshal(*rawMsg, &textEntityTypeMediaTimestamp) + return &textEntityTypeMediaTimestamp, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 "/" +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 +} + +// 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 +} + +// TextEntityTypeBankCardNumber A bank card number. The getBankCardInfo method can be used to get information about the bank card +type TextEntityTypeBankCardNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeBankCardNumber +func (textEntityTypeBankCardNumber *TextEntityTypeBankCardNumber) MessageType() string { + return "textEntityTypeBankCardNumber" +} + +// NewTextEntityTypeBankCardNumber creates a new TextEntityTypeBankCardNumber +// +func NewTextEntityTypeBankCardNumber() *TextEntityTypeBankCardNumber { + textEntityTypeBankCardNumberTemp := TextEntityTypeBankCardNumber{ + tdCommon: tdCommon{Type: "textEntityTypeBankCardNumber"}, + } + + return &textEntityTypeBankCardNumberTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeBankCardNumber *TextEntityTypeBankCardNumber) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeBankCardNumberType +} + +// 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 +} + +// TextEntityTypeUnderline An underlined text +type TextEntityTypeUnderline struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeUnderline +func (textEntityTypeUnderline *TextEntityTypeUnderline) MessageType() string { + return "textEntityTypeUnderline" +} + +// NewTextEntityTypeUnderline creates a new TextEntityTypeUnderline +// +func NewTextEntityTypeUnderline() *TextEntityTypeUnderline { + textEntityTypeUnderlineTemp := TextEntityTypeUnderline{ + tdCommon: tdCommon{Type: "textEntityTypeUnderline"}, + } + + return &textEntityTypeUnderlineTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeUnderline *TextEntityTypeUnderline) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeUnderlineType +} + +// TextEntityTypeStrikethrough A strikethrough text +type TextEntityTypeStrikethrough struct { + tdCommon +} + +// MessageType return the string telegram-type of TextEntityTypeStrikethrough +func (textEntityTypeStrikethrough *TextEntityTypeStrikethrough) MessageType() string { + return "textEntityTypeStrikethrough" +} + +// NewTextEntityTypeStrikethrough creates a new TextEntityTypeStrikethrough +// +func NewTextEntityTypeStrikethrough() *TextEntityTypeStrikethrough { + textEntityTypeStrikethroughTemp := TextEntityTypeStrikethrough{ + tdCommon: tdCommon{Type: "textEntityTypeStrikethrough"}, + } + + return &textEntityTypeStrikethroughTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeStrikethrough *TextEntityTypeStrikethrough) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeStrikethroughType +} + +// 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 int64 `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 int64) *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 +} + +// TextEntityTypeMediaTimestamp A media timestamp +type TextEntityTypeMediaTimestamp struct { + tdCommon + MediaTimestamp int32 `json:"media_timestamp"` // Timestamp from which a video/audio/video note/voice note playing should start, in seconds. The media can be in the content or the web page preview of the current message, or in the same places in the replied message +} + +// MessageType return the string telegram-type of TextEntityTypeMediaTimestamp +func (textEntityTypeMediaTimestamp *TextEntityTypeMediaTimestamp) MessageType() string { + return "textEntityTypeMediaTimestamp" +} + +// NewTextEntityTypeMediaTimestamp creates a new TextEntityTypeMediaTimestamp +// +// @param mediaTimestamp Timestamp from which a video/audio/video note/voice note playing should start, in seconds. The media can be in the content or the web page preview of the current message, or in the same places in the replied message +func NewTextEntityTypeMediaTimestamp(mediaTimestamp int32) *TextEntityTypeMediaTimestamp { + textEntityTypeMediaTimestampTemp := TextEntityTypeMediaTimestamp{ + tdCommon: tdCommon{Type: "textEntityTypeMediaTimestamp"}, + MediaTimestamp: mediaTimestamp, + } + + return &textEntityTypeMediaTimestampTemp +} + +// GetTextEntityTypeEnum return the enum type of this object +func (textEntityTypeMediaTimestamp *TextEntityTypeMediaTimestamp) GetTextEntityTypeEnum() TextEntityTypeEnum { + return TextEntityTypeMediaTimestampType +} diff --git a/tdlib/textParseMode.go b/tdlib/textParseMode.go new file mode 100644 index 0000000..032c2e5 --- /dev/null +++ b/tdlib/textParseMode.go @@ -0,0 +1,102 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// TextParseMode Describes the way the text should be parsed for TextEntities +type TextParseMode interface { + GetTextParseModeEnum() TextParseModeEnum +} + +// TextParseModeEnum Alias for abstract TextParseMode 'Sub-Classes', used as constant-enum here +type TextParseModeEnum string + +// TextParseMode enums +const ( + TextParseModeMarkdownType TextParseModeEnum = "textParseModeMarkdown" + TextParseModeHTMLType TextParseModeEnum = "textParseModeHTML" +) + +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)) + } +} + +// TextParseModeMarkdown The text uses Markdown-style formatting +type TextParseModeMarkdown struct { + tdCommon + Version int32 `json:"version"` // Version of the parser: 0 or 1 - Telegram Bot API "Markdown" parse mode, 2 - Telegram Bot API "MarkdownV2" parse mode +} + +// MessageType return the string telegram-type of TextParseModeMarkdown +func (textParseModeMarkdown *TextParseModeMarkdown) MessageType() string { + return "textParseModeMarkdown" +} + +// NewTextParseModeMarkdown creates a new TextParseModeMarkdown +// +// @param version Version of the parser: 0 or 1 - Telegram Bot API "Markdown" parse mode, 2 - Telegram Bot API "MarkdownV2" parse mode +func NewTextParseModeMarkdown(version int32) *TextParseModeMarkdown { + textParseModeMarkdownTemp := TextParseModeMarkdown{ + tdCommon: tdCommon{Type: "textParseModeMarkdown"}, + Version: version, + } + + return &textParseModeMarkdownTemp +} + +// GetTextParseModeEnum return the enum type of this object +func (textParseModeMarkdown *TextParseModeMarkdown) GetTextParseModeEnum() TextParseModeEnum { + return TextParseModeMarkdownType +} + +// TextParseModeHTML The text uses HTML-style formatting. The same as Telegram Bot API "HTML" parse mode +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 +} diff --git a/tdlib/themeSettings.go b/tdlib/themeSettings.go new file mode 100644 index 0000000..719fe68 --- /dev/null +++ b/tdlib/themeSettings.go @@ -0,0 +1,68 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// ThemeSettings Describes theme settings +type ThemeSettings struct { + tdCommon + AccentColor int32 `json:"accent_color"` // Theme accent color in ARGB format + Background *Background `json:"background"` // The background to be used in chats; may be null + MessageFill BackgroundFill `json:"message_fill"` // The fill to be used as a background for outgoing messages + AnimateMessageFill bool `json:"animate_message_fill"` // If true, the freeform gradient fill needs to be animated on every sent message +} + +// MessageType return the string telegram-type of ThemeSettings +func (themeSettings *ThemeSettings) MessageType() string { + return "themeSettings" +} + +// NewThemeSettings creates a new ThemeSettings +// +// @param accentColor Theme accent color in ARGB format +// @param background The background to be used in chats; may be null +// @param messageFill The fill to be used as a background for outgoing messages +// @param animateMessageFill If true, the freeform gradient fill needs to be animated on every sent message +func NewThemeSettings(accentColor int32, background *Background, messageFill BackgroundFill, animateMessageFill bool) *ThemeSettings { + themeSettingsTemp := ThemeSettings{ + tdCommon: tdCommon{Type: "themeSettings"}, + AccentColor: accentColor, + Background: background, + MessageFill: messageFill, + AnimateMessageFill: animateMessageFill, + } + + return &themeSettingsTemp +} + +// UnmarshalJSON unmarshal to json +func (themeSettings *ThemeSettings) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + AccentColor int32 `json:"accent_color"` // Theme accent color in ARGB format + Background *Background `json:"background"` // The background to be used in chats; may be null + AnimateMessageFill bool `json:"animate_message_fill"` // If true, the freeform gradient fill needs to be animated on every sent message + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + themeSettings.tdCommon = tempObj.tdCommon + themeSettings.AccentColor = tempObj.AccentColor + themeSettings.Background = tempObj.Background + themeSettings.AnimateMessageFill = tempObj.AnimateMessageFill + + fieldMessageFill, _ := unmarshalBackgroundFill(objMap["message_fill"]) + themeSettings.MessageFill = fieldMessageFill + + return nil +} diff --git a/tdlib/thumbnail.go b/tdlib/thumbnail.go new file mode 100644 index 0000000..403179d --- /dev/null +++ b/tdlib/thumbnail.go @@ -0,0 +1,68 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// Thumbnail Represents a thumbnail +type Thumbnail struct { + tdCommon + Format ThumbnailFormat `json:"format"` // Thumbnail format + Width int32 `json:"width"` // Thumbnail width + Height int32 `json:"height"` // Thumbnail height + File *File `json:"file"` // The thumbnail +} + +// MessageType return the string telegram-type of Thumbnail +func (thumbnail *Thumbnail) MessageType() string { + return "thumbnail" +} + +// NewThumbnail creates a new Thumbnail +// +// @param format Thumbnail format +// @param width Thumbnail width +// @param height Thumbnail height +// @param file The thumbnail +func NewThumbnail(format ThumbnailFormat, width int32, height int32, file *File) *Thumbnail { + thumbnailTemp := Thumbnail{ + tdCommon: tdCommon{Type: "thumbnail"}, + Format: format, + Width: width, + Height: height, + File: file, + } + + return &thumbnailTemp +} + +// UnmarshalJSON unmarshal to json +func (thumbnail *Thumbnail) 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 + Height int32 `json:"height"` // Thumbnail height + File *File `json:"file"` // The thumbnail + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + thumbnail.tdCommon = tempObj.tdCommon + thumbnail.Width = tempObj.Width + thumbnail.Height = tempObj.Height + thumbnail.File = tempObj.File + + fieldFormat, _ := unmarshalThumbnailFormat(objMap["format"]) + thumbnail.Format = fieldFormat + + return nil +} diff --git a/tdlib/thumbnailFormat.go b/tdlib/thumbnailFormat.go new file mode 100644 index 0000000..20c803b --- /dev/null +++ b/tdlib/thumbnailFormat.go @@ -0,0 +1,223 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// ThumbnailFormat Describes format of the thumbnail +type ThumbnailFormat interface { + GetThumbnailFormatEnum() ThumbnailFormatEnum +} + +// ThumbnailFormatEnum Alias for abstract ThumbnailFormat 'Sub-Classes', used as constant-enum here +type ThumbnailFormatEnum string + +// ThumbnailFormat enums +const ( + ThumbnailFormatJpegType ThumbnailFormatEnum = "thumbnailFormatJpeg" + ThumbnailFormatPngType ThumbnailFormatEnum = "thumbnailFormatPng" + ThumbnailFormatWebpType ThumbnailFormatEnum = "thumbnailFormatWebp" + ThumbnailFormatGifType ThumbnailFormatEnum = "thumbnailFormatGif" + ThumbnailFormatTgsType ThumbnailFormatEnum = "thumbnailFormatTgs" + ThumbnailFormatMpeg4Type ThumbnailFormatEnum = "thumbnailFormatMpeg4" +) + +func unmarshalThumbnailFormat(rawMsg *json.RawMessage) (ThumbnailFormat, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch ThumbnailFormatEnum(objMap["@type"].(string)) { + case ThumbnailFormatJpegType: + var thumbnailFormatJpeg ThumbnailFormatJpeg + err := json.Unmarshal(*rawMsg, &thumbnailFormatJpeg) + return &thumbnailFormatJpeg, err + + case ThumbnailFormatPngType: + var thumbnailFormatPng ThumbnailFormatPng + err := json.Unmarshal(*rawMsg, &thumbnailFormatPng) + return &thumbnailFormatPng, err + + case ThumbnailFormatWebpType: + var thumbnailFormatWebp ThumbnailFormatWebp + err := json.Unmarshal(*rawMsg, &thumbnailFormatWebp) + return &thumbnailFormatWebp, err + + case ThumbnailFormatGifType: + var thumbnailFormatGif ThumbnailFormatGif + err := json.Unmarshal(*rawMsg, &thumbnailFormatGif) + return &thumbnailFormatGif, err + + case ThumbnailFormatTgsType: + var thumbnailFormatTgs ThumbnailFormatTgs + err := json.Unmarshal(*rawMsg, &thumbnailFormatTgs) + return &thumbnailFormatTgs, err + + case ThumbnailFormatMpeg4Type: + var thumbnailFormatMpeg4 ThumbnailFormatMpeg4 + err := json.Unmarshal(*rawMsg, &thumbnailFormatMpeg4) + return &thumbnailFormatMpeg4, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// ThumbnailFormatJpeg The thumbnail is in JPEG format +type ThumbnailFormatJpeg struct { + tdCommon +} + +// MessageType return the string telegram-type of ThumbnailFormatJpeg +func (thumbnailFormatJpeg *ThumbnailFormatJpeg) MessageType() string { + return "thumbnailFormatJpeg" +} + +// NewThumbnailFormatJpeg creates a new ThumbnailFormatJpeg +// +func NewThumbnailFormatJpeg() *ThumbnailFormatJpeg { + thumbnailFormatJpegTemp := ThumbnailFormatJpeg{ + tdCommon: tdCommon{Type: "thumbnailFormatJpeg"}, + } + + return &thumbnailFormatJpegTemp +} + +// GetThumbnailFormatEnum return the enum type of this object +func (thumbnailFormatJpeg *ThumbnailFormatJpeg) GetThumbnailFormatEnum() ThumbnailFormatEnum { + return ThumbnailFormatJpegType +} + +// ThumbnailFormatPng The thumbnail is in PNG format. It will be used only for background patterns +type ThumbnailFormatPng struct { + tdCommon +} + +// MessageType return the string telegram-type of ThumbnailFormatPng +func (thumbnailFormatPng *ThumbnailFormatPng) MessageType() string { + return "thumbnailFormatPng" +} + +// NewThumbnailFormatPng creates a new ThumbnailFormatPng +// +func NewThumbnailFormatPng() *ThumbnailFormatPng { + thumbnailFormatPngTemp := ThumbnailFormatPng{ + tdCommon: tdCommon{Type: "thumbnailFormatPng"}, + } + + return &thumbnailFormatPngTemp +} + +// GetThumbnailFormatEnum return the enum type of this object +func (thumbnailFormatPng *ThumbnailFormatPng) GetThumbnailFormatEnum() ThumbnailFormatEnum { + return ThumbnailFormatPngType +} + +// ThumbnailFormatWebp The thumbnail is in WEBP format. It will be used only for some stickers +type ThumbnailFormatWebp struct { + tdCommon +} + +// MessageType return the string telegram-type of ThumbnailFormatWebp +func (thumbnailFormatWebp *ThumbnailFormatWebp) MessageType() string { + return "thumbnailFormatWebp" +} + +// NewThumbnailFormatWebp creates a new ThumbnailFormatWebp +// +func NewThumbnailFormatWebp() *ThumbnailFormatWebp { + thumbnailFormatWebpTemp := ThumbnailFormatWebp{ + tdCommon: tdCommon{Type: "thumbnailFormatWebp"}, + } + + return &thumbnailFormatWebpTemp +} + +// GetThumbnailFormatEnum return the enum type of this object +func (thumbnailFormatWebp *ThumbnailFormatWebp) GetThumbnailFormatEnum() ThumbnailFormatEnum { + return ThumbnailFormatWebpType +} + +// ThumbnailFormatGif The thumbnail is in static GIF format. It will be used only for some bot inline results +type ThumbnailFormatGif struct { + tdCommon +} + +// MessageType return the string telegram-type of ThumbnailFormatGif +func (thumbnailFormatGif *ThumbnailFormatGif) MessageType() string { + return "thumbnailFormatGif" +} + +// NewThumbnailFormatGif creates a new ThumbnailFormatGif +// +func NewThumbnailFormatGif() *ThumbnailFormatGif { + thumbnailFormatGifTemp := ThumbnailFormatGif{ + tdCommon: tdCommon{Type: "thumbnailFormatGif"}, + } + + return &thumbnailFormatGifTemp +} + +// GetThumbnailFormatEnum return the enum type of this object +func (thumbnailFormatGif *ThumbnailFormatGif) GetThumbnailFormatEnum() ThumbnailFormatEnum { + return ThumbnailFormatGifType +} + +// ThumbnailFormatTgs The thumbnail is in TGS format. It will be used only for animated sticker sets +type ThumbnailFormatTgs struct { + tdCommon +} + +// MessageType return the string telegram-type of ThumbnailFormatTgs +func (thumbnailFormatTgs *ThumbnailFormatTgs) MessageType() string { + return "thumbnailFormatTgs" +} + +// NewThumbnailFormatTgs creates a new ThumbnailFormatTgs +// +func NewThumbnailFormatTgs() *ThumbnailFormatTgs { + thumbnailFormatTgsTemp := ThumbnailFormatTgs{ + tdCommon: tdCommon{Type: "thumbnailFormatTgs"}, + } + + return &thumbnailFormatTgsTemp +} + +// GetThumbnailFormatEnum return the enum type of this object +func (thumbnailFormatTgs *ThumbnailFormatTgs) GetThumbnailFormatEnum() ThumbnailFormatEnum { + return ThumbnailFormatTgsType +} + +// ThumbnailFormatMpeg4 The thumbnail is in MPEG4 format. It will be used only for some animations and videos +type ThumbnailFormatMpeg4 struct { + tdCommon +} + +// MessageType return the string telegram-type of ThumbnailFormatMpeg4 +func (thumbnailFormatMpeg4 *ThumbnailFormatMpeg4) MessageType() string { + return "thumbnailFormatMpeg4" +} + +// NewThumbnailFormatMpeg4 creates a new ThumbnailFormatMpeg4 +// +func NewThumbnailFormatMpeg4() *ThumbnailFormatMpeg4 { + thumbnailFormatMpeg4Temp := ThumbnailFormatMpeg4{ + tdCommon: tdCommon{Type: "thumbnailFormatMpeg4"}, + } + + return &thumbnailFormatMpeg4Temp +} + +// GetThumbnailFormatEnum return the enum type of this object +func (thumbnailFormatMpeg4 *ThumbnailFormatMpeg4) GetThumbnailFormatEnum() ThumbnailFormatEnum { + return ThumbnailFormatMpeg4Type +} diff --git a/tdlib/topChatCategory.go b/tdlib/topChatCategory.go new file mode 100644 index 0000000..a4cb839 --- /dev/null +++ b/tdlib/topChatCategory.go @@ -0,0 +1,254 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// TopChatCategory Represents the categories of chats for which a list of frequently used chats can be retrieved +type TopChatCategory interface { + GetTopChatCategoryEnum() TopChatCategoryEnum +} + +// 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" + TopChatCategoryForwardChatsType TopChatCategoryEnum = "topChatCategoryForwardChats" +) + +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 + + case TopChatCategoryForwardChatsType: + var topChatCategoryForwardChats TopChatCategoryForwardChats + err := json.Unmarshal(*rawMsg, &topChatCategoryForwardChats) + return &topChatCategoryForwardChats, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 +} + +// TopChatCategoryForwardChats A category containing frequently used chats used to forward messages +type TopChatCategoryForwardChats struct { + tdCommon +} + +// MessageType return the string telegram-type of TopChatCategoryForwardChats +func (topChatCategoryForwardChats *TopChatCategoryForwardChats) MessageType() string { + return "topChatCategoryForwardChats" +} + +// NewTopChatCategoryForwardChats creates a new TopChatCategoryForwardChats +// +func NewTopChatCategoryForwardChats() *TopChatCategoryForwardChats { + topChatCategoryForwardChatsTemp := TopChatCategoryForwardChats{ + tdCommon: tdCommon{Type: "topChatCategoryForwardChats"}, + } + + return &topChatCategoryForwardChatsTemp +} + +// GetTopChatCategoryEnum return the enum type of this object +func (topChatCategoryForwardChats *TopChatCategoryForwardChats) GetTopChatCategoryEnum() TopChatCategoryEnum { + return TopChatCategoryForwardChatsType +} diff --git a/tdlib/update.go b/tdlib/update.go new file mode 100644 index 0000000..99b36a5 --- /dev/null +++ b/tdlib/update.go @@ -0,0 +1,3839 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// Update Contains notifications about data changes +type Update interface { + GetUpdateEnum() UpdateEnum +} + +// 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" + UpdateMessageIsPinnedType UpdateEnum = "updateMessageIsPinned" + UpdateMessageInteractionInfoType UpdateEnum = "updateMessageInteractionInfo" + UpdateMessageContentOpenedType UpdateEnum = "updateMessageContentOpened" + UpdateMessageMentionReadType UpdateEnum = "updateMessageMentionRead" + UpdateMessageLiveLocationViewedType UpdateEnum = "updateMessageLiveLocationViewed" + UpdateNewChatType UpdateEnum = "updateNewChat" + UpdateChatTitleType UpdateEnum = "updateChatTitle" + UpdateChatPhotoType UpdateEnum = "updateChatPhoto" + UpdateChatPermissionsType UpdateEnum = "updateChatPermissions" + UpdateChatLastMessageType UpdateEnum = "updateChatLastMessage" + UpdateChatPositionType UpdateEnum = "updateChatPosition" + UpdateChatIsMarkedAsUnreadType UpdateEnum = "updateChatIsMarkedAsUnread" + UpdateChatIsBlockedType UpdateEnum = "updateChatIsBlocked" + UpdateChatHasScheduledMessagesType UpdateEnum = "updateChatHasScheduledMessages" + UpdateChatVoiceChatType UpdateEnum = "updateChatVoiceChat" + UpdateChatDefaultDisableNotificationType UpdateEnum = "updateChatDefaultDisableNotification" + UpdateChatReadInboxType UpdateEnum = "updateChatReadInbox" + UpdateChatReadOutboxType UpdateEnum = "updateChatReadOutbox" + UpdateChatUnreadMentionCountType UpdateEnum = "updateChatUnreadMentionCount" + UpdateChatNotificationSettingsType UpdateEnum = "updateChatNotificationSettings" + UpdateScopeNotificationSettingsType UpdateEnum = "updateScopeNotificationSettings" + UpdateChatMessageTTLSettingType UpdateEnum = "updateChatMessageTtlSetting" + UpdateChatActionBarType UpdateEnum = "updateChatActionBar" + UpdateChatThemeType UpdateEnum = "updateChatTheme" + UpdateChatReplyMarkupType UpdateEnum = "updateChatReplyMarkup" + UpdateChatDraftMessageType UpdateEnum = "updateChatDraftMessage" + UpdateChatFiltersType UpdateEnum = "updateChatFilters" + UpdateChatOnlineMemberCountType UpdateEnum = "updateChatOnlineMemberCount" + UpdateNotificationType UpdateEnum = "updateNotification" + UpdateNotificationGroupType UpdateEnum = "updateNotificationGroup" + UpdateActiveNotificationsType UpdateEnum = "updateActiveNotifications" + UpdateHavePendingNotificationsType UpdateEnum = "updateHavePendingNotifications" + 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" + UpdateGroupCallType UpdateEnum = "updateGroupCall" + UpdateGroupCallParticipantType UpdateEnum = "updateGroupCallParticipant" + UpdateNewCallSignalingDataType UpdateEnum = "updateNewCallSignalingData" + UpdateUserPrivacySettingRulesType UpdateEnum = "updateUserPrivacySettingRules" + UpdateUnreadMessageCountType UpdateEnum = "updateUnreadMessageCount" + UpdateUnreadChatCountType UpdateEnum = "updateUnreadChatCount" + UpdateOptionType UpdateEnum = "updateOption" + UpdateStickerSetType UpdateEnum = "updateStickerSet" + UpdateInstalledStickerSetsType UpdateEnum = "updateInstalledStickerSets" + UpdateTrendingStickerSetsType UpdateEnum = "updateTrendingStickerSets" + UpdateRecentStickersType UpdateEnum = "updateRecentStickers" + UpdateFavoriteStickersType UpdateEnum = "updateFavoriteStickers" + UpdateSavedAnimationsType UpdateEnum = "updateSavedAnimations" + UpdateSelectedBackgroundType UpdateEnum = "updateSelectedBackground" + UpdateChatThemesType UpdateEnum = "updateChatThemes" + UpdateLanguagePackStringsType UpdateEnum = "updateLanguagePackStrings" + UpdateConnectionStateType UpdateEnum = "updateConnectionState" + UpdateTermsOfServiceType UpdateEnum = "updateTermsOfService" + UpdateUsersNearbyType UpdateEnum = "updateUsersNearby" + UpdateDiceEmojisType UpdateEnum = "updateDiceEmojis" + UpdateAnimationSearchParametersType UpdateEnum = "updateAnimationSearchParameters" + UpdateSuggestedActionsType UpdateEnum = "updateSuggestedActions" + UpdateNewInlineQueryType UpdateEnum = "updateNewInlineQuery" + UpdateNewChosenInlineResultType UpdateEnum = "updateNewChosenInlineResult" + UpdateNewCallbackQueryType UpdateEnum = "updateNewCallbackQuery" + UpdateNewInlineCallbackQueryType UpdateEnum = "updateNewInlineCallbackQuery" + UpdateNewShippingQueryType UpdateEnum = "updateNewShippingQuery" + UpdateNewPreCheckoutQueryType UpdateEnum = "updateNewPreCheckoutQuery" + UpdateNewCustomEventType UpdateEnum = "updateNewCustomEvent" + UpdateNewCustomQueryType UpdateEnum = "updateNewCustomQuery" + UpdatePollType UpdateEnum = "updatePoll" + UpdatePollAnswerType UpdateEnum = "updatePollAnswer" + UpdateChatMemberType UpdateEnum = "updateChatMember" +) + +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 UpdateMessageIsPinnedType: + var updateMessageIsPinned UpdateMessageIsPinned + err := json.Unmarshal(*rawMsg, &updateMessageIsPinned) + return &updateMessageIsPinned, err + + case UpdateMessageInteractionInfoType: + var updateMessageInteractionInfo UpdateMessageInteractionInfo + err := json.Unmarshal(*rawMsg, &updateMessageInteractionInfo) + return &updateMessageInteractionInfo, 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 UpdateMessageLiveLocationViewedType: + var updateMessageLiveLocationViewed UpdateMessageLiveLocationViewed + err := json.Unmarshal(*rawMsg, &updateMessageLiveLocationViewed) + return &updateMessageLiveLocationViewed, 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 UpdateChatPermissionsType: + var updateChatPermissions UpdateChatPermissions + err := json.Unmarshal(*rawMsg, &updateChatPermissions) + return &updateChatPermissions, err + + case UpdateChatLastMessageType: + var updateChatLastMessage UpdateChatLastMessage + err := json.Unmarshal(*rawMsg, &updateChatLastMessage) + return &updateChatLastMessage, err + + case UpdateChatPositionType: + var updateChatPosition UpdateChatPosition + err := json.Unmarshal(*rawMsg, &updateChatPosition) + return &updateChatPosition, err + + case UpdateChatIsMarkedAsUnreadType: + var updateChatIsMarkedAsUnread UpdateChatIsMarkedAsUnread + err := json.Unmarshal(*rawMsg, &updateChatIsMarkedAsUnread) + return &updateChatIsMarkedAsUnread, err + + case UpdateChatIsBlockedType: + var updateChatIsBlocked UpdateChatIsBlocked + err := json.Unmarshal(*rawMsg, &updateChatIsBlocked) + return &updateChatIsBlocked, err + + case UpdateChatHasScheduledMessagesType: + var updateChatHasScheduledMessages UpdateChatHasScheduledMessages + err := json.Unmarshal(*rawMsg, &updateChatHasScheduledMessages) + return &updateChatHasScheduledMessages, err + + case UpdateChatVoiceChatType: + var updateChatVoiceChat UpdateChatVoiceChat + err := json.Unmarshal(*rawMsg, &updateChatVoiceChat) + return &updateChatVoiceChat, 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 UpdateChatMessageTTLSettingType: + var updateChatMessageTTLSetting UpdateChatMessageTTLSetting + err := json.Unmarshal(*rawMsg, &updateChatMessageTTLSetting) + return &updateChatMessageTTLSetting, err + + case UpdateChatActionBarType: + var updateChatActionBar UpdateChatActionBar + err := json.Unmarshal(*rawMsg, &updateChatActionBar) + return &updateChatActionBar, err + + case UpdateChatThemeType: + var updateChatTheme UpdateChatTheme + err := json.Unmarshal(*rawMsg, &updateChatTheme) + return &updateChatTheme, 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 UpdateChatFiltersType: + var updateChatFilters UpdateChatFilters + err := json.Unmarshal(*rawMsg, &updateChatFilters) + return &updateChatFilters, err + + case UpdateChatOnlineMemberCountType: + var updateChatOnlineMemberCount UpdateChatOnlineMemberCount + err := json.Unmarshal(*rawMsg, &updateChatOnlineMemberCount) + return &updateChatOnlineMemberCount, err + + case UpdateNotificationType: + var updateNotification UpdateNotification + err := json.Unmarshal(*rawMsg, &updateNotification) + return &updateNotification, err + + case UpdateNotificationGroupType: + var updateNotificationGroup UpdateNotificationGroup + err := json.Unmarshal(*rawMsg, &updateNotificationGroup) + return &updateNotificationGroup, err + + case UpdateActiveNotificationsType: + var updateActiveNotifications UpdateActiveNotifications + err := json.Unmarshal(*rawMsg, &updateActiveNotifications) + return &updateActiveNotifications, err + + case UpdateHavePendingNotificationsType: + var updateHavePendingNotifications UpdateHavePendingNotifications + err := json.Unmarshal(*rawMsg, &updateHavePendingNotifications) + return &updateHavePendingNotifications, 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 UpdateGroupCallType: + var updateGroupCall UpdateGroupCall + err := json.Unmarshal(*rawMsg, &updateGroupCall) + return &updateGroupCall, err + + case UpdateGroupCallParticipantType: + var updateGroupCallParticipant UpdateGroupCallParticipant + err := json.Unmarshal(*rawMsg, &updateGroupCallParticipant) + return &updateGroupCallParticipant, err + + case UpdateNewCallSignalingDataType: + var updateNewCallSignalingData UpdateNewCallSignalingData + err := json.Unmarshal(*rawMsg, &updateNewCallSignalingData) + return &updateNewCallSignalingData, 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 UpdateStickerSetType: + var updateStickerSet UpdateStickerSet + err := json.Unmarshal(*rawMsg, &updateStickerSet) + return &updateStickerSet, 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 UpdateSelectedBackgroundType: + var updateSelectedBackground UpdateSelectedBackground + err := json.Unmarshal(*rawMsg, &updateSelectedBackground) + return &updateSelectedBackground, err + + case UpdateChatThemesType: + var updateChatThemes UpdateChatThemes + err := json.Unmarshal(*rawMsg, &updateChatThemes) + return &updateChatThemes, 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 UpdateUsersNearbyType: + var updateUsersNearby UpdateUsersNearby + err := json.Unmarshal(*rawMsg, &updateUsersNearby) + return &updateUsersNearby, err + + case UpdateDiceEmojisType: + var updateDiceEmojis UpdateDiceEmojis + err := json.Unmarshal(*rawMsg, &updateDiceEmojis) + return &updateDiceEmojis, err + + case UpdateAnimationSearchParametersType: + var updateAnimationSearchParameters UpdateAnimationSearchParameters + err := json.Unmarshal(*rawMsg, &updateAnimationSearchParameters) + return &updateAnimationSearchParameters, err + + case UpdateSuggestedActionsType: + var updateSuggestedActions UpdateSuggestedActions + err := json.Unmarshal(*rawMsg, &updateSuggestedActions) + return &updateSuggestedActions, 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 + + case UpdatePollType: + var updatePoll UpdatePoll + err := json.Unmarshal(*rawMsg, &updatePoll) + return &updatePoll, err + + case UpdatePollAnswerType: + var updatePollAnswer UpdatePollAnswer + err := json.Unmarshal(*rawMsg, &updatePollAnswer) + return &updatePollAnswer, err + + case UpdateChatMemberType: + var updateChatMember UpdateChatMember + err := json.Unmarshal(*rawMsg, &updateChatMember) + return &updateChatMember, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 +} + +// 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 +func NewUpdateNewMessage(message *Message) *UpdateNewMessage { + updateNewMessageTemp := UpdateNewMessage{ + tdCommon: tdCommon{Type: "updateNewMessage"}, + Message: message, + } + + 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 which 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 which 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 +} + +// UpdateMessageIsPinned The message pinned state was changed +type UpdateMessageIsPinned struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // The message identifier + IsPinned bool `json:"is_pinned"` // True, if the message is pinned +} + +// MessageType return the string telegram-type of UpdateMessageIsPinned +func (updateMessageIsPinned *UpdateMessageIsPinned) MessageType() string { + return "updateMessageIsPinned" +} + +// NewUpdateMessageIsPinned creates a new UpdateMessageIsPinned +// +// @param chatID Chat identifier +// @param messageID The message identifier +// @param isPinned True, if the message is pinned +func NewUpdateMessageIsPinned(chatID int64, messageID int64, isPinned bool) *UpdateMessageIsPinned { + updateMessageIsPinnedTemp := UpdateMessageIsPinned{ + tdCommon: tdCommon{Type: "updateMessageIsPinned"}, + ChatID: chatID, + MessageID: messageID, + IsPinned: isPinned, + } + + return &updateMessageIsPinnedTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageIsPinned *UpdateMessageIsPinned) GetUpdateEnum() UpdateEnum { + return UpdateMessageIsPinnedType +} + +// UpdateMessageInteractionInfo The information about interactions with a message has changed +type UpdateMessageInteractionInfo struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageID int64 `json:"message_id"` // Message identifier + InteractionInfo *MessageInteractionInfo `json:"interaction_info"` // New information about interactions with the message; may be null +} + +// MessageType return the string telegram-type of UpdateMessageInteractionInfo +func (updateMessageInteractionInfo *UpdateMessageInteractionInfo) MessageType() string { + return "updateMessageInteractionInfo" +} + +// NewUpdateMessageInteractionInfo creates a new UpdateMessageInteractionInfo +// +// @param chatID Chat identifier +// @param messageID Message identifier +// @param interactionInfo New information about interactions with the message; may be null +func NewUpdateMessageInteractionInfo(chatID int64, messageID int64, interactionInfo *MessageInteractionInfo) *UpdateMessageInteractionInfo { + updateMessageInteractionInfoTemp := UpdateMessageInteractionInfo{ + tdCommon: tdCommon{Type: "updateMessageInteractionInfo"}, + ChatID: chatID, + MessageID: messageID, + InteractionInfo: interactionInfo, + } + + return &updateMessageInteractionInfoTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageInteractionInfo *UpdateMessageInteractionInfo) GetUpdateEnum() UpdateEnum { + return UpdateMessageInteractionInfoType +} + +// 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 +} + +// UpdateMessageLiveLocationViewed A message with a live location was viewed. When the update is received, the application is supposed to update the live location +type UpdateMessageLiveLocationViewed struct { + tdCommon + ChatID int64 `json:"chat_id"` // Identifier of the chat with the live location message + MessageID int64 `json:"message_id"` // Identifier of the message with live location +} + +// MessageType return the string telegram-type of UpdateMessageLiveLocationViewed +func (updateMessageLiveLocationViewed *UpdateMessageLiveLocationViewed) MessageType() string { + return "updateMessageLiveLocationViewed" +} + +// NewUpdateMessageLiveLocationViewed creates a new UpdateMessageLiveLocationViewed +// +// @param chatID Identifier of the chat with the live location message +// @param messageID Identifier of the message with live location +func NewUpdateMessageLiveLocationViewed(chatID int64, messageID int64) *UpdateMessageLiveLocationViewed { + updateMessageLiveLocationViewedTemp := UpdateMessageLiveLocationViewed{ + tdCommon: tdCommon{Type: "updateMessageLiveLocationViewed"}, + ChatID: chatID, + MessageID: messageID, + } + + return &updateMessageLiveLocationViewedTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateMessageLiveLocationViewed *UpdateMessageLiveLocationViewed) GetUpdateEnum() UpdateEnum { + return UpdateMessageLiveLocationViewedType +} + +// UpdateNewChat A new chat has been loaded/created. This update is guaranteed to come before the chat identifier is returned to the application. 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 *ChatPhotoInfo `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 *ChatPhotoInfo) *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 +} + +// UpdateChatPermissions Chat permissions was changed +type UpdateChatPermissions struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + Permissions *ChatPermissions `json:"permissions"` // The new chat permissions +} + +// MessageType return the string telegram-type of UpdateChatPermissions +func (updateChatPermissions *UpdateChatPermissions) MessageType() string { + return "updateChatPermissions" +} + +// NewUpdateChatPermissions creates a new UpdateChatPermissions +// +// @param chatID Chat identifier +// @param permissions The new chat permissions +func NewUpdateChatPermissions(chatID int64, permissions *ChatPermissions) *UpdateChatPermissions { + updateChatPermissionsTemp := UpdateChatPermissions{ + tdCommon: tdCommon{Type: "updateChatPermissions"}, + ChatID: chatID, + Permissions: permissions, + } + + return &updateChatPermissionsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatPermissions *UpdateChatPermissions) GetUpdateEnum() UpdateEnum { + return UpdateChatPermissionsType +} + +// 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 + Positions []ChatPosition `json:"positions"` // The new chat positions in the chat lists +} + +// 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 positions The new chat positions in the chat lists +func NewUpdateChatLastMessage(chatID int64, lastMessage *Message, positions []ChatPosition) *UpdateChatLastMessage { + updateChatLastMessageTemp := UpdateChatLastMessage{ + tdCommon: tdCommon{Type: "updateChatLastMessage"}, + ChatID: chatID, + LastMessage: lastMessage, + Positions: positions, + } + + return &updateChatLastMessageTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatLastMessage *UpdateChatLastMessage) GetUpdateEnum() UpdateEnum { + return UpdateChatLastMessageType +} + +// UpdateChatPosition The position of a chat in a chat list has changed. Instead of this update updateChatLastMessage or updateChatDraftMessage might be sent +type UpdateChatPosition struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + Position *ChatPosition `json:"position"` // New chat position. If new order is 0, then the chat needs to be removed from the list +} + +// MessageType return the string telegram-type of UpdateChatPosition +func (updateChatPosition *UpdateChatPosition) MessageType() string { + return "updateChatPosition" +} + +// NewUpdateChatPosition creates a new UpdateChatPosition +// +// @param chatID Chat identifier +// @param position New chat position. If new order is 0, then the chat needs to be removed from the list +func NewUpdateChatPosition(chatID int64, position *ChatPosition) *UpdateChatPosition { + updateChatPositionTemp := UpdateChatPosition{ + tdCommon: tdCommon{Type: "updateChatPosition"}, + ChatID: chatID, + Position: position, + } + + return &updateChatPositionTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatPosition *UpdateChatPosition) GetUpdateEnum() UpdateEnum { + return UpdateChatPositionType +} + +// 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 +} + +// UpdateChatIsBlocked A chat was blocked or unblocked +type UpdateChatIsBlocked struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + IsBlocked bool `json:"is_blocked"` // New value of is_blocked +} + +// MessageType return the string telegram-type of UpdateChatIsBlocked +func (updateChatIsBlocked *UpdateChatIsBlocked) MessageType() string { + return "updateChatIsBlocked" +} + +// NewUpdateChatIsBlocked creates a new UpdateChatIsBlocked +// +// @param chatID Chat identifier +// @param isBlocked New value of is_blocked +func NewUpdateChatIsBlocked(chatID int64, isBlocked bool) *UpdateChatIsBlocked { + updateChatIsBlockedTemp := UpdateChatIsBlocked{ + tdCommon: tdCommon{Type: "updateChatIsBlocked"}, + ChatID: chatID, + IsBlocked: isBlocked, + } + + return &updateChatIsBlockedTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatIsBlocked *UpdateChatIsBlocked) GetUpdateEnum() UpdateEnum { + return UpdateChatIsBlockedType +} + +// UpdateChatHasScheduledMessages A chat's has_scheduled_messages field has changed +type UpdateChatHasScheduledMessages struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + HasScheduledMessages bool `json:"has_scheduled_messages"` // New value of has_scheduled_messages +} + +// MessageType return the string telegram-type of UpdateChatHasScheduledMessages +func (updateChatHasScheduledMessages *UpdateChatHasScheduledMessages) MessageType() string { + return "updateChatHasScheduledMessages" +} + +// NewUpdateChatHasScheduledMessages creates a new UpdateChatHasScheduledMessages +// +// @param chatID Chat identifier +// @param hasScheduledMessages New value of has_scheduled_messages +func NewUpdateChatHasScheduledMessages(chatID int64, hasScheduledMessages bool) *UpdateChatHasScheduledMessages { + updateChatHasScheduledMessagesTemp := UpdateChatHasScheduledMessages{ + tdCommon: tdCommon{Type: "updateChatHasScheduledMessages"}, + ChatID: chatID, + HasScheduledMessages: hasScheduledMessages, + } + + return &updateChatHasScheduledMessagesTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatHasScheduledMessages *UpdateChatHasScheduledMessages) GetUpdateEnum() UpdateEnum { + return UpdateChatHasScheduledMessagesType +} + +// UpdateChatVoiceChat A chat voice chat state has changed +type UpdateChatVoiceChat struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + VoiceChat *VoiceChat `json:"voice_chat"` // New value of voice_chat +} + +// MessageType return the string telegram-type of UpdateChatVoiceChat +func (updateChatVoiceChat *UpdateChatVoiceChat) MessageType() string { + return "updateChatVoiceChat" +} + +// NewUpdateChatVoiceChat creates a new UpdateChatVoiceChat +// +// @param chatID Chat identifier +// @param voiceChat New value of voice_chat +func NewUpdateChatVoiceChat(chatID int64, voiceChat *VoiceChat) *UpdateChatVoiceChat { + updateChatVoiceChatTemp := UpdateChatVoiceChat{ + tdCommon: tdCommon{Type: "updateChatVoiceChat"}, + ChatID: chatID, + VoiceChat: voiceChat, + } + + return &updateChatVoiceChatTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatVoiceChat *UpdateChatVoiceChat) GetUpdateEnum() UpdateEnum { + return UpdateChatVoiceChatType +} + +// 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 +} + +// UpdateChatMessageTTLSetting The message Time To Live setting for a chat was changed +type UpdateChatMessageTTLSetting struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + MessageTTLSetting int32 `json:"message_ttl_setting"` // New value of message_ttl_setting +} + +// MessageType return the string telegram-type of UpdateChatMessageTTLSetting +func (updateChatMessageTTLSetting *UpdateChatMessageTTLSetting) MessageType() string { + return "updateChatMessageTtlSetting" +} + +// NewUpdateChatMessageTTLSetting creates a new UpdateChatMessageTTLSetting +// +// @param chatID Chat identifier +// @param messageTTLSetting New value of message_ttl_setting +func NewUpdateChatMessageTTLSetting(chatID int64, messageTTLSetting int32) *UpdateChatMessageTTLSetting { + updateChatMessageTTLSettingTemp := UpdateChatMessageTTLSetting{ + tdCommon: tdCommon{Type: "updateChatMessageTtlSetting"}, + ChatID: chatID, + MessageTTLSetting: messageTTLSetting, + } + + return &updateChatMessageTTLSettingTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatMessageTTLSetting *UpdateChatMessageTTLSetting) GetUpdateEnum() UpdateEnum { + return UpdateChatMessageTTLSettingType +} + +// UpdateChatActionBar The chat action bar was changed +type UpdateChatActionBar struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + ActionBar ChatActionBar `json:"action_bar"` // The new value of the action bar; may be null +} + +// MessageType return the string telegram-type of UpdateChatActionBar +func (updateChatActionBar *UpdateChatActionBar) MessageType() string { + return "updateChatActionBar" +} + +// NewUpdateChatActionBar creates a new UpdateChatActionBar +// +// @param chatID Chat identifier +// @param actionBar The new value of the action bar; may be null +func NewUpdateChatActionBar(chatID int64, actionBar ChatActionBar) *UpdateChatActionBar { + updateChatActionBarTemp := UpdateChatActionBar{ + tdCommon: tdCommon{Type: "updateChatActionBar"}, + ChatID: chatID, + ActionBar: actionBar, + } + + return &updateChatActionBarTemp +} + +// UnmarshalJSON unmarshal to json +func (updateChatActionBar *UpdateChatActionBar) 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 + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateChatActionBar.tdCommon = tempObj.tdCommon + updateChatActionBar.ChatID = tempObj.ChatID + + fieldActionBar, _ := unmarshalChatActionBar(objMap["action_bar"]) + updateChatActionBar.ActionBar = fieldActionBar + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateChatActionBar *UpdateChatActionBar) GetUpdateEnum() UpdateEnum { + return UpdateChatActionBarType +} + +// UpdateChatTheme The chat theme was changed +type UpdateChatTheme struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + ThemeName string `json:"theme_name"` // The new name of the chat theme; may be empty if theme was reset to default +} + +// MessageType return the string telegram-type of UpdateChatTheme +func (updateChatTheme *UpdateChatTheme) MessageType() string { + return "updateChatTheme" +} + +// NewUpdateChatTheme creates a new UpdateChatTheme +// +// @param chatID Chat identifier +// @param themeName The new name of the chat theme; may be empty if theme was reset to default +func NewUpdateChatTheme(chatID int64, themeName string) *UpdateChatTheme { + updateChatThemeTemp := UpdateChatTheme{ + tdCommon: tdCommon{Type: "updateChatTheme"}, + ChatID: chatID, + ThemeName: themeName, + } + + return &updateChatThemeTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatTheme *UpdateChatTheme) GetUpdateEnum() UpdateEnum { + return UpdateChatThemeType +} + +// 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 + Positions []ChatPosition `json:"positions"` // The new chat positions in the chat lists +} + +// 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 positions The new chat positions in the chat lists +func NewUpdateChatDraftMessage(chatID int64, draftMessage *DraftMessage, positions []ChatPosition) *UpdateChatDraftMessage { + updateChatDraftMessageTemp := UpdateChatDraftMessage{ + tdCommon: tdCommon{Type: "updateChatDraftMessage"}, + ChatID: chatID, + DraftMessage: draftMessage, + Positions: positions, + } + + return &updateChatDraftMessageTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatDraftMessage *UpdateChatDraftMessage) GetUpdateEnum() UpdateEnum { + return UpdateChatDraftMessageType +} + +// UpdateChatFilters The list of chat filters or a chat filter has changed +type UpdateChatFilters struct { + tdCommon + ChatFilters []ChatFilterInfo `json:"chat_filters"` // The new list of chat filters +} + +// MessageType return the string telegram-type of UpdateChatFilters +func (updateChatFilters *UpdateChatFilters) MessageType() string { + return "updateChatFilters" +} + +// NewUpdateChatFilters creates a new UpdateChatFilters +// +// @param chatFilters The new list of chat filters +func NewUpdateChatFilters(chatFilters []ChatFilterInfo) *UpdateChatFilters { + updateChatFiltersTemp := UpdateChatFilters{ + tdCommon: tdCommon{Type: "updateChatFilters"}, + ChatFilters: chatFilters, + } + + return &updateChatFiltersTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatFilters *UpdateChatFilters) GetUpdateEnum() UpdateEnum { + return UpdateChatFiltersType +} + +// UpdateChatOnlineMemberCount The number of online group members has changed. This update with non-zero count is sent only for currently opened chats. There is no guarantee that it will be sent just after the count has changed +type UpdateChatOnlineMemberCount struct { + tdCommon + ChatID int64 `json:"chat_id"` // Identifier of the chat + OnlineMemberCount int32 `json:"online_member_count"` // New number of online members in the chat, or 0 if unknown +} + +// MessageType return the string telegram-type of UpdateChatOnlineMemberCount +func (updateChatOnlineMemberCount *UpdateChatOnlineMemberCount) MessageType() string { + return "updateChatOnlineMemberCount" +} + +// NewUpdateChatOnlineMemberCount creates a new UpdateChatOnlineMemberCount +// +// @param chatID Identifier of the chat +// @param onlineMemberCount New number of online members in the chat, or 0 if unknown +func NewUpdateChatOnlineMemberCount(chatID int64, onlineMemberCount int32) *UpdateChatOnlineMemberCount { + updateChatOnlineMemberCountTemp := UpdateChatOnlineMemberCount{ + tdCommon: tdCommon{Type: "updateChatOnlineMemberCount"}, + ChatID: chatID, + OnlineMemberCount: onlineMemberCount, + } + + return &updateChatOnlineMemberCountTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatOnlineMemberCount *UpdateChatOnlineMemberCount) GetUpdateEnum() UpdateEnum { + return UpdateChatOnlineMemberCountType +} + +// UpdateNotification A notification was changed +type UpdateNotification struct { + tdCommon + NotificationGroupID int32 `json:"notification_group_id"` // Unique notification group identifier + Notification *Notification `json:"notification"` // Changed notification +} + +// MessageType return the string telegram-type of UpdateNotification +func (updateNotification *UpdateNotification) MessageType() string { + return "updateNotification" +} + +// NewUpdateNotification creates a new UpdateNotification +// +// @param notificationGroupID Unique notification group identifier +// @param notification Changed notification +func NewUpdateNotification(notificationGroupID int32, notification *Notification) *UpdateNotification { + updateNotificationTemp := UpdateNotification{ + tdCommon: tdCommon{Type: "updateNotification"}, + NotificationGroupID: notificationGroupID, + Notification: notification, + } + + return &updateNotificationTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNotification *UpdateNotification) GetUpdateEnum() UpdateEnum { + return UpdateNotificationType +} + +// UpdateNotificationGroup A list of active notifications in a notification group has changed +type UpdateNotificationGroup struct { + tdCommon + NotificationGroupID int32 `json:"notification_group_id"` // Unique notification group identifier + Type NotificationGroupType `json:"type"` // New type of the notification group + ChatID int64 `json:"chat_id"` // Identifier of a chat to which all notifications in the group belong + NotificationSettingsChatID int64 `json:"notification_settings_chat_id"` // Chat identifier, which notification settings must be applied to the added notifications + IsSilent bool `json:"is_silent"` // True, if the notifications should be shown without sound + TotalCount int32 `json:"total_count"` // Total number of unread notifications in the group, can be bigger than number of active notifications + AddedNotifications []Notification `json:"added_notifications"` // List of added group notifications, sorted by notification ID + RemovedNotificationIDs []int32 `json:"removed_notification_ids"` // Identifiers of removed group notifications, sorted by notification ID +} + +// MessageType return the string telegram-type of UpdateNotificationGroup +func (updateNotificationGroup *UpdateNotificationGroup) MessageType() string { + return "updateNotificationGroup" +} + +// NewUpdateNotificationGroup creates a new UpdateNotificationGroup +// +// @param notificationGroupID Unique notification group identifier +// @param typeParam New type of the notification group +// @param chatID Identifier of a chat to which all notifications in the group belong +// @param notificationSettingsChatID Chat identifier, which notification settings must be applied to the added notifications +// @param isSilent True, if the notifications should be shown without sound +// @param totalCount Total number of unread notifications in the group, can be bigger than number of active notifications +// @param addedNotifications List of added group notifications, sorted by notification ID +// @param removedNotificationIDs Identifiers of removed group notifications, sorted by notification ID +func NewUpdateNotificationGroup(notificationGroupID int32, typeParam NotificationGroupType, chatID int64, notificationSettingsChatID int64, isSilent bool, totalCount int32, addedNotifications []Notification, removedNotificationIDs []int32) *UpdateNotificationGroup { + updateNotificationGroupTemp := UpdateNotificationGroup{ + tdCommon: tdCommon{Type: "updateNotificationGroup"}, + NotificationGroupID: notificationGroupID, + Type: typeParam, + ChatID: chatID, + NotificationSettingsChatID: notificationSettingsChatID, + IsSilent: isSilent, + TotalCount: totalCount, + AddedNotifications: addedNotifications, + RemovedNotificationIDs: removedNotificationIDs, + } + + return &updateNotificationGroupTemp +} + +// UnmarshalJSON unmarshal to json +func (updateNotificationGroup *UpdateNotificationGroup) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + NotificationGroupID int32 `json:"notification_group_id"` // Unique notification group identifier + ChatID int64 `json:"chat_id"` // Identifier of a chat to which all notifications in the group belong + NotificationSettingsChatID int64 `json:"notification_settings_chat_id"` // Chat identifier, which notification settings must be applied to the added notifications + IsSilent bool `json:"is_silent"` // True, if the notifications should be shown without sound + TotalCount int32 `json:"total_count"` // Total number of unread notifications in the group, can be bigger than number of active notifications + AddedNotifications []Notification `json:"added_notifications"` // List of added group notifications, sorted by notification ID + RemovedNotificationIDs []int32 `json:"removed_notification_ids"` // Identifiers of removed group notifications, sorted by notification ID + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateNotificationGroup.tdCommon = tempObj.tdCommon + updateNotificationGroup.NotificationGroupID = tempObj.NotificationGroupID + updateNotificationGroup.ChatID = tempObj.ChatID + updateNotificationGroup.NotificationSettingsChatID = tempObj.NotificationSettingsChatID + updateNotificationGroup.IsSilent = tempObj.IsSilent + updateNotificationGroup.TotalCount = tempObj.TotalCount + updateNotificationGroup.AddedNotifications = tempObj.AddedNotifications + updateNotificationGroup.RemovedNotificationIDs = tempObj.RemovedNotificationIDs + + fieldType, _ := unmarshalNotificationGroupType(objMap["type"]) + updateNotificationGroup.Type = fieldType + + return nil +} + +// GetUpdateEnum return the enum type of this object +func (updateNotificationGroup *UpdateNotificationGroup) GetUpdateEnum() UpdateEnum { + return UpdateNotificationGroupType +} + +// UpdateActiveNotifications Contains active notifications that was shown on previous application launches. This update is sent only if the message database is used. In that case it comes once before any updateNotification and updateNotificationGroup update +type UpdateActiveNotifications struct { + tdCommon + Groups []NotificationGroup `json:"groups"` // Lists of active notification groups +} + +// MessageType return the string telegram-type of UpdateActiveNotifications +func (updateActiveNotifications *UpdateActiveNotifications) MessageType() string { + return "updateActiveNotifications" +} + +// NewUpdateActiveNotifications creates a new UpdateActiveNotifications +// +// @param groups Lists of active notification groups +func NewUpdateActiveNotifications(groups []NotificationGroup) *UpdateActiveNotifications { + updateActiveNotificationsTemp := UpdateActiveNotifications{ + tdCommon: tdCommon{Type: "updateActiveNotifications"}, + Groups: groups, + } + + return &updateActiveNotificationsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateActiveNotifications *UpdateActiveNotifications) GetUpdateEnum() UpdateEnum { + return UpdateActiveNotificationsType +} + +// UpdateHavePendingNotifications Describes whether there are some pending notification updates. Can be used to prevent application from killing, while there are some pending notifications +type UpdateHavePendingNotifications struct { + tdCommon + HaveDelayedNotifications bool `json:"have_delayed_notifications"` // True, if there are some delayed notification updates, which will be sent soon + HaveUnreceivedNotifications bool `json:"have_unreceived_notifications"` // True, if there can be some yet unreceived notifications, which are being fetched from the server +} + +// MessageType return the string telegram-type of UpdateHavePendingNotifications +func (updateHavePendingNotifications *UpdateHavePendingNotifications) MessageType() string { + return "updateHavePendingNotifications" +} + +// NewUpdateHavePendingNotifications creates a new UpdateHavePendingNotifications +// +// @param haveDelayedNotifications True, if there are some delayed notification updates, which will be sent soon +// @param haveUnreceivedNotifications True, if there can be some yet unreceived notifications, which are being fetched from the server +func NewUpdateHavePendingNotifications(haveDelayedNotifications bool, haveUnreceivedNotifications bool) *UpdateHavePendingNotifications { + updateHavePendingNotificationsTemp := UpdateHavePendingNotifications{ + tdCommon: tdCommon{Type: "updateHavePendingNotifications"}, + HaveDelayedNotifications: haveDelayedNotifications, + HaveUnreceivedNotifications: haveUnreceivedNotifications, + } + + return &updateHavePendingNotificationsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateHavePendingNotifications *UpdateHavePendingNotifications) GetUpdateEnum() UpdateEnum { + return UpdateHavePendingNotificationsType +} + +// 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 inaccessible) + 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 inaccessible) +// @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 + MessageThreadID int64 `json:"message_thread_id"` // If not 0, a message thread identifier in which the action was performed + UserID int64 `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 messageThreadID If not 0, a message thread identifier in which the action was performed +// @param userID Identifier of a user performing an action +// @param action The action description +func NewUpdateUserChatAction(chatID int64, messageThreadID int64, userID int64, action ChatAction) *UpdateUserChatAction { + updateUserChatActionTemp := UpdateUserChatAction{ + tdCommon: tdCommon{Type: "updateUserChatAction"}, + ChatID: chatID, + MessageThreadID: messageThreadID, + 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 + MessageThreadID int64 `json:"message_thread_id"` // If not 0, a message thread identifier in which the action was performed + UserID int64 `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.MessageThreadID = tempObj.MessageThreadID + 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 int64 `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 int64, 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 int64 `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 application +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 application +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 application +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 application +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 int64 `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 int64, 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 int64 `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 int64, 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 int64 `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 int64, 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 application 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 application +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 application +} + +// 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 application +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 +} + +// UpdateGroupCall Information about a group call was updated +type UpdateGroupCall struct { + tdCommon + GroupCall *GroupCall `json:"group_call"` // New data about a group call +} + +// MessageType return the string telegram-type of UpdateGroupCall +func (updateGroupCall *UpdateGroupCall) MessageType() string { + return "updateGroupCall" +} + +// NewUpdateGroupCall creates a new UpdateGroupCall +// +// @param groupCall New data about a group call +func NewUpdateGroupCall(groupCall *GroupCall) *UpdateGroupCall { + updateGroupCallTemp := UpdateGroupCall{ + tdCommon: tdCommon{Type: "updateGroupCall"}, + GroupCall: groupCall, + } + + return &updateGroupCallTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateGroupCall *UpdateGroupCall) GetUpdateEnum() UpdateEnum { + return UpdateGroupCallType +} + +// UpdateGroupCallParticipant Information about a group call participant was changed. The updates are sent only after the group call is received through getGroupCall and only if the call is joined or being joined +type UpdateGroupCallParticipant struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Identifier of group call + Participant *GroupCallParticipant `json:"participant"` // New data about a participant +} + +// MessageType return the string telegram-type of UpdateGroupCallParticipant +func (updateGroupCallParticipant *UpdateGroupCallParticipant) MessageType() string { + return "updateGroupCallParticipant" +} + +// NewUpdateGroupCallParticipant creates a new UpdateGroupCallParticipant +// +// @param groupCallID Identifier of group call +// @param participant New data about a participant +func NewUpdateGroupCallParticipant(groupCallID int32, participant *GroupCallParticipant) *UpdateGroupCallParticipant { + updateGroupCallParticipantTemp := UpdateGroupCallParticipant{ + tdCommon: tdCommon{Type: "updateGroupCallParticipant"}, + GroupCallID: groupCallID, + Participant: participant, + } + + return &updateGroupCallParticipantTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateGroupCallParticipant *UpdateGroupCallParticipant) GetUpdateEnum() UpdateEnum { + return UpdateGroupCallParticipantType +} + +// UpdateNewCallSignalingData New call signaling data arrived +type UpdateNewCallSignalingData struct { + tdCommon + CallID int32 `json:"call_id"` // The call identifier + Data []byte `json:"data"` // The data +} + +// MessageType return the string telegram-type of UpdateNewCallSignalingData +func (updateNewCallSignalingData *UpdateNewCallSignalingData) MessageType() string { + return "updateNewCallSignalingData" +} + +// NewUpdateNewCallSignalingData creates a new UpdateNewCallSignalingData +// +// @param callID The call identifier +// @param data The data +func NewUpdateNewCallSignalingData(callID int32, data []byte) *UpdateNewCallSignalingData { + updateNewCallSignalingDataTemp := UpdateNewCallSignalingData{ + tdCommon: tdCommon{Type: "updateNewCallSignalingData"}, + CallID: callID, + Data: data, + } + + return &updateNewCallSignalingDataTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateNewCallSignalingData *UpdateNewCallSignalingData) GetUpdateEnum() UpdateEnum { + return UpdateNewCallSignalingDataType +} + +// 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 in a chat list has changed. This update is sent only if the message database is used +type UpdateUnreadMessageCount struct { + tdCommon + ChatList ChatList `json:"chat_list"` // The chat list with changed number of unread messages + 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 chatList The chat list with changed number of unread messages +// @param unreadCount Total number of unread messages +// @param unreadUnmutedCount Total number of unread messages in unmuted chats +func NewUpdateUnreadMessageCount(chatList ChatList, unreadCount int32, unreadUnmutedCount int32) *UpdateUnreadMessageCount { + updateUnreadMessageCountTemp := UpdateUnreadMessageCount{ + tdCommon: tdCommon{Type: "updateUnreadMessageCount"}, + ChatList: chatList, + UnreadCount: unreadCount, + UnreadUnmutedCount: unreadUnmutedCount, + } + + return &updateUnreadMessageCountTemp +} + +// UnmarshalJSON unmarshal to json +func (updateUnreadMessageCount *UpdateUnreadMessageCount) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := 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 + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateUnreadMessageCount.tdCommon = tempObj.tdCommon + updateUnreadMessageCount.UnreadCount = tempObj.UnreadCount + updateUnreadMessageCount.UnreadUnmutedCount = tempObj.UnreadUnmutedCount + + fieldChatList, _ := unmarshalChatList(objMap["chat_list"]) + updateUnreadMessageCount.ChatList = fieldChatList + + return nil +} + +// 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 the message database is used +type UpdateUnreadChatCount struct { + tdCommon + ChatList ChatList `json:"chat_list"` // The chat list with changed number of unread messages + TotalCount int32 `json:"total_count"` // Approximate total number of chats in the chat list + 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 chatList The chat list with changed number of unread messages +// @param totalCount Approximate total number of chats in the chat list +// @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(chatList ChatList, totalCount int32, unreadCount int32, unreadUnmutedCount int32, markedAsUnreadCount int32, markedAsUnreadUnmutedCount int32) *UpdateUnreadChatCount { + updateUnreadChatCountTemp := UpdateUnreadChatCount{ + tdCommon: tdCommon{Type: "updateUnreadChatCount"}, + ChatList: chatList, + TotalCount: totalCount, + UnreadCount: unreadCount, + UnreadUnmutedCount: unreadUnmutedCount, + MarkedAsUnreadCount: markedAsUnreadCount, + MarkedAsUnreadUnmutedCount: markedAsUnreadUnmutedCount, + } + + return &updateUnreadChatCountTemp +} + +// UnmarshalJSON unmarshal to json +func (updateUnreadChatCount *UpdateUnreadChatCount) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total number of chats in the chat list + 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 + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateUnreadChatCount.tdCommon = tempObj.tdCommon + updateUnreadChatCount.TotalCount = tempObj.TotalCount + updateUnreadChatCount.UnreadCount = tempObj.UnreadCount + updateUnreadChatCount.UnreadUnmutedCount = tempObj.UnreadUnmutedCount + updateUnreadChatCount.MarkedAsUnreadCount = tempObj.MarkedAsUnreadCount + updateUnreadChatCount.MarkedAsUnreadUnmutedCount = tempObj.MarkedAsUnreadUnmutedCount + + fieldChatList, _ := unmarshalChatList(objMap["chat_list"]) + updateUnreadChatCount.ChatList = fieldChatList + + return nil +} + +// 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 +} + +// UpdateStickerSet A sticker set has changed +type UpdateStickerSet struct { + tdCommon + StickerSet *StickerSet `json:"sticker_set"` // The sticker set +} + +// MessageType return the string telegram-type of UpdateStickerSet +func (updateStickerSet *UpdateStickerSet) MessageType() string { + return "updateStickerSet" +} + +// NewUpdateStickerSet creates a new UpdateStickerSet +// +// @param stickerSet The sticker set +func NewUpdateStickerSet(stickerSet *StickerSet) *UpdateStickerSet { + updateStickerSetTemp := UpdateStickerSet{ + tdCommon: tdCommon{Type: "updateStickerSet"}, + StickerSet: stickerSet, + } + + return &updateStickerSetTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateStickerSet *UpdateStickerSet) GetUpdateEnum() UpdateEnum { + return UpdateStickerSetType +} + +// 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 prefix of the list of trending sticker sets with the newest 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 prefix of the list of trending sticker sets with the newest 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 +} + +// UpdateSelectedBackground The selected background has changed +type UpdateSelectedBackground struct { + tdCommon + ForDarkTheme bool `json:"for_dark_theme"` // True, if background for dark theme has changed + Background *Background `json:"background"` // The new selected background; may be null +} + +// MessageType return the string telegram-type of UpdateSelectedBackground +func (updateSelectedBackground *UpdateSelectedBackground) MessageType() string { + return "updateSelectedBackground" +} + +// NewUpdateSelectedBackground creates a new UpdateSelectedBackground +// +// @param forDarkTheme True, if background for dark theme has changed +// @param background The new selected background; may be null +func NewUpdateSelectedBackground(forDarkTheme bool, background *Background) *UpdateSelectedBackground { + updateSelectedBackgroundTemp := UpdateSelectedBackground{ + tdCommon: tdCommon{Type: "updateSelectedBackground"}, + ForDarkTheme: forDarkTheme, + Background: background, + } + + return &updateSelectedBackgroundTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateSelectedBackground *UpdateSelectedBackground) GetUpdateEnum() UpdateEnum { + return UpdateSelectedBackgroundType +} + +// UpdateChatThemes The list of available chat themes has changed +type UpdateChatThemes struct { + tdCommon + ChatThemes []ChatTheme `json:"chat_themes"` // The new list of chat themes +} + +// MessageType return the string telegram-type of UpdateChatThemes +func (updateChatThemes *UpdateChatThemes) MessageType() string { + return "updateChatThemes" +} + +// NewUpdateChatThemes creates a new UpdateChatThemes +// +// @param chatThemes The new list of chat themes +func NewUpdateChatThemes(chatThemes []ChatTheme) *UpdateChatThemes { + updateChatThemesTemp := UpdateChatThemes{ + tdCommon: tdCommon{Type: "updateChatThemes"}, + ChatThemes: chatThemes, + } + + return &updateChatThemesTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatThemes *UpdateChatThemes) GetUpdateEnum() UpdateEnum { + return UpdateChatThemesType +} + +// 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. This update must be used only to show a human-readable description of the connection state +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 +} + +// UpdateUsersNearby The list of users nearby has changed. The update is guaranteed to be sent only 60 seconds after a successful searchChatsNearby request +type UpdateUsersNearby struct { + tdCommon + UsersNearby []ChatNearby `json:"users_nearby"` // The new list of users nearby +} + +// MessageType return the string telegram-type of UpdateUsersNearby +func (updateUsersNearby *UpdateUsersNearby) MessageType() string { + return "updateUsersNearby" +} + +// NewUpdateUsersNearby creates a new UpdateUsersNearby +// +// @param usersNearby The new list of users nearby +func NewUpdateUsersNearby(usersNearby []ChatNearby) *UpdateUsersNearby { + updateUsersNearbyTemp := UpdateUsersNearby{ + tdCommon: tdCommon{Type: "updateUsersNearby"}, + UsersNearby: usersNearby, + } + + return &updateUsersNearbyTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateUsersNearby *UpdateUsersNearby) GetUpdateEnum() UpdateEnum { + return UpdateUsersNearbyType +} + +// UpdateDiceEmojis The list of supported dice emojis has changed +type UpdateDiceEmojis struct { + tdCommon + Emojis []string `json:"emojis"` // The new list of supported dice emojis +} + +// MessageType return the string telegram-type of UpdateDiceEmojis +func (updateDiceEmojis *UpdateDiceEmojis) MessageType() string { + return "updateDiceEmojis" +} + +// NewUpdateDiceEmojis creates a new UpdateDiceEmojis +// +// @param emojis The new list of supported dice emojis +func NewUpdateDiceEmojis(emojis []string) *UpdateDiceEmojis { + updateDiceEmojisTemp := UpdateDiceEmojis{ + tdCommon: tdCommon{Type: "updateDiceEmojis"}, + Emojis: emojis, + } + + return &updateDiceEmojisTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateDiceEmojis *UpdateDiceEmojis) GetUpdateEnum() UpdateEnum { + return UpdateDiceEmojisType +} + +// UpdateAnimationSearchParameters The parameters of animation search through GetOption("animation_search_bot_username") bot has changed +type UpdateAnimationSearchParameters struct { + tdCommon + Provider string `json:"provider"` // Name of the animation search provider + Emojis []string `json:"emojis"` // The new list of emojis suggested for searching +} + +// MessageType return the string telegram-type of UpdateAnimationSearchParameters +func (updateAnimationSearchParameters *UpdateAnimationSearchParameters) MessageType() string { + return "updateAnimationSearchParameters" +} + +// NewUpdateAnimationSearchParameters creates a new UpdateAnimationSearchParameters +// +// @param provider Name of the animation search provider +// @param emojis The new list of emojis suggested for searching +func NewUpdateAnimationSearchParameters(provider string, emojis []string) *UpdateAnimationSearchParameters { + updateAnimationSearchParametersTemp := UpdateAnimationSearchParameters{ + tdCommon: tdCommon{Type: "updateAnimationSearchParameters"}, + Provider: provider, + Emojis: emojis, + } + + return &updateAnimationSearchParametersTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateAnimationSearchParameters *UpdateAnimationSearchParameters) GetUpdateEnum() UpdateEnum { + return UpdateAnimationSearchParametersType +} + +// UpdateSuggestedActions The list of suggested to the user actions has changed +type UpdateSuggestedActions struct { + tdCommon + AddedActions []SuggestedAction `json:"added_actions"` // Added suggested actions + RemovedActions []SuggestedAction `json:"removed_actions"` // Removed suggested actions +} + +// MessageType return the string telegram-type of UpdateSuggestedActions +func (updateSuggestedActions *UpdateSuggestedActions) MessageType() string { + return "updateSuggestedActions" +} + +// NewUpdateSuggestedActions creates a new UpdateSuggestedActions +// +// @param addedActions Added suggested actions +// @param removedActions Removed suggested actions +func NewUpdateSuggestedActions(addedActions []SuggestedAction, removedActions []SuggestedAction) *UpdateSuggestedActions { + updateSuggestedActionsTemp := UpdateSuggestedActions{ + tdCommon: tdCommon{Type: "updateSuggestedActions"}, + AddedActions: addedActions, + RemovedActions: removedActions, + } + + return &updateSuggestedActionsTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateSuggestedActions *UpdateSuggestedActions) GetUpdateEnum() UpdateEnum { + return UpdateSuggestedActionsType +} + +// UpdateNewInlineQuery A new incoming inline query; for bots only +type UpdateNewInlineQuery struct { + tdCommon + ID JSONInt64 `json:"id"` // Unique query identifier + SenderUserID int64 `json:"sender_user_id"` // Identifier of the user who sent the query + UserLocation *Location `json:"user_location"` // User location; may be null + ChatType ChatType `json:"chat_type"` // Contains information about the type of the chat, from which the query originated; may be null if unknown + 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; may be null +// @param chatType Contains information about the type of the chat, from which the query originated; may be null if unknown +// @param query Text of the query +// @param offset Offset of the first entry to return +func NewUpdateNewInlineQuery(iD JSONInt64, senderUserID int64, userLocation *Location, chatType ChatType, query string, offset string) *UpdateNewInlineQuery { + updateNewInlineQueryTemp := UpdateNewInlineQuery{ + tdCommon: tdCommon{Type: "updateNewInlineQuery"}, + ID: iD, + SenderUserID: senderUserID, + UserLocation: userLocation, + ChatType: chatType, + Query: query, + Offset: offset, + } + + return &updateNewInlineQueryTemp +} + +// UnmarshalJSON unmarshal to json +func (updateNewInlineQuery *UpdateNewInlineQuery) 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 int64 `json:"sender_user_id"` // Identifier of the user who sent the query + UserLocation *Location `json:"user_location"` // User location; may be null + Query string `json:"query"` // Text of the query + Offset string `json:"offset"` // Offset of the first entry to return + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + updateNewInlineQuery.tdCommon = tempObj.tdCommon + updateNewInlineQuery.ID = tempObj.ID + updateNewInlineQuery.SenderUserID = tempObj.SenderUserID + updateNewInlineQuery.UserLocation = tempObj.UserLocation + updateNewInlineQuery.Query = tempObj.Query + updateNewInlineQuery.Offset = tempObj.Offset + + fieldChatType, _ := unmarshalChatType(objMap["chat_type"]) + updateNewInlineQuery.ChatType = fieldChatType + + return nil +} + +// 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 int64 `json:"sender_user_id"` // Identifier of the user who sent the query + UserLocation *Location `json:"user_location"` // User location; 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; 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 int64, 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 int64 `json:"sender_user_id"` // Identifier of the user who sent the query + ChatID int64 `json:"chat_id"` // Identifier of the chat where 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 where 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 int64, 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 int64 `json:"sender_user_id"` // Identifier of the user who sent the query + ChatID int64 `json:"chat_id"` // Identifier of the chat where 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 int64 `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 int64, 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 int64 `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 int64 `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 int64, 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 int64 `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 smallest units 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 smallest units 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 int64, 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 +} + +// UpdatePoll A poll was updated; for bots only +type UpdatePoll struct { + tdCommon + Poll *Poll `json:"poll"` // New data about the poll +} + +// MessageType return the string telegram-type of UpdatePoll +func (updatePoll *UpdatePoll) MessageType() string { + return "updatePoll" +} + +// NewUpdatePoll creates a new UpdatePoll +// +// @param poll New data about the poll +func NewUpdatePoll(poll *Poll) *UpdatePoll { + updatePollTemp := UpdatePoll{ + tdCommon: tdCommon{Type: "updatePoll"}, + Poll: poll, + } + + return &updatePollTemp +} + +// GetUpdateEnum return the enum type of this object +func (updatePoll *UpdatePoll) GetUpdateEnum() UpdateEnum { + return UpdatePollType +} + +// UpdatePollAnswer A user changed the answer to a poll; for bots only +type UpdatePollAnswer struct { + tdCommon + PollID JSONInt64 `json:"poll_id"` // Unique poll identifier + UserID int64 `json:"user_id"` // The user, who changed the answer to the poll + OptionIDs []int32 `json:"option_ids"` // 0-based identifiers of answer options, chosen by the user +} + +// MessageType return the string telegram-type of UpdatePollAnswer +func (updatePollAnswer *UpdatePollAnswer) MessageType() string { + return "updatePollAnswer" +} + +// NewUpdatePollAnswer creates a new UpdatePollAnswer +// +// @param pollID Unique poll identifier +// @param userID The user, who changed the answer to the poll +// @param optionIDs 0-based identifiers of answer options, chosen by the user +func NewUpdatePollAnswer(pollID JSONInt64, userID int64, optionIDs []int32) *UpdatePollAnswer { + updatePollAnswerTemp := UpdatePollAnswer{ + tdCommon: tdCommon{Type: "updatePollAnswer"}, + PollID: pollID, + UserID: userID, + OptionIDs: optionIDs, + } + + return &updatePollAnswerTemp +} + +// GetUpdateEnum return the enum type of this object +func (updatePollAnswer *UpdatePollAnswer) GetUpdateEnum() UpdateEnum { + return UpdatePollAnswerType +} + +// UpdateChatMember User rights changed in a chat; for bots only +type UpdateChatMember struct { + tdCommon + ChatID int64 `json:"chat_id"` // Chat identifier + ActorUserID int64 `json:"actor_user_id"` // Identifier of the user, changing the rights + Date int32 `json:"date"` // Point in time (Unix timestamp) when the user rights was changed + InviteLink *ChatInviteLink `json:"invite_link"` // If user has joined the chat using an invite link, the invite link; may be null + OldChatMember *ChatMember `json:"old_chat_member"` // Previous chat member + NewChatMember *ChatMember `json:"new_chat_member"` // New chat member +} + +// MessageType return the string telegram-type of UpdateChatMember +func (updateChatMember *UpdateChatMember) MessageType() string { + return "updateChatMember" +} + +// NewUpdateChatMember creates a new UpdateChatMember +// +// @param chatID Chat identifier +// @param actorUserID Identifier of the user, changing the rights +// @param date Point in time (Unix timestamp) when the user rights was changed +// @param inviteLink If user has joined the chat using an invite link, the invite link; may be null +// @param oldChatMember Previous chat member +// @param newChatMember New chat member +func NewUpdateChatMember(chatID int64, actorUserID int64, date int32, inviteLink *ChatInviteLink, oldChatMember *ChatMember, newChatMember *ChatMember) *UpdateChatMember { + updateChatMemberTemp := UpdateChatMember{ + tdCommon: tdCommon{Type: "updateChatMember"}, + ChatID: chatID, + ActorUserID: actorUserID, + Date: date, + InviteLink: inviteLink, + OldChatMember: oldChatMember, + NewChatMember: newChatMember, + } + + return &updateChatMemberTemp +} + +// GetUpdateEnum return the enum type of this object +func (updateChatMember *UpdateChatMember) GetUpdateEnum() UpdateEnum { + return UpdateChatMemberType +} diff --git a/tdlib/updates.go b/tdlib/updates.go new file mode 100644 index 0000000..feb6926 --- /dev/null +++ b/tdlib/updates.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Updates Contains a list of updates +type Updates struct { + tdCommon + Updates []Update `json:"updates"` // List of updates +} + +// MessageType return the string telegram-type of Updates +func (updates *Updates) MessageType() string { + return "updates" +} + +// NewUpdates creates a new Updates +// +// @param updates List of updates +func NewUpdates(updates []Update) *Updates { + updatesTemp := Updates{ + tdCommon: tdCommon{Type: "updates"}, + Updates: updates, + } + + return &updatesTemp +} diff --git a/tdlib/user.go b/tdlib/user.go new file mode 100644 index 0000000..3546a73 --- /dev/null +++ b/tdlib/user.go @@ -0,0 +1,134 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// User Represents a user +type User struct { + tdCommon + ID int64 `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 + IsContact bool `json:"is_contact"` // The user is a contact of the current user + IsMutualContact bool `json:"is_mutual_contact"` // The user is a contact of the current user and the current user is a contact of the user + IsVerified bool `json:"is_verified"` // True, if the user is verified + IsSupport bool `json:"is_support"` // True, if the user is Telegram support account + RestrictionReason string `json:"restriction_reason"` // If non-empty, it contains a human-readable description of the reason why access to this user must be restricted + IsScam bool `json:"is_scam"` // True, if many users reported this user as a scam + IsFake bool `json:"is_fake"` // True, if many users reported this user as a fake account + 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 isContact The user is a contact of the current user +// @param isMutualContact The user is a contact of the current user and the current user is a contact of the user +// @param isVerified True, if the user is verified +// @param isSupport True, if the user is Telegram support account +// @param restrictionReason If non-empty, it contains a human-readable description of the reason why access to this user must be restricted +// @param isScam True, if many users reported this user as a scam +// @param isFake True, if many users reported this user as a fake account +// @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 int64, firstName string, lastName string, username string, phoneNumber string, status UserStatus, profilePhoto *ProfilePhoto, isContact bool, isMutualContact bool, isVerified bool, isSupport bool, restrictionReason string, isScam bool, isFake bool, 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, + IsContact: isContact, + IsMutualContact: isMutualContact, + IsVerified: isVerified, + IsSupport: isSupport, + RestrictionReason: restrictionReason, + IsScam: isScam, + IsFake: isFake, + 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 int64 `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 + IsContact bool `json:"is_contact"` // The user is a contact of the current user + IsMutualContact bool `json:"is_mutual_contact"` // The user is a contact of the current user and the current user is a contact of the user + IsVerified bool `json:"is_verified"` // True, if the user is verified + IsSupport bool `json:"is_support"` // True, if the user is Telegram support account + RestrictionReason string `json:"restriction_reason"` // If non-empty, it contains a human-readable description of the reason why access to this user must be restricted + IsScam bool `json:"is_scam"` // True, if many users reported this user as a scam + IsFake bool `json:"is_fake"` // True, if many users reported this user as a fake account + 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.IsContact = tempObj.IsContact + user.IsMutualContact = tempObj.IsMutualContact + user.IsVerified = tempObj.IsVerified + user.IsSupport = tempObj.IsSupport + user.RestrictionReason = tempObj.RestrictionReason + user.IsScam = tempObj.IsScam + user.IsFake = tempObj.IsFake + user.HaveAccess = tempObj.HaveAccess + user.LanguageCode = tempObj.LanguageCode + + fieldStatus, _ := unmarshalUserStatus(objMap["status"]) + user.Status = fieldStatus + + fieldType, _ := unmarshalUserType(objMap["type"]) + user.Type = fieldType + + return nil +} diff --git a/tdlib/userFullInfo.go b/tdlib/userFullInfo.go new file mode 100644 index 0000000..e87de2e --- /dev/null +++ b/tdlib/userFullInfo.go @@ -0,0 +1,56 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// UserFullInfo Contains full information about a user +type UserFullInfo struct { + tdCommon + Photo *ChatPhoto `json:"photo"` // User profile photo; may be null + IsBlocked bool `json:"is_blocked"` // True, if the user is blocked by the current user + CanBeCalled bool `json:"can_be_called"` // True, if the user can be called + SupportsVideoCalls bool `json:"supports_video_calls"` // True, if a video call can be created with the user + HasPrivateCalls bool `json:"has_private_calls"` // True, if the user can't be called due to their privacy settings + NeedPhoneNumberPrivacyException bool `json:"need_phone_number_privacy_exception"` // True, if the current user needs to explicitly allow to share their phone number with the user when the method addContact is used + Bio string `json:"bio"` // A short user bio + ShareText string `json:"share_text"` // For bots, the text that is shown on the bot's profile page and is sent together with the link when users share the bot + Description string `json:"description"` // For bots, the text shown in the chat with the bot if the chat is empty + 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 + Commands []BotCommand `json:"commands"` // For bots, list of the bot commands +} + +// MessageType return the string telegram-type of UserFullInfo +func (userFullInfo *UserFullInfo) MessageType() string { + return "userFullInfo" +} + +// NewUserFullInfo creates a new UserFullInfo +// +// @param photo User profile photo; may be null +// @param isBlocked True, if the user is blocked by the current user +// @param canBeCalled True, if the user can be called +// @param supportsVideoCalls True, if a video call can be created with the user +// @param hasPrivateCalls True, if the user can't be called due to their privacy settings +// @param needPhoneNumberPrivacyException True, if the current user needs to explicitly allow to share their phone number with the user when the method addContact is used +// @param bio A short user bio +// @param shareText For bots, the text that is shown on the bot's profile page and is sent together with the link when users share the bot +// @param description For bots, the text shown in the chat with the bot if the chat is empty +// @param groupInCommonCount Number of group chats where both the other user and the current user are a member; 0 for the current user +// @param commands For bots, list of the bot commands +func NewUserFullInfo(photo *ChatPhoto, isBlocked bool, canBeCalled bool, supportsVideoCalls bool, hasPrivateCalls bool, needPhoneNumberPrivacyException bool, bio string, shareText string, description string, groupInCommonCount int32, commands []BotCommand) *UserFullInfo { + userFullInfoTemp := UserFullInfo{ + tdCommon: tdCommon{Type: "userFullInfo"}, + Photo: photo, + IsBlocked: isBlocked, + CanBeCalled: canBeCalled, + SupportsVideoCalls: supportsVideoCalls, + HasPrivateCalls: hasPrivateCalls, + NeedPhoneNumberPrivacyException: needPhoneNumberPrivacyException, + Bio: bio, + ShareText: shareText, + Description: description, + GroupInCommonCount: groupInCommonCount, + Commands: commands, + } + + return &userFullInfoTemp +} diff --git a/tdlib/userPrivacySetting.go b/tdlib/userPrivacySetting.go new file mode 100644 index 0000000..5efd38a --- /dev/null +++ b/tdlib/userPrivacySetting.go @@ -0,0 +1,285 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// UserPrivacySetting Describes available user privacy settings +type UserPrivacySetting interface { + GetUserPrivacySettingEnum() UserPrivacySettingEnum +} + +// UserPrivacySettingEnum Alias for abstract UserPrivacySetting 'Sub-Classes', used as constant-enum here +type UserPrivacySettingEnum string + +// UserPrivacySetting enums +const ( + UserPrivacySettingShowStatusType UserPrivacySettingEnum = "userPrivacySettingShowStatus" + UserPrivacySettingShowProfilePhotoType UserPrivacySettingEnum = "userPrivacySettingShowProfilePhoto" + UserPrivacySettingShowLinkInForwardedMessagesType UserPrivacySettingEnum = "userPrivacySettingShowLinkInForwardedMessages" + UserPrivacySettingShowPhoneNumberType UserPrivacySettingEnum = "userPrivacySettingShowPhoneNumber" + UserPrivacySettingAllowChatInvitesType UserPrivacySettingEnum = "userPrivacySettingAllowChatInvites" + UserPrivacySettingAllowCallsType UserPrivacySettingEnum = "userPrivacySettingAllowCalls" + UserPrivacySettingAllowPeerToPeerCallsType UserPrivacySettingEnum = "userPrivacySettingAllowPeerToPeerCalls" + UserPrivacySettingAllowFindingByPhoneNumberType UserPrivacySettingEnum = "userPrivacySettingAllowFindingByPhoneNumber" +) + +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 UserPrivacySettingShowProfilePhotoType: + var userPrivacySettingShowProfilePhoto UserPrivacySettingShowProfilePhoto + err := json.Unmarshal(*rawMsg, &userPrivacySettingShowProfilePhoto) + return &userPrivacySettingShowProfilePhoto, err + + case UserPrivacySettingShowLinkInForwardedMessagesType: + var userPrivacySettingShowLinkInForwardedMessages UserPrivacySettingShowLinkInForwardedMessages + err := json.Unmarshal(*rawMsg, &userPrivacySettingShowLinkInForwardedMessages) + return &userPrivacySettingShowLinkInForwardedMessages, err + + case UserPrivacySettingShowPhoneNumberType: + var userPrivacySettingShowPhoneNumber UserPrivacySettingShowPhoneNumber + err := json.Unmarshal(*rawMsg, &userPrivacySettingShowPhoneNumber) + return &userPrivacySettingShowPhoneNumber, 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 + + case UserPrivacySettingAllowPeerToPeerCallsType: + var userPrivacySettingAllowPeerToPeerCalls UserPrivacySettingAllowPeerToPeerCalls + err := json.Unmarshal(*rawMsg, &userPrivacySettingAllowPeerToPeerCalls) + return &userPrivacySettingAllowPeerToPeerCalls, err + + case UserPrivacySettingAllowFindingByPhoneNumberType: + var userPrivacySettingAllowFindingByPhoneNumber UserPrivacySettingAllowFindingByPhoneNumber + err := json.Unmarshal(*rawMsg, &userPrivacySettingAllowFindingByPhoneNumber) + return &userPrivacySettingAllowFindingByPhoneNumber, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 +} + +// UserPrivacySettingShowProfilePhoto A privacy setting for managing whether the user's profile photo is visible +type UserPrivacySettingShowProfilePhoto struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingShowProfilePhoto +func (userPrivacySettingShowProfilePhoto *UserPrivacySettingShowProfilePhoto) MessageType() string { + return "userPrivacySettingShowProfilePhoto" +} + +// NewUserPrivacySettingShowProfilePhoto creates a new UserPrivacySettingShowProfilePhoto +// +func NewUserPrivacySettingShowProfilePhoto() *UserPrivacySettingShowProfilePhoto { + userPrivacySettingShowProfilePhotoTemp := UserPrivacySettingShowProfilePhoto{ + tdCommon: tdCommon{Type: "userPrivacySettingShowProfilePhoto"}, + } + + return &userPrivacySettingShowProfilePhotoTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingShowProfilePhoto *UserPrivacySettingShowProfilePhoto) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingShowProfilePhotoType +} + +// UserPrivacySettingShowLinkInForwardedMessages A privacy setting for managing whether a link to the user's account is included in forwarded messages +type UserPrivacySettingShowLinkInForwardedMessages struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingShowLinkInForwardedMessages +func (userPrivacySettingShowLinkInForwardedMessages *UserPrivacySettingShowLinkInForwardedMessages) MessageType() string { + return "userPrivacySettingShowLinkInForwardedMessages" +} + +// NewUserPrivacySettingShowLinkInForwardedMessages creates a new UserPrivacySettingShowLinkInForwardedMessages +// +func NewUserPrivacySettingShowLinkInForwardedMessages() *UserPrivacySettingShowLinkInForwardedMessages { + userPrivacySettingShowLinkInForwardedMessagesTemp := UserPrivacySettingShowLinkInForwardedMessages{ + tdCommon: tdCommon{Type: "userPrivacySettingShowLinkInForwardedMessages"}, + } + + return &userPrivacySettingShowLinkInForwardedMessagesTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingShowLinkInForwardedMessages *UserPrivacySettingShowLinkInForwardedMessages) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingShowLinkInForwardedMessagesType +} + +// UserPrivacySettingShowPhoneNumber A privacy setting for managing whether the user's phone number is visible +type UserPrivacySettingShowPhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingShowPhoneNumber +func (userPrivacySettingShowPhoneNumber *UserPrivacySettingShowPhoneNumber) MessageType() string { + return "userPrivacySettingShowPhoneNumber" +} + +// NewUserPrivacySettingShowPhoneNumber creates a new UserPrivacySettingShowPhoneNumber +// +func NewUserPrivacySettingShowPhoneNumber() *UserPrivacySettingShowPhoneNumber { + userPrivacySettingShowPhoneNumberTemp := UserPrivacySettingShowPhoneNumber{ + tdCommon: tdCommon{Type: "userPrivacySettingShowPhoneNumber"}, + } + + return &userPrivacySettingShowPhoneNumberTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingShowPhoneNumber *UserPrivacySettingShowPhoneNumber) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingShowPhoneNumberType +} + +// 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 +} + +// UserPrivacySettingAllowPeerToPeerCalls A privacy setting for managing whether peer-to-peer connections can be used for calls +type UserPrivacySettingAllowPeerToPeerCalls struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingAllowPeerToPeerCalls +func (userPrivacySettingAllowPeerToPeerCalls *UserPrivacySettingAllowPeerToPeerCalls) MessageType() string { + return "userPrivacySettingAllowPeerToPeerCalls" +} + +// NewUserPrivacySettingAllowPeerToPeerCalls creates a new UserPrivacySettingAllowPeerToPeerCalls +// +func NewUserPrivacySettingAllowPeerToPeerCalls() *UserPrivacySettingAllowPeerToPeerCalls { + userPrivacySettingAllowPeerToPeerCallsTemp := UserPrivacySettingAllowPeerToPeerCalls{ + tdCommon: tdCommon{Type: "userPrivacySettingAllowPeerToPeerCalls"}, + } + + return &userPrivacySettingAllowPeerToPeerCallsTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingAllowPeerToPeerCalls *UserPrivacySettingAllowPeerToPeerCalls) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingAllowPeerToPeerCallsType +} + +// UserPrivacySettingAllowFindingByPhoneNumber A privacy setting for managing whether the user can be found by their phone number. Checked only if the phone number is not known to the other user. Can be set only to "Allow contacts" or "Allow all" +type UserPrivacySettingAllowFindingByPhoneNumber struct { + tdCommon +} + +// MessageType return the string telegram-type of UserPrivacySettingAllowFindingByPhoneNumber +func (userPrivacySettingAllowFindingByPhoneNumber *UserPrivacySettingAllowFindingByPhoneNumber) MessageType() string { + return "userPrivacySettingAllowFindingByPhoneNumber" +} + +// NewUserPrivacySettingAllowFindingByPhoneNumber creates a new UserPrivacySettingAllowFindingByPhoneNumber +// +func NewUserPrivacySettingAllowFindingByPhoneNumber() *UserPrivacySettingAllowFindingByPhoneNumber { + userPrivacySettingAllowFindingByPhoneNumberTemp := UserPrivacySettingAllowFindingByPhoneNumber{ + tdCommon: tdCommon{Type: "userPrivacySettingAllowFindingByPhoneNumber"}, + } + + return &userPrivacySettingAllowFindingByPhoneNumberTemp +} + +// GetUserPrivacySettingEnum return the enum type of this object +func (userPrivacySettingAllowFindingByPhoneNumber *UserPrivacySettingAllowFindingByPhoneNumber) GetUserPrivacySettingEnum() UserPrivacySettingEnum { + return UserPrivacySettingAllowFindingByPhoneNumberType +} diff --git a/tdlib/userPrivacySettingRule.go b/tdlib/userPrivacySettingRule.go new file mode 100644 index 0000000..9002099 --- /dev/null +++ b/tdlib/userPrivacySettingRule.go @@ -0,0 +1,297 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// UserPrivacySettingRule Represents a single rule for managing privacy settings +type UserPrivacySettingRule interface { + GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum +} + +// 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" + UserPrivacySettingRuleAllowChatMembersType UserPrivacySettingRuleEnum = "userPrivacySettingRuleAllowChatMembers" + UserPrivacySettingRuleRestrictAllType UserPrivacySettingRuleEnum = "userPrivacySettingRuleRestrictAll" + UserPrivacySettingRuleRestrictContactsType UserPrivacySettingRuleEnum = "userPrivacySettingRuleRestrictContacts" + UserPrivacySettingRuleRestrictUsersType UserPrivacySettingRuleEnum = "userPrivacySettingRuleRestrictUsers" + UserPrivacySettingRuleRestrictChatMembersType UserPrivacySettingRuleEnum = "userPrivacySettingRuleRestrictChatMembers" +) + +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 UserPrivacySettingRuleAllowChatMembersType: + var userPrivacySettingRuleAllowChatMembers UserPrivacySettingRuleAllowChatMembers + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleAllowChatMembers) + return &userPrivacySettingRuleAllowChatMembers, 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 + + case UserPrivacySettingRuleRestrictChatMembersType: + var userPrivacySettingRuleRestrictChatMembers UserPrivacySettingRuleRestrictChatMembers + err := json.Unmarshal(*rawMsg, &userPrivacySettingRuleRestrictChatMembers) + return &userPrivacySettingRuleRestrictChatMembers, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// 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 []int64 `json:"user_ids"` // The user identifiers, total number of users in all rules must not exceed 1000 +} + +// 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, total number of users in all rules must not exceed 1000 +func NewUserPrivacySettingRuleAllowUsers(userIDs []int64) *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 +} + +// UserPrivacySettingRuleAllowChatMembers A rule to allow all members of certain specified basic groups and supergroups to doing something +type UserPrivacySettingRuleAllowChatMembers struct { + tdCommon + ChatIDs []int64 `json:"chat_ids"` // The chat identifiers, total number of chats in all rules must not exceed 20 +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleAllowChatMembers +func (userPrivacySettingRuleAllowChatMembers *UserPrivacySettingRuleAllowChatMembers) MessageType() string { + return "userPrivacySettingRuleAllowChatMembers" +} + +// NewUserPrivacySettingRuleAllowChatMembers creates a new UserPrivacySettingRuleAllowChatMembers +// +// @param chatIDs The chat identifiers, total number of chats in all rules must not exceed 20 +func NewUserPrivacySettingRuleAllowChatMembers(chatIDs []int64) *UserPrivacySettingRuleAllowChatMembers { + userPrivacySettingRuleAllowChatMembersTemp := UserPrivacySettingRuleAllowChatMembers{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleAllowChatMembers"}, + ChatIDs: chatIDs, + } + + return &userPrivacySettingRuleAllowChatMembersTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleAllowChatMembers *UserPrivacySettingRuleAllowChatMembers) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleAllowChatMembersType +} + +// 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 []int64 `json:"user_ids"` // The user identifiers, total number of users in all rules must not exceed 1000 +} + +// 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, total number of users in all rules must not exceed 1000 +func NewUserPrivacySettingRuleRestrictUsers(userIDs []int64) *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 +} + +// UserPrivacySettingRuleRestrictChatMembers A rule to restrict all members of specified basic groups and supergroups from doing something +type UserPrivacySettingRuleRestrictChatMembers struct { + tdCommon + ChatIDs []int64 `json:"chat_ids"` // The chat identifiers, total number of chats in all rules must not exceed 20 +} + +// MessageType return the string telegram-type of UserPrivacySettingRuleRestrictChatMembers +func (userPrivacySettingRuleRestrictChatMembers *UserPrivacySettingRuleRestrictChatMembers) MessageType() string { + return "userPrivacySettingRuleRestrictChatMembers" +} + +// NewUserPrivacySettingRuleRestrictChatMembers creates a new UserPrivacySettingRuleRestrictChatMembers +// +// @param chatIDs The chat identifiers, total number of chats in all rules must not exceed 20 +func NewUserPrivacySettingRuleRestrictChatMembers(chatIDs []int64) *UserPrivacySettingRuleRestrictChatMembers { + userPrivacySettingRuleRestrictChatMembersTemp := UserPrivacySettingRuleRestrictChatMembers{ + tdCommon: tdCommon{Type: "userPrivacySettingRuleRestrictChatMembers"}, + ChatIDs: chatIDs, + } + + return &userPrivacySettingRuleRestrictChatMembersTemp +} + +// GetUserPrivacySettingRuleEnum return the enum type of this object +func (userPrivacySettingRuleRestrictChatMembers *UserPrivacySettingRuleRestrictChatMembers) GetUserPrivacySettingRuleEnum() UserPrivacySettingRuleEnum { + return UserPrivacySettingRuleRestrictChatMembersType +} diff --git a/tdlib/userPrivacySettingRules.go b/tdlib/userPrivacySettingRules.go new file mode 100644 index 0000000..ffdf4dc --- /dev/null +++ b/tdlib/userPrivacySettingRules.go @@ -0,0 +1,26 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/userStatus.go b/tdlib/userStatus.go new file mode 100644 index 0000000..a430e39 --- /dev/null +++ b/tdlib/userStatus.go @@ -0,0 +1,229 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// UserStatus Describes the last time the user was online +type UserStatus interface { + GetUserStatusEnum() UserStatusEnum +} + +// 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" +) + +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)) + } +} + +// 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 +} diff --git a/tdlib/userType.go b/tdlib/userType.go new file mode 100644 index 0000000..3539960 --- /dev/null +++ b/tdlib/userType.go @@ -0,0 +1,176 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// UserType Represents the type of a user. The following types are possible: regular users, deleted users and bots +type UserType interface { + GetUserTypeEnum() UserTypeEnum +} + +// 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" +) + +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)) + } +} + +// 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 identifier 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 application 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 application 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 identifier 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 +} diff --git a/tdlib/users.go b/tdlib/users.go new file mode 100644 index 0000000..ac732c5 --- /dev/null +++ b/tdlib/users.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// Users Represents a list of users +type Users struct { + tdCommon + TotalCount int32 `json:"total_count"` // Approximate total count of users found + UserIDs []int64 `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 []int64) *Users { + usersTemp := Users{ + tdCommon: tdCommon{Type: "users"}, + TotalCount: totalCount, + UserIDs: userIDs, + } + + return &usersTemp +} diff --git a/tdlib/validatedOrderInfo.go b/tdlib/validatedOrderInfo.go new file mode 100644 index 0000000..99ec081 --- /dev/null +++ b/tdlib/validatedOrderInfo.go @@ -0,0 +1,29 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/vectorPathCommand.go b/tdlib/vectorPathCommand.go new file mode 100644 index 0000000..5978e75 --- /dev/null +++ b/tdlib/vectorPathCommand.go @@ -0,0 +1,111 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" + "fmt" +) + +// VectorPathCommand Represents a vector path command +type VectorPathCommand interface { + GetVectorPathCommandEnum() VectorPathCommandEnum +} + +// VectorPathCommandEnum Alias for abstract VectorPathCommand 'Sub-Classes', used as constant-enum here +type VectorPathCommandEnum string + +// VectorPathCommand enums +const ( + VectorPathCommandLineType VectorPathCommandEnum = "vectorPathCommandLine" + VectorPathCommandCubicBezierCurveType VectorPathCommandEnum = "vectorPathCommandCubicBezierCurve" +) + +func unmarshalVectorPathCommand(rawMsg *json.RawMessage) (VectorPathCommand, error) { + + if rawMsg == nil { + return nil, nil + } + var objMap map[string]interface{} + err := json.Unmarshal(*rawMsg, &objMap) + if err != nil { + return nil, err + } + + switch VectorPathCommandEnum(objMap["@type"].(string)) { + case VectorPathCommandLineType: + var vectorPathCommandLine VectorPathCommandLine + err := json.Unmarshal(*rawMsg, &vectorPathCommandLine) + return &vectorPathCommandLine, err + + case VectorPathCommandCubicBezierCurveType: + var vectorPathCommandCubicBezierCurve VectorPathCommandCubicBezierCurve + err := json.Unmarshal(*rawMsg, &vectorPathCommandCubicBezierCurve) + return &vectorPathCommandCubicBezierCurve, err + + default: + return nil, fmt.Errorf("Error UnMarshaling, unknown type:" + objMap["@type"].(string)) + } +} + +// VectorPathCommandLine A straight line to a given point +type VectorPathCommandLine struct { + tdCommon + EndPoint *Point `json:"end_point"` // The end point of the straight line +} + +// MessageType return the string telegram-type of VectorPathCommandLine +func (vectorPathCommandLine *VectorPathCommandLine) MessageType() string { + return "vectorPathCommandLine" +} + +// NewVectorPathCommandLine creates a new VectorPathCommandLine +// +// @param endPoint The end point of the straight line +func NewVectorPathCommandLine(endPoint *Point) *VectorPathCommandLine { + vectorPathCommandLineTemp := VectorPathCommandLine{ + tdCommon: tdCommon{Type: "vectorPathCommandLine"}, + EndPoint: endPoint, + } + + return &vectorPathCommandLineTemp +} + +// GetVectorPathCommandEnum return the enum type of this object +func (vectorPathCommandLine *VectorPathCommandLine) GetVectorPathCommandEnum() VectorPathCommandEnum { + return VectorPathCommandLineType +} + +// VectorPathCommandCubicBezierCurve A cubic Bézier curve to a given point +type VectorPathCommandCubicBezierCurve struct { + tdCommon + StartControlPoint *Point `json:"start_control_point"` // The start control point of the curve + EndControlPoint *Point `json:"end_control_point"` // The end control point of the curve + EndPoint *Point `json:"end_point"` // The end point of the curve +} + +// MessageType return the string telegram-type of VectorPathCommandCubicBezierCurve +func (vectorPathCommandCubicBezierCurve *VectorPathCommandCubicBezierCurve) MessageType() string { + return "vectorPathCommandCubicBezierCurve" +} + +// NewVectorPathCommandCubicBezierCurve creates a new VectorPathCommandCubicBezierCurve +// +// @param startControlPoint The start control point of the curve +// @param endControlPoint The end control point of the curve +// @param endPoint The end point of the curve +func NewVectorPathCommandCubicBezierCurve(startControlPoint *Point, endControlPoint *Point, endPoint *Point) *VectorPathCommandCubicBezierCurve { + vectorPathCommandCubicBezierCurveTemp := VectorPathCommandCubicBezierCurve{ + tdCommon: tdCommon{Type: "vectorPathCommandCubicBezierCurve"}, + StartControlPoint: startControlPoint, + EndControlPoint: endControlPoint, + EndPoint: endPoint, + } + + return &vectorPathCommandCubicBezierCurveTemp +} + +// GetVectorPathCommandEnum return the enum type of this object +func (vectorPathCommandCubicBezierCurve *VectorPathCommandCubicBezierCurve) GetVectorPathCommandEnum() VectorPathCommandEnum { + return VectorPathCommandCubicBezierCurveType +} diff --git a/tdlib/venue.go b/tdlib/venue.go new file mode 100644 index 0000000..7fae7dc --- /dev/null +++ b/tdlib/venue.go @@ -0,0 +1,41 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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" and "gplaces" (Google Places) need 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" and "gplaces" (Google Places) need 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 +} diff --git a/tdlib/video.go b/tdlib/video.go new file mode 100644 index 0000000..5c505c6 --- /dev/null +++ b/tdlib/video.go @@ -0,0 +1,53 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 video. The list of corresponding sticker sets can be received using getAttachedStickerSets + SupportsStreaming bool `json:"supports_streaming"` // True, if the video should be tried to be streamed + Minithumbnail *Minithumbnail `json:"minithumbnail"` // Video minithumbnail; may be null + Thumbnail *Thumbnail `json:"thumbnail"` // Video thumbnail in JPEG or MPEG4 format; 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 video. The list of corresponding sticker sets can be received using getAttachedStickerSets +// @param supportsStreaming True, if the video should be tried to be streamed +// @param minithumbnail Video minithumbnail; may be null +// @param thumbnail Video thumbnail in JPEG or MPEG4 format; 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, minithumbnail *Minithumbnail, thumbnail *Thumbnail, video *File) *Video { + videoTemp := Video{ + tdCommon: tdCommon{Type: "video"}, + Duration: duration, + Width: width, + Height: height, + FileName: fileName, + MimeType: mimeType, + HasStickers: hasStickers, + SupportsStreaming: supportsStreaming, + Minithumbnail: minithumbnail, + Thumbnail: thumbnail, + Video: video, + } + + return &videoTemp +} diff --git a/tdlib/videoNote.go b/tdlib/videoNote.go new file mode 100644 index 0000000..ee1e521 --- /dev/null +++ b/tdlib/videoNote.go @@ -0,0 +1,38 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 + Minithumbnail *Minithumbnail `json:"minithumbnail"` // Video minithumbnail; may be null + Thumbnail *Thumbnail `json:"thumbnail"` // Video thumbnail in JPEG format; 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 minithumbnail Video minithumbnail; may be null +// @param thumbnail Video thumbnail in JPEG format; as defined by the sender; may be null +// @param video File containing the video +func NewVideoNote(duration int32, length int32, minithumbnail *Minithumbnail, thumbnail *Thumbnail, video *File) *VideoNote { + videoNoteTemp := VideoNote{ + tdCommon: tdCommon{Type: "videoNote"}, + Duration: duration, + Length: length, + Minithumbnail: minithumbnail, + Thumbnail: thumbnail, + Video: video, + } + + return &videoNoteTemp +} diff --git a/tdlib/voiceChat.go b/tdlib/voiceChat.go new file mode 100644 index 0000000..1a9a95b --- /dev/null +++ b/tdlib/voiceChat.go @@ -0,0 +1,64 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// VoiceChat Describes a voice chat +type VoiceChat struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Group call identifier of an active voice chat; 0 if none. Full informationa about the voice chat can be received through the method getGroupCall + HasParticipants bool `json:"has_participants"` // True, if the voice chat has participants + DefaultParticipantID MessageSender `json:"default_participant_id"` // Default group call participant identifier to join the voice chat; may be null +} + +// MessageType return the string telegram-type of VoiceChat +func (voiceChat *VoiceChat) MessageType() string { + return "voiceChat" +} + +// NewVoiceChat creates a new VoiceChat +// +// @param groupCallID Group call identifier of an active voice chat; 0 if none. Full informationa about the voice chat can be received through the method getGroupCall +// @param hasParticipants True, if the voice chat has participants +// @param defaultParticipantID Default group call participant identifier to join the voice chat; may be null +func NewVoiceChat(groupCallID int32, hasParticipants bool, defaultParticipantID MessageSender) *VoiceChat { + voiceChatTemp := VoiceChat{ + tdCommon: tdCommon{Type: "voiceChat"}, + GroupCallID: groupCallID, + HasParticipants: hasParticipants, + DefaultParticipantID: defaultParticipantID, + } + + return &voiceChatTemp +} + +// UnmarshalJSON unmarshal to json +func (voiceChat *VoiceChat) UnmarshalJSON(b []byte) error { + var objMap map[string]*json.RawMessage + err := json.Unmarshal(b, &objMap) + if err != nil { + return err + } + tempObj := struct { + tdCommon + GroupCallID int32 `json:"group_call_id"` // Group call identifier of an active voice chat; 0 if none. Full informationa about the voice chat can be received through the method getGroupCall + HasParticipants bool `json:"has_participants"` // True, if the voice chat has participants + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + voiceChat.tdCommon = tempObj.tdCommon + voiceChat.GroupCallID = tempObj.GroupCallID + voiceChat.HasParticipants = tempObj.HasParticipants + + fieldDefaultParticipantID, _ := unmarshalMessageSender(objMap["default_participant_id"]) + voiceChat.DefaultParticipantID = fieldDefaultParticipantID + + return nil +} diff --git a/tdlib/voiceNote.go b/tdlib/voiceNote.go new file mode 100644 index 0000000..3c76283 --- /dev/null +++ b/tdlib/voiceNote.go @@ -0,0 +1,35 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 +} diff --git a/tdlib/webPage.go b/tdlib/webPage.go new file mode 100644 index 0000000..067788b --- /dev/null +++ b/tdlib/webPage.go @@ -0,0 +1,86 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +// 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 *FormattedText `json:"description"` // Description of the content + 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 + InstantViewVersion int32 `json:"instant_view_version"` // Version of instant view, available for the web page (currently can be 1 or 2), 0 if none +} + +// 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 Description of the content +// @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 instantViewVersion Version of instant view, available for the web page (currently can be 1 or 2), 0 if none +func NewWebPage(uRL string, displayURL string, typeParam string, siteName string, title string, description *FormattedText, 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, instantViewVersion int32) *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, + InstantViewVersion: instantViewVersion, + } + + return &webPageTemp +} diff --git a/tdlib/webPageInstantView.go b/tdlib/webPageInstantView.go new file mode 100644 index 0000000..d4c3f72 --- /dev/null +++ b/tdlib/webPageInstantView.go @@ -0,0 +1,79 @@ +// AUTOGENERATED - DO NOT EDIT + +package tdlib + +import ( + "encoding/json" +) + +// WebPageInstantView Describes an instant view page for a web page +type WebPageInstantView struct { + tdCommon + PageBlocks []PageBlock `json:"page_blocks"` // Content of the web page + ViewCount int32 `json:"view_count"` // Number of the instant view views; 0 if unknown + Version int32 `json:"version"` // Version of the instant view, currently can be 1 or 2 + IsRtl bool `json:"is_rtl"` // True, if the instant view must be shown from right to left + 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 + FeedbackLink InternalLinkType `json:"feedback_link"` // An internal link to be opened to leave feedback about the 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 viewCount Number of the instant view views; 0 if unknown +// @param version Version of the instant view, currently can be 1 or 2 +// @param isRtl True, if the instant view must be shown from right to left +// @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 +// @param feedbackLink An internal link to be opened to leave feedback about the instant view +func NewWebPageInstantView(pageBlocks []PageBlock, viewCount int32, version int32, isRtl bool, isFull bool, feedbackLink InternalLinkType) *WebPageInstantView { + webPageInstantViewTemp := WebPageInstantView{ + tdCommon: tdCommon{Type: "webPageInstantView"}, + PageBlocks: pageBlocks, + ViewCount: viewCount, + Version: version, + IsRtl: isRtl, + IsFull: isFull, + FeedbackLink: feedbackLink, + } + + return &webPageInstantViewTemp +} + +// UnmarshalJSON unmarshal to json +func (webPageInstantView *WebPageInstantView) 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"` // Content of the web page + ViewCount int32 `json:"view_count"` // Number of the instant view views; 0 if unknown + Version int32 `json:"version"` // Version of the instant view, currently can be 1 or 2 + IsRtl bool `json:"is_rtl"` // True, if the instant view must be shown from right to left + 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 + + }{} + err = json.Unmarshal(b, &tempObj) + if err != nil { + return err + } + + webPageInstantView.tdCommon = tempObj.tdCommon + webPageInstantView.PageBlocks = tempObj.PageBlocks + webPageInstantView.ViewCount = tempObj.ViewCount + webPageInstantView.Version = tempObj.Version + webPageInstantView.IsRtl = tempObj.IsRtl + webPageInstantView.IsFull = tempObj.IsFull + + fieldFeedbackLink, _ := unmarshalInternalLinkType(objMap["feedback_link"]) + webPageInstantView.FeedbackLink = fieldFeedbackLink + + return nil +}