├── go.mod ├── examples ├── sendPhoto │ ├── bunny.jpg │ └── sendPhoto.go ├── authorization │ ├── botAuthorization.go │ └── basicAuthorization.go └── sendText │ └── sendText.go ├── .gitignore ├── point.go ├── date.go ├── datedFile.go ├── chatNearby.go ├── closedVectorPath.go ├── botCommand.go ├── pageBlockListItem.go ├── chatLocation.go ├── bankCardActionOpenURL.go ├── savedCredentials.go ├── dateRange.go ├── gameHighScore.go ├── recommendedChatFilter.go ├── labeledPricePart.go ├── colorReplacement.go ├── messageCalendarDay.go ├── chatTheme.go ├── minithumbnail.go ├── passportRequiredElement.go ├── chatJoinRequest.go ├── personalDocument.go ├── chatJoinRequestsInfo.go ├── shippingOption.go ├── chatStatisticsInviterInfo.go ├── groupCallVideoSourceGroup.go ├── encryptedCredentials.go ├── inputPersonalDocument.go ├── chatAdministrator.go ├── messagePosition.go ├── common.go ├── photo.go ├── proxies.go ├── termsOfService.go ├── statisticalValue.go ├── animatedChatPhoto.go ├── animations.go ├── logTags.go ├── countries.go ├── testInt.go ├── tMeURLs.go ├── tMeURL.go ├── chatInviteLinkMember.go ├── testBytes.go ├── location.go ├── chatInviteLinkCount.go ├── testString.go ├── updates.go ├── chatLists.go ├── seconds.go ├── voiceNote.go ├── hashtags.go ├── address.go ├── callID.go ├── contact.go ├── chatStatisticsMessageInteractionInfo.go ├── backgrounds.go ├── testVectorInt.go ├── chatStatisticsMessageSenderInfo.go ├── connectedWebsites.go ├── databaseStatistics.go ├── countryInfo.go ├── storageStatisticsByChat.go ├── accountTTL.go ├── textEntities.go ├── jsonObjectMember.go ├── testVectorString.go ├── passportElements.go ├── keyboardButton.go ├── photoSize.go ├── groupCallParticipantVideoInfo.go ├── paymentsProviderStripe.go ├── recommendedChatFilters.go ├── chatAdministrators.go ├── callProtocol.go ├── customRequestResult.go ├── chatPhoto.go ├── sessions.go ├── pollOption.go ├── chatPhotoInfo.go ├── testVectorIntObject.go ├── game.go ├── messageInteractionInfo.go ├── pageBlockCaption.go ├── videoNote.go ├── bankCardInfo.go ├── document.go ├── inlineKeyboardButton.go ├── chatInviteLinkCounts.go ├── testVectorStringObject.go ├── languagePackString.go ├── pageBlockRelatedArticle.go ├── userPrivacySettingRules.go ├── recoveryEmailAddress.go ├── error.go ├── venue.go ├── botCommands.go ├── messageCopyOptions.go ├── chatPhotos.go ├── orderInfo.go ├── groupCallID.go ├── thumbnail.go ├── chatStatisticsAdministratorActionsInfo.go ├── profilePhoto.go ├── languagePackStrings.go ├── deepLinkInfo.go ├── textEntity.go ├── paymentFormTheme.go ├── chatsNearby.go ├── iDentityDocument.go ├── networkStatistics.go ├── localizationTargetInfo.go ├── groupCallRecentSpeaker.go ├── storageStatisticsByFileType.go ├── passportElementError.go ├── chatEvent.go ├── call.go ├── notification.go ├── animatedEmoji.go ├── inputPassportElementError.go ├── chatEvents.go ├── inputThumbnail.go ├── callbackQueryAnswer.go ├── logVerbosityLevel.go ├── callServer.go ├── draftMessage.go ├── passportElementsWithErrors.go ├── validatedOrderInfo.go ├── autoDownloadSettingsPresets.go ├── messageReplyInfo.go ├── emojis.go └── messageLink.go /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/c0re100/go-tdlib 2 | 3 | go 1.15 4 | -------------------------------------------------------------------------------- /examples/sendPhoto/bunny.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c0re100/go-tdlib/HEAD/examples/sendPhoto/bunny.jpg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Any file without an extension 3 | * 4 | !*/ 5 | !*.* 6 | 7 | /.vscode 8 | /.git_old 9 | 10 | 11 | # Binaries for programs and plugins 12 | *.exe 13 | *.dll 14 | *.so 15 | *.dylib 16 | 17 | # Test binary, build with `go test -c` 18 | *.test 19 | 20 | # Output of the go coverage tool, specifically when used with LiteIDE 21 | *.out 22 | 23 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 24 | .glide/ 25 | 26 | tdlib-db 27 | tdlib-files 28 | 29 | errors.txt 30 | 31 | .idea/ 32 | -------------------------------------------------------------------------------- /point.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Point A point on a Cartesian plane 4 | type Point struct { 5 | tdCommon 6 | X float64 `json:"x"` // The point's first coordinate 7 | Y float64 `json:"y"` // The point's second coordinate 8 | } 9 | 10 | // MessageType return the string telegram-type of Point 11 | func (point *Point) MessageType() string { 12 | return "point" 13 | } 14 | 15 | // NewPoint creates a new Point 16 | // 17 | // @param x The point's first coordinate 18 | // @param y The point's second coordinate 19 | func NewPoint(x float64, y float64) *Point { 20 | pointTemp := Point{ 21 | tdCommon: tdCommon{Type: "point"}, 22 | X: x, 23 | Y: y, 24 | } 25 | 26 | return &pointTemp 27 | } 28 | -------------------------------------------------------------------------------- /date.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Date Represents a date according to the Gregorian calendar 4 | type Date struct { 5 | tdCommon 6 | Day int32 `json:"day"` // Day of the month; 1-31 7 | Month int32 `json:"month"` // Month; 1-12 8 | Year int32 `json:"year"` // Year; 1-9999 9 | } 10 | 11 | // MessageType return the string telegram-type of Date 12 | func (date *Date) MessageType() string { 13 | return "date" 14 | } 15 | 16 | // NewDate creates a new Date 17 | // 18 | // @param day Day of the month; 1-31 19 | // @param month Month; 1-12 20 | // @param year Year; 1-9999 21 | func NewDate(day int32, month int32, year int32) *Date { 22 | dateTemp := Date{ 23 | tdCommon: tdCommon{Type: "date"}, 24 | Day: day, 25 | Month: month, 26 | Year: year, 27 | } 28 | 29 | return &dateTemp 30 | } 31 | -------------------------------------------------------------------------------- /datedFile.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // DatedFile File with the date it was uploaded 4 | type DatedFile struct { 5 | tdCommon 6 | File *File `json:"file"` // The file 7 | Date int32 `json:"date"` // Point in time (Unix timestamp) when the file was uploaded 8 | } 9 | 10 | // MessageType return the string telegram-type of DatedFile 11 | func (datedFile *DatedFile) MessageType() string { 12 | return "datedFile" 13 | } 14 | 15 | // NewDatedFile creates a new DatedFile 16 | // 17 | // @param file The file 18 | // @param date Point in time (Unix timestamp) when the file was uploaded 19 | func NewDatedFile(file *File, date int32) *DatedFile { 20 | datedFileTemp := DatedFile{ 21 | tdCommon: tdCommon{Type: "datedFile"}, 22 | File: file, 23 | Date: date, 24 | } 25 | 26 | return &datedFileTemp 27 | } 28 | -------------------------------------------------------------------------------- /chatNearby.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatNearby Describes a chat located nearby 4 | type ChatNearby struct { 5 | tdCommon 6 | ChatId int64 `json:"chat_id"` // Chat identifier 7 | Distance int32 `json:"distance"` // Distance to the chat location, in meters 8 | } 9 | 10 | // MessageType return the string telegram-type of ChatNearby 11 | func (chatNearby *ChatNearby) MessageType() string { 12 | return "chatNearby" 13 | } 14 | 15 | // NewChatNearby creates a new ChatNearby 16 | // 17 | // @param chatId Chat identifier 18 | // @param distance Distance to the chat location, in meters 19 | func NewChatNearby(chatId int64, distance int32) *ChatNearby { 20 | chatNearbyTemp := ChatNearby{ 21 | tdCommon: tdCommon{Type: "chatNearby"}, 22 | ChatId: chatId, 23 | Distance: distance, 24 | } 25 | 26 | return &chatNearbyTemp 27 | } 28 | -------------------------------------------------------------------------------- /closedVectorPath.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ClosedVectorPath Represents a closed vector path. The path begins at the end point of the last command 4 | type ClosedVectorPath struct { 5 | tdCommon 6 | Commands []VectorPathCommand `json:"commands"` // List of vector path commands 7 | } 8 | 9 | // MessageType return the string telegram-type of ClosedVectorPath 10 | func (closedVectorPath *ClosedVectorPath) MessageType() string { 11 | return "closedVectorPath" 12 | } 13 | 14 | // NewClosedVectorPath creates a new ClosedVectorPath 15 | // 16 | // @param commands List of vector path commands 17 | func NewClosedVectorPath(commands []VectorPathCommand) *ClosedVectorPath { 18 | closedVectorPathTemp := ClosedVectorPath{ 19 | tdCommon: tdCommon{Type: "closedVectorPath"}, 20 | Commands: commands, 21 | } 22 | 23 | return &closedVectorPathTemp 24 | } 25 | -------------------------------------------------------------------------------- /botCommand.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // BotCommand Represents a command supported by a bot 4 | type BotCommand struct { 5 | tdCommon 6 | Command string `json:"command"` // Text of the bot command 7 | Description string `json:"description"` // Description of the bot command 8 | } 9 | 10 | // MessageType return the string telegram-type of BotCommand 11 | func (botCommand *BotCommand) MessageType() string { 12 | return "botCommand" 13 | } 14 | 15 | // NewBotCommand creates a new BotCommand 16 | // 17 | // @param command Text of the bot command 18 | // @param description Description of the bot command 19 | func NewBotCommand(command string, description string) *BotCommand { 20 | botCommandTemp := BotCommand{ 21 | tdCommon: tdCommon{Type: "botCommand"}, 22 | Command: command, 23 | Description: description, 24 | } 25 | 26 | return &botCommandTemp 27 | } 28 | -------------------------------------------------------------------------------- /pageBlockListItem.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PageBlockListItem Describes an item of a list page block 4 | type PageBlockListItem struct { 5 | tdCommon 6 | Label string `json:"label"` // Item label 7 | PageBlocks []PageBlock `json:"page_blocks"` // Item blocks 8 | } 9 | 10 | // MessageType return the string telegram-type of PageBlockListItem 11 | func (pageBlockListItem *PageBlockListItem) MessageType() string { 12 | return "pageBlockListItem" 13 | } 14 | 15 | // NewPageBlockListItem creates a new PageBlockListItem 16 | // 17 | // @param label Item label 18 | // @param pageBlocks Item blocks 19 | func NewPageBlockListItem(label string, pageBlocks []PageBlock) *PageBlockListItem { 20 | pageBlockListItemTemp := PageBlockListItem{ 21 | tdCommon: tdCommon{Type: "pageBlockListItem"}, 22 | Label: label, 23 | PageBlocks: pageBlocks, 24 | } 25 | 26 | return &pageBlockListItemTemp 27 | } 28 | -------------------------------------------------------------------------------- /chatLocation.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatLocation Represents a location to which a chat is connected 4 | type ChatLocation struct { 5 | tdCommon 6 | Location *Location `json:"location"` // The location 7 | Address string `json:"address"` // Location address; 1-64 characters, as defined by the chat owner 8 | } 9 | 10 | // MessageType return the string telegram-type of ChatLocation 11 | func (chatLocation *ChatLocation) MessageType() string { 12 | return "chatLocation" 13 | } 14 | 15 | // NewChatLocation creates a new ChatLocation 16 | // 17 | // @param location The location 18 | // @param address Location address; 1-64 characters, as defined by the chat owner 19 | func NewChatLocation(location *Location, address string) *ChatLocation { 20 | chatLocationTemp := ChatLocation{ 21 | tdCommon: tdCommon{Type: "chatLocation"}, 22 | Location: location, 23 | Address: address, 24 | } 25 | 26 | return &chatLocationTemp 27 | } 28 | -------------------------------------------------------------------------------- /bankCardActionOpenURL.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // BankCardActionOpenUrl Describes an action associated with a bank card number 4 | type BankCardActionOpenUrl struct { 5 | tdCommon 6 | Text string `json:"text"` // Action text 7 | Url string `json:"url"` // The URL to be opened 8 | } 9 | 10 | // MessageType return the string telegram-type of BankCardActionOpenUrl 11 | func (bankCardActionOpenUrl *BankCardActionOpenUrl) MessageType() string { 12 | return "bankCardActionOpenUrl" 13 | } 14 | 15 | // NewBankCardActionOpenUrl creates a new BankCardActionOpenUrl 16 | // 17 | // @param text Action text 18 | // @param url The URL to be opened 19 | func NewBankCardActionOpenUrl(text string, url string) *BankCardActionOpenUrl { 20 | bankCardActionOpenUrlTemp := BankCardActionOpenUrl{ 21 | tdCommon: tdCommon{Type: "bankCardActionOpenUrl"}, 22 | Text: text, 23 | Url: url, 24 | } 25 | 26 | return &bankCardActionOpenUrlTemp 27 | } 28 | -------------------------------------------------------------------------------- /savedCredentials.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // SavedCredentials Contains information about saved card credentials 4 | type SavedCredentials struct { 5 | tdCommon 6 | Id string `json:"id"` // Unique identifier of the saved credentials 7 | Title string `json:"title"` // Title of the saved credentials 8 | } 9 | 10 | // MessageType return the string telegram-type of SavedCredentials 11 | func (savedCredentials *SavedCredentials) MessageType() string { 12 | return "savedCredentials" 13 | } 14 | 15 | // NewSavedCredentials creates a new SavedCredentials 16 | // 17 | // @param id Unique identifier of the saved credentials 18 | // @param title Title of the saved credentials 19 | func NewSavedCredentials(id string, title string) *SavedCredentials { 20 | savedCredentialsTemp := SavedCredentials{ 21 | tdCommon: tdCommon{Type: "savedCredentials"}, 22 | Id: id, 23 | Title: title, 24 | } 25 | 26 | return &savedCredentialsTemp 27 | } 28 | -------------------------------------------------------------------------------- /dateRange.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // DateRange Represents a date range 4 | type DateRange struct { 5 | tdCommon 6 | StartDate int32 `json:"start_date"` // Point in time (Unix timestamp) at which the date range begins 7 | EndDate int32 `json:"end_date"` // Point in time (Unix timestamp) at which the date range ends 8 | } 9 | 10 | // MessageType return the string telegram-type of DateRange 11 | func (dateRange *DateRange) MessageType() string { 12 | return "dateRange" 13 | } 14 | 15 | // NewDateRange creates a new DateRange 16 | // 17 | // @param startDate Point in time (Unix timestamp) at which the date range begins 18 | // @param endDate Point in time (Unix timestamp) at which the date range ends 19 | func NewDateRange(startDate int32, endDate int32) *DateRange { 20 | dateRangeTemp := DateRange{ 21 | tdCommon: tdCommon{Type: "dateRange"}, 22 | StartDate: startDate, 23 | EndDate: endDate, 24 | } 25 | 26 | return &dateRangeTemp 27 | } 28 | -------------------------------------------------------------------------------- /gameHighScore.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // GameHighScore Contains one row of the game high score table 4 | type GameHighScore struct { 5 | tdCommon 6 | Position int32 `json:"position"` // Position in the high score table 7 | UserId int64 `json:"user_id"` // User identifier 8 | Score int32 `json:"score"` // User score 9 | } 10 | 11 | // MessageType return the string telegram-type of GameHighScore 12 | func (gameHighScore *GameHighScore) MessageType() string { 13 | return "gameHighScore" 14 | } 15 | 16 | // NewGameHighScore creates a new GameHighScore 17 | // 18 | // @param position Position in the high score table 19 | // @param userId User identifier 20 | // @param score User score 21 | func NewGameHighScore(position int32, userId int64, score int32) *GameHighScore { 22 | gameHighScoreTemp := GameHighScore{ 23 | tdCommon: tdCommon{Type: "gameHighScore"}, 24 | Position: position, 25 | UserId: userId, 26 | Score: score, 27 | } 28 | 29 | return &gameHighScoreTemp 30 | } 31 | -------------------------------------------------------------------------------- /recommendedChatFilter.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // RecommendedChatFilter Describes a recommended chat filter 4 | type RecommendedChatFilter struct { 5 | tdCommon 6 | Filter *ChatFilter `json:"filter"` // The chat filter 7 | Description string `json:"description"` // Chat filter description 8 | } 9 | 10 | // MessageType return the string telegram-type of RecommendedChatFilter 11 | func (recommendedChatFilter *RecommendedChatFilter) MessageType() string { 12 | return "recommendedChatFilter" 13 | } 14 | 15 | // NewRecommendedChatFilter creates a new RecommendedChatFilter 16 | // 17 | // @param filter The chat filter 18 | // @param description Chat filter description 19 | func NewRecommendedChatFilter(filter *ChatFilter, description string) *RecommendedChatFilter { 20 | recommendedChatFilterTemp := RecommendedChatFilter{ 21 | tdCommon: tdCommon{Type: "recommendedChatFilter"}, 22 | Filter: filter, 23 | Description: description, 24 | } 25 | 26 | return &recommendedChatFilterTemp 27 | } 28 | -------------------------------------------------------------------------------- /labeledPricePart.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // LabeledPricePart Portion of the price of a product (e.g., "delivery cost", "tax amount") 4 | type LabeledPricePart struct { 5 | tdCommon 6 | Label string `json:"label"` // Label for this portion of the product price 7 | Amount int64 `json:"amount"` // Currency amount in the smallest units of the currency 8 | } 9 | 10 | // MessageType return the string telegram-type of LabeledPricePart 11 | func (labeledPricePart *LabeledPricePart) MessageType() string { 12 | return "labeledPricePart" 13 | } 14 | 15 | // NewLabeledPricePart creates a new LabeledPricePart 16 | // 17 | // @param label Label for this portion of the product price 18 | // @param amount Currency amount in the smallest units of the currency 19 | func NewLabeledPricePart(label string, amount int64) *LabeledPricePart { 20 | labeledPricePartTemp := LabeledPricePart{ 21 | tdCommon: tdCommon{Type: "labeledPricePart"}, 22 | Label: label, 23 | Amount: amount, 24 | } 25 | 26 | return &labeledPricePartTemp 27 | } 28 | -------------------------------------------------------------------------------- /colorReplacement.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ColorReplacement Describes a color replacement for animated emoji 4 | type ColorReplacement struct { 5 | tdCommon 6 | OldColor int32 `json:"old_color"` // Original animated emoji color in the RGB24 format 7 | NewColor int32 `json:"new_color"` // Replacement animated emoji color in the RGB24 format 8 | } 9 | 10 | // MessageType return the string telegram-type of ColorReplacement 11 | func (colorReplacement *ColorReplacement) MessageType() string { 12 | return "colorReplacement" 13 | } 14 | 15 | // NewColorReplacement creates a new ColorReplacement 16 | // 17 | // @param oldColor Original animated emoji color in the RGB24 format 18 | // @param newColor Replacement animated emoji color in the RGB24 format 19 | func NewColorReplacement(oldColor int32, newColor int32) *ColorReplacement { 20 | colorReplacementTemp := ColorReplacement{ 21 | tdCommon: tdCommon{Type: "colorReplacement"}, 22 | OldColor: oldColor, 23 | NewColor: newColor, 24 | } 25 | 26 | return &colorReplacementTemp 27 | } 28 | -------------------------------------------------------------------------------- /messageCalendarDay.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // MessageCalendarDay Contains information about found messages sent on a specific day 4 | type MessageCalendarDay struct { 5 | tdCommon 6 | TotalCount int32 `json:"total_count"` // Total number of found messages sent on the day 7 | Message *Message `json:"message"` // First message sent on the day 8 | } 9 | 10 | // MessageType return the string telegram-type of MessageCalendarDay 11 | func (messageCalendarDay *MessageCalendarDay) MessageType() string { 12 | return "messageCalendarDay" 13 | } 14 | 15 | // NewMessageCalendarDay creates a new MessageCalendarDay 16 | // 17 | // @param totalCount Total number of found messages sent on the day 18 | // @param message First message sent on the day 19 | func NewMessageCalendarDay(totalCount int32, message *Message) *MessageCalendarDay { 20 | messageCalendarDayTemp := MessageCalendarDay{ 21 | tdCommon: tdCommon{Type: "messageCalendarDay"}, 22 | TotalCount: totalCount, 23 | Message: message, 24 | } 25 | 26 | return &messageCalendarDayTemp 27 | } 28 | -------------------------------------------------------------------------------- /chatTheme.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatTheme Describes a chat theme 4 | type ChatTheme struct { 5 | tdCommon 6 | Name string `json:"name"` // Theme name 7 | LightSettings *ThemeSettings `json:"light_settings"` // Theme settings for a light chat theme 8 | DarkSettings *ThemeSettings `json:"dark_settings"` // Theme settings for a dark chat theme 9 | } 10 | 11 | // MessageType return the string telegram-type of ChatTheme 12 | func (chatTheme *ChatTheme) MessageType() string { 13 | return "chatTheme" 14 | } 15 | 16 | // NewChatTheme creates a new ChatTheme 17 | // 18 | // @param name Theme name 19 | // @param lightSettings Theme settings for a light chat theme 20 | // @param darkSettings Theme settings for a dark chat theme 21 | func NewChatTheme(name string, lightSettings *ThemeSettings, darkSettings *ThemeSettings) *ChatTheme { 22 | chatThemeTemp := ChatTheme{ 23 | tdCommon: tdCommon{Type: "chatTheme"}, 24 | Name: name, 25 | LightSettings: lightSettings, 26 | DarkSettings: darkSettings, 27 | } 28 | 29 | return &chatThemeTemp 30 | } 31 | -------------------------------------------------------------------------------- /minithumbnail.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Minithumbnail Thumbnail image of a very poor quality and low resolution 4 | type Minithumbnail struct { 5 | tdCommon 6 | Width int32 `json:"width"` // Thumbnail width, usually doesn't exceed 40 7 | Height int32 `json:"height"` // Thumbnail height, usually doesn't exceed 40 8 | Data []byte `json:"data"` // The thumbnail in JPEG format 9 | } 10 | 11 | // MessageType return the string telegram-type of Minithumbnail 12 | func (minithumbnail *Minithumbnail) MessageType() string { 13 | return "minithumbnail" 14 | } 15 | 16 | // NewMinithumbnail creates a new Minithumbnail 17 | // 18 | // @param width Thumbnail width, usually doesn't exceed 40 19 | // @param height Thumbnail height, usually doesn't exceed 40 20 | // @param data The thumbnail in JPEG format 21 | func NewMinithumbnail(width int32, height int32, data []byte) *Minithumbnail { 22 | minithumbnailTemp := Minithumbnail{ 23 | tdCommon: tdCommon{Type: "minithumbnail"}, 24 | Width: width, 25 | Height: height, 26 | Data: data, 27 | } 28 | 29 | return &minithumbnailTemp 30 | } 31 | -------------------------------------------------------------------------------- /passportRequiredElement.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PassportRequiredElement Contains a description of the required Telegram Passport element that was requested by a service 4 | type PassportRequiredElement struct { 5 | tdCommon 6 | SuitableElements []PassportSuitableElement `json:"suitable_elements"` // List of Telegram Passport elements any of which is enough to provide 7 | } 8 | 9 | // MessageType return the string telegram-type of PassportRequiredElement 10 | func (passportRequiredElement *PassportRequiredElement) MessageType() string { 11 | return "passportRequiredElement" 12 | } 13 | 14 | // NewPassportRequiredElement creates a new PassportRequiredElement 15 | // 16 | // @param suitableElements List of Telegram Passport elements any of which is enough to provide 17 | func NewPassportRequiredElement(suitableElements []PassportSuitableElement) *PassportRequiredElement { 18 | passportRequiredElementTemp := PassportRequiredElement{ 19 | tdCommon: tdCommon{Type: "passportRequiredElement"}, 20 | SuitableElements: suitableElements, 21 | } 22 | 23 | return &passportRequiredElementTemp 24 | } 25 | -------------------------------------------------------------------------------- /chatJoinRequest.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatJoinRequest Describes a user that sent a join request and waits for administrator approval 4 | type ChatJoinRequest struct { 5 | tdCommon 6 | UserId int64 `json:"user_id"` // User identifier 7 | Date int32 `json:"date"` // Point in time (Unix timestamp) when the user sent the join request 8 | Bio string `json:"bio"` // A short bio of the user 9 | } 10 | 11 | // MessageType return the string telegram-type of ChatJoinRequest 12 | func (chatJoinRequest *ChatJoinRequest) MessageType() string { 13 | return "chatJoinRequest" 14 | } 15 | 16 | // NewChatJoinRequest creates a new ChatJoinRequest 17 | // 18 | // @param userId User identifier 19 | // @param date Point in time (Unix timestamp) when the user sent the join request 20 | // @param bio A short bio of the user 21 | func NewChatJoinRequest(userId int64, date int32, bio string) *ChatJoinRequest { 22 | chatJoinRequestTemp := ChatJoinRequest{ 23 | tdCommon: tdCommon{Type: "chatJoinRequest"}, 24 | UserId: userId, 25 | Date: date, 26 | Bio: bio, 27 | } 28 | 29 | return &chatJoinRequestTemp 30 | } 31 | -------------------------------------------------------------------------------- /personalDocument.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PersonalDocument A personal document, containing some information about a user 4 | type PersonalDocument struct { 5 | tdCommon 6 | Files []DatedFile `json:"files"` // List of files containing the pages of the document 7 | Translation []DatedFile `json:"translation"` // List of files containing a certified English translation of the document 8 | } 9 | 10 | // MessageType return the string telegram-type of PersonalDocument 11 | func (personalDocument *PersonalDocument) MessageType() string { 12 | return "personalDocument" 13 | } 14 | 15 | // NewPersonalDocument creates a new PersonalDocument 16 | // 17 | // @param files List of files containing the pages of the document 18 | // @param translation List of files containing a certified English translation of the document 19 | func NewPersonalDocument(files []DatedFile, translation []DatedFile) *PersonalDocument { 20 | personalDocumentTemp := PersonalDocument{ 21 | tdCommon: tdCommon{Type: "personalDocument"}, 22 | Files: files, 23 | Translation: translation, 24 | } 25 | 26 | return &personalDocumentTemp 27 | } 28 | -------------------------------------------------------------------------------- /chatJoinRequestsInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatJoinRequestsInfo Contains information about pending join requests for a chat 4 | type ChatJoinRequestsInfo struct { 5 | tdCommon 6 | TotalCount int32 `json:"total_count"` // Total number of pending join requests 7 | UserIds []int64 `json:"user_ids"` // Identifiers of at most 3 users sent the newest pending join requests 8 | } 9 | 10 | // MessageType return the string telegram-type of ChatJoinRequestsInfo 11 | func (chatJoinRequestsInfo *ChatJoinRequestsInfo) MessageType() string { 12 | return "chatJoinRequestsInfo" 13 | } 14 | 15 | // NewChatJoinRequestsInfo creates a new ChatJoinRequestsInfo 16 | // 17 | // @param totalCount Total number of pending join requests 18 | // @param userIds Identifiers of at most 3 users sent the newest pending join requests 19 | func NewChatJoinRequestsInfo(totalCount int32, userIds []int64) *ChatJoinRequestsInfo { 20 | chatJoinRequestsInfoTemp := ChatJoinRequestsInfo{ 21 | tdCommon: tdCommon{Type: "chatJoinRequestsInfo"}, 22 | TotalCount: totalCount, 23 | UserIds: userIds, 24 | } 25 | 26 | return &chatJoinRequestsInfoTemp 27 | } 28 | -------------------------------------------------------------------------------- /shippingOption.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ShippingOption One shipping option 4 | type ShippingOption struct { 5 | tdCommon 6 | Id string `json:"id"` // Shipping option identifier 7 | Title string `json:"title"` // Option title 8 | PriceParts []LabeledPricePart `json:"price_parts"` // A list of objects used to calculate the total shipping costs 9 | } 10 | 11 | // MessageType return the string telegram-type of ShippingOption 12 | func (shippingOption *ShippingOption) MessageType() string { 13 | return "shippingOption" 14 | } 15 | 16 | // NewShippingOption creates a new ShippingOption 17 | // 18 | // @param id Shipping option identifier 19 | // @param title Option title 20 | // @param priceParts A list of objects used to calculate the total shipping costs 21 | func NewShippingOption(id string, title string, priceParts []LabeledPricePart) *ShippingOption { 22 | shippingOptionTemp := ShippingOption{ 23 | tdCommon: tdCommon{Type: "shippingOption"}, 24 | Id: id, 25 | Title: title, 26 | PriceParts: priceParts, 27 | } 28 | 29 | return &shippingOptionTemp 30 | } 31 | -------------------------------------------------------------------------------- /chatStatisticsInviterInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatStatisticsInviterInfo Contains statistics about number of new members invited by a user 4 | type ChatStatisticsInviterInfo struct { 5 | tdCommon 6 | UserId int64 `json:"user_id"` // User identifier 7 | AddedMemberCount int32 `json:"added_member_count"` // Number of new members invited by the user 8 | } 9 | 10 | // MessageType return the string telegram-type of ChatStatisticsInviterInfo 11 | func (chatStatisticsInviterInfo *ChatStatisticsInviterInfo) MessageType() string { 12 | return "chatStatisticsInviterInfo" 13 | } 14 | 15 | // NewChatStatisticsInviterInfo creates a new ChatStatisticsInviterInfo 16 | // 17 | // @param userId User identifier 18 | // @param addedMemberCount Number of new members invited by the user 19 | func NewChatStatisticsInviterInfo(userId int64, addedMemberCount int32) *ChatStatisticsInviterInfo { 20 | chatStatisticsInviterInfoTemp := ChatStatisticsInviterInfo{ 21 | tdCommon: tdCommon{Type: "chatStatisticsInviterInfo"}, 22 | UserId: userId, 23 | AddedMemberCount: addedMemberCount, 24 | } 25 | 26 | return &chatStatisticsInviterInfoTemp 27 | } 28 | -------------------------------------------------------------------------------- /groupCallVideoSourceGroup.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // GroupCallVideoSourceGroup Describes a group of video synchronization source identifiers 4 | type GroupCallVideoSourceGroup struct { 5 | tdCommon 6 | Semantics string `json:"semantics"` // The semantics of sources, one of "SIM" or "FID" 7 | SourceIds []int32 `json:"source_ids"` // The list of synchronization source identifiers 8 | } 9 | 10 | // MessageType return the string telegram-type of GroupCallVideoSourceGroup 11 | func (groupCallVideoSourceGroup *GroupCallVideoSourceGroup) MessageType() string { 12 | return "groupCallVideoSourceGroup" 13 | } 14 | 15 | // NewGroupCallVideoSourceGroup creates a new GroupCallVideoSourceGroup 16 | // 17 | // @param semantics The semantics of sources, one of "SIM" or "FID" 18 | // @param sourceIds The list of synchronization source identifiers 19 | func NewGroupCallVideoSourceGroup(semantics string, sourceIds []int32) *GroupCallVideoSourceGroup { 20 | groupCallVideoSourceGroupTemp := GroupCallVideoSourceGroup{ 21 | tdCommon: tdCommon{Type: "groupCallVideoSourceGroup"}, 22 | Semantics: semantics, 23 | SourceIds: sourceIds, 24 | } 25 | 26 | return &groupCallVideoSourceGroupTemp 27 | } 28 | -------------------------------------------------------------------------------- /encryptedCredentials.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // EncryptedCredentials Contains encrypted Telegram Passport data credentials 4 | type EncryptedCredentials struct { 5 | tdCommon 6 | Data []byte `json:"data"` // The encrypted credentials 7 | Hash []byte `json:"hash"` // The decrypted data hash 8 | Secret []byte `json:"secret"` // Secret for data decryption, encrypted with the service's public key 9 | } 10 | 11 | // MessageType return the string telegram-type of EncryptedCredentials 12 | func (encryptedCredentials *EncryptedCredentials) MessageType() string { 13 | return "encryptedCredentials" 14 | } 15 | 16 | // NewEncryptedCredentials creates a new EncryptedCredentials 17 | // 18 | // @param data The encrypted credentials 19 | // @param hash The decrypted data hash 20 | // @param secret Secret for data decryption, encrypted with the service's public key 21 | func NewEncryptedCredentials(data []byte, hash []byte, secret []byte) *EncryptedCredentials { 22 | encryptedCredentialsTemp := EncryptedCredentials{ 23 | tdCommon: tdCommon{Type: "encryptedCredentials"}, 24 | Data: data, 25 | Hash: hash, 26 | Secret: secret, 27 | } 28 | 29 | return &encryptedCredentialsTemp 30 | } 31 | -------------------------------------------------------------------------------- /inputPersonalDocument.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // InputPersonalDocument A personal document to be saved to Telegram Passport 4 | type InputPersonalDocument struct { 5 | tdCommon 6 | Files []InputFile `json:"files"` // List of files containing the pages of the document 7 | Translation []InputFile `json:"translation"` // List of files containing a certified English translation of the document 8 | } 9 | 10 | // MessageType return the string telegram-type of InputPersonalDocument 11 | func (inputPersonalDocument *InputPersonalDocument) MessageType() string { 12 | return "inputPersonalDocument" 13 | } 14 | 15 | // NewInputPersonalDocument creates a new InputPersonalDocument 16 | // 17 | // @param files List of files containing the pages of the document 18 | // @param translation List of files containing a certified English translation of the document 19 | func NewInputPersonalDocument(files []InputFile, translation []InputFile) *InputPersonalDocument { 20 | inputPersonalDocumentTemp := InputPersonalDocument{ 21 | tdCommon: tdCommon{Type: "inputPersonalDocument"}, 22 | Files: files, 23 | Translation: translation, 24 | } 25 | 26 | return &inputPersonalDocumentTemp 27 | } 28 | -------------------------------------------------------------------------------- /chatAdministrator.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatAdministrator Contains information about a chat administrator 4 | type ChatAdministrator struct { 5 | tdCommon 6 | UserId int64 `json:"user_id"` // User identifier of the administrator 7 | CustomTitle string `json:"custom_title"` // Custom title of the administrator 8 | IsOwner bool `json:"is_owner"` // True, if the user is the owner of the chat 9 | } 10 | 11 | // MessageType return the string telegram-type of ChatAdministrator 12 | func (chatAdministrator *ChatAdministrator) MessageType() string { 13 | return "chatAdministrator" 14 | } 15 | 16 | // NewChatAdministrator creates a new ChatAdministrator 17 | // 18 | // @param userId User identifier of the administrator 19 | // @param customTitle Custom title of the administrator 20 | // @param isOwner True, if the user is the owner of the chat 21 | func NewChatAdministrator(userId int64, customTitle string, isOwner bool) *ChatAdministrator { 22 | chatAdministratorTemp := ChatAdministrator{ 23 | tdCommon: tdCommon{Type: "chatAdministrator"}, 24 | UserId: userId, 25 | CustomTitle: customTitle, 26 | IsOwner: isOwner, 27 | } 28 | 29 | return &chatAdministratorTemp 30 | } 31 | -------------------------------------------------------------------------------- /messagePosition.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // MessagePosition Contains information about a message in a specific position 4 | type MessagePosition struct { 5 | tdCommon 6 | Position int32 `json:"position"` // 0-based message position in the full list of suitable messages 7 | MessageId int64 `json:"message_id"` // Message identifier 8 | Date int32 `json:"date"` // Point in time (Unix timestamp) when the message was sent 9 | } 10 | 11 | // MessageType return the string telegram-type of MessagePosition 12 | func (messagePosition *MessagePosition) MessageType() string { 13 | return "messagePosition" 14 | } 15 | 16 | // NewMessagePosition creates a new MessagePosition 17 | // 18 | // @param position 0-based message position in the full list of suitable messages 19 | // @param messageId Message identifier 20 | // @param date Point in time (Unix timestamp) when the message was sent 21 | func NewMessagePosition(position int32, messageId int64, date int32) *MessagePosition { 22 | messagePositionTemp := MessagePosition{ 23 | tdCommon: tdCommon{Type: "messagePosition"}, 24 | Position: position, 25 | MessageId: messageId, 26 | Date: date, 27 | } 28 | 29 | return &messagePositionTemp 30 | } 31 | -------------------------------------------------------------------------------- /common.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | type tdCommon struct { 9 | Type string `json:"@type"` 10 | Extra string `json:"@extra"` 11 | } 12 | 13 | // TdMessage is the interface for all messages send and received to/from tdlib 14 | type TdMessage interface { 15 | MessageType() string 16 | } 17 | 18 | // JSONInt64 alias for int64, in order to deal with json big number problem 19 | type JSONInt64 int64 20 | 21 | // UpdateData alias for use in UpdateMsg 22 | type UpdateData map[string]interface{} 23 | 24 | // UpdateMsg is used to unmarshal received json strings into 25 | type UpdateMsg struct { 26 | Data UpdateData 27 | Raw []byte 28 | } 29 | 30 | // MarshalJSON marshals to json 31 | func (jsonInt *JSONInt64) MarshalJSON() ([]byte, error) { 32 | intStr := strconv.FormatInt(int64(*jsonInt), 10) 33 | return []byte(intStr), nil 34 | } 35 | 36 | // UnmarshalJSON unmarshals from json 37 | func (jsonInt *JSONInt64) UnmarshalJSON(b []byte) error { 38 | intStr := string(b) 39 | intStr = strings.Replace(intStr, "\"", "", 2) 40 | jsonBigInt, err := strconv.ParseInt(intStr, 10, 64) 41 | if err != nil { 42 | return err 43 | } 44 | *jsonInt = JSONInt64(jsonBigInt) 45 | return nil 46 | } 47 | -------------------------------------------------------------------------------- /photo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Photo Describes a photo 4 | type Photo struct { 5 | tdCommon 6 | HasStickers bool `json:"has_stickers"` // True, if stickers were added to the photo. The list of corresponding sticker sets can be received using getAttachedStickerSets 7 | Minithumbnail *Minithumbnail `json:"minithumbnail"` // Photo minithumbnail; may be null 8 | Sizes []PhotoSize `json:"sizes"` // Available variants of the photo, in different sizes 9 | } 10 | 11 | // MessageType return the string telegram-type of Photo 12 | func (photo *Photo) MessageType() string { 13 | return "photo" 14 | } 15 | 16 | // NewPhoto creates a new Photo 17 | // 18 | // @param hasStickers True, if stickers were added to the photo. The list of corresponding sticker sets can be received using getAttachedStickerSets 19 | // @param minithumbnail Photo minithumbnail; may be null 20 | // @param sizes Available variants of the photo, in different sizes 21 | func NewPhoto(hasStickers bool, minithumbnail *Minithumbnail, sizes []PhotoSize) *Photo { 22 | photoTemp := Photo{ 23 | tdCommon: tdCommon{Type: "photo"}, 24 | HasStickers: hasStickers, 25 | Minithumbnail: minithumbnail, 26 | Sizes: sizes, 27 | } 28 | 29 | return &photoTemp 30 | } 31 | -------------------------------------------------------------------------------- /proxies.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Proxies Represents a list of proxy servers 9 | type Proxies struct { 10 | tdCommon 11 | Proxies []Proxy `json:"proxies"` // List of proxy servers 12 | } 13 | 14 | // MessageType return the string telegram-type of Proxies 15 | func (proxies *Proxies) MessageType() string { 16 | return "proxies" 17 | } 18 | 19 | // NewProxies creates a new Proxies 20 | // 21 | // @param proxies List of proxy servers 22 | func NewProxies(proxies []Proxy) *Proxies { 23 | proxiesTemp := Proxies{ 24 | tdCommon: tdCommon{Type: "proxies"}, 25 | Proxies: proxies, 26 | } 27 | 28 | return &proxiesTemp 29 | } 30 | 31 | // GetProxies Returns list of proxies that are currently set up. Can be called before authorization 32 | func (client *Client) GetProxies() (*Proxies, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getProxies", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var proxies Proxies 46 | err = json.Unmarshal(result.Raw, &proxies) 47 | return &proxies, err 48 | } 49 | -------------------------------------------------------------------------------- /termsOfService.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // TermsOfService Contains Telegram terms of service 4 | type TermsOfService struct { 5 | tdCommon 6 | Text *FormattedText `json:"text"` // Text of the terms of service 7 | MinUserAge int32 `json:"min_user_age"` // The minimum age of a user to be able to accept the terms; 0 if any 8 | ShowPopup bool `json:"show_popup"` // True, if a blocking popup with terms of service must be shown to the user 9 | } 10 | 11 | // MessageType return the string telegram-type of TermsOfService 12 | func (termsOfService *TermsOfService) MessageType() string { 13 | return "termsOfService" 14 | } 15 | 16 | // NewTermsOfService creates a new TermsOfService 17 | // 18 | // @param text Text of the terms of service 19 | // @param minUserAge The minimum age of a user to be able to accept the terms; 0 if any 20 | // @param showPopup True, if a blocking popup with terms of service must be shown to the user 21 | func NewTermsOfService(text *FormattedText, minUserAge int32, showPopup bool) *TermsOfService { 22 | termsOfServiceTemp := TermsOfService{ 23 | tdCommon: tdCommon{Type: "termsOfService"}, 24 | Text: text, 25 | MinUserAge: minUserAge, 26 | ShowPopup: showPopup, 27 | } 28 | 29 | return &termsOfServiceTemp 30 | } 31 | -------------------------------------------------------------------------------- /statisticalValue.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // StatisticalValue A value with information about its recent changes 4 | type StatisticalValue struct { 5 | tdCommon 6 | Value float64 `json:"value"` // The current value 7 | PreviousValue float64 `json:"previous_value"` // The value for the previous day 8 | GrowthRatePercentage float64 `json:"growth_rate_percentage"` // The growth rate of the value, as a percentage 9 | } 10 | 11 | // MessageType return the string telegram-type of StatisticalValue 12 | func (statisticalValue *StatisticalValue) MessageType() string { 13 | return "statisticalValue" 14 | } 15 | 16 | // NewStatisticalValue creates a new StatisticalValue 17 | // 18 | // @param value The current value 19 | // @param previousValue The value for the previous day 20 | // @param growthRatePercentage The growth rate of the value, as a percentage 21 | func NewStatisticalValue(value float64, previousValue float64, growthRatePercentage float64) *StatisticalValue { 22 | statisticalValueTemp := StatisticalValue{ 23 | tdCommon: tdCommon{Type: "statisticalValue"}, 24 | Value: value, 25 | PreviousValue: previousValue, 26 | GrowthRatePercentage: growthRatePercentage, 27 | } 28 | 29 | return &statisticalValueTemp 30 | } 31 | -------------------------------------------------------------------------------- /animatedChatPhoto.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // AnimatedChatPhoto Animated variant of a chat photo in MPEG4 format 4 | type AnimatedChatPhoto struct { 5 | tdCommon 6 | Length int32 `json:"length"` // Animation width and height 7 | File *File `json:"file"` // Information about the animation file 8 | MainFrameTimestamp float64 `json:"main_frame_timestamp"` // Timestamp of the frame, used as a static chat photo 9 | } 10 | 11 | // MessageType return the string telegram-type of AnimatedChatPhoto 12 | func (animatedChatPhoto *AnimatedChatPhoto) MessageType() string { 13 | return "animatedChatPhoto" 14 | } 15 | 16 | // NewAnimatedChatPhoto creates a new AnimatedChatPhoto 17 | // 18 | // @param length Animation width and height 19 | // @param file Information about the animation file 20 | // @param mainFrameTimestamp Timestamp of the frame, used as a static chat photo 21 | func NewAnimatedChatPhoto(length int32, file *File, mainFrameTimestamp float64) *AnimatedChatPhoto { 22 | animatedChatPhotoTemp := AnimatedChatPhoto{ 23 | tdCommon: tdCommon{Type: "animatedChatPhoto"}, 24 | Length: length, 25 | File: file, 26 | MainFrameTimestamp: mainFrameTimestamp, 27 | } 28 | 29 | return &animatedChatPhotoTemp 30 | } 31 | -------------------------------------------------------------------------------- /animations.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Animations Represents a list of animations 9 | type Animations struct { 10 | tdCommon 11 | Animations []Animation `json:"animations"` // List of animations 12 | } 13 | 14 | // MessageType return the string telegram-type of Animations 15 | func (animations *Animations) MessageType() string { 16 | return "animations" 17 | } 18 | 19 | // NewAnimations creates a new Animations 20 | // 21 | // @param animations List of animations 22 | func NewAnimations(animations []Animation) *Animations { 23 | animationsTemp := Animations{ 24 | tdCommon: tdCommon{Type: "animations"}, 25 | Animations: animations, 26 | } 27 | 28 | return &animationsTemp 29 | } 30 | 31 | // GetSavedAnimations Returns saved animations 32 | func (client *Client) GetSavedAnimations() (*Animations, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getSavedAnimations", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var animations Animations 46 | err = json.Unmarshal(result.Raw, &animations) 47 | return &animations, err 48 | } 49 | -------------------------------------------------------------------------------- /logTags.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // LogTags Contains a list of available TDLib internal log tags 9 | type LogTags struct { 10 | tdCommon 11 | Tags []string `json:"tags"` // List of log tags 12 | } 13 | 14 | // MessageType return the string telegram-type of LogTags 15 | func (logTags *LogTags) MessageType() string { 16 | return "logTags" 17 | } 18 | 19 | // NewLogTags creates a new LogTags 20 | // 21 | // @param tags List of log tags 22 | func NewLogTags(tags []string) *LogTags { 23 | logTagsTemp := LogTags{ 24 | tdCommon: tdCommon{Type: "logTags"}, 25 | Tags: tags, 26 | } 27 | 28 | return &logTagsTemp 29 | } 30 | 31 | // GetLogTags Returns list of available TDLib internal log tags, for example, ["actor", "binlog", "connections", "notifications", "proxy"]. Can be called synchronously 32 | func (client *Client) GetLogTags() (*LogTags, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getLogTags", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var logTags LogTags 46 | err = json.Unmarshal(result.Raw, &logTags) 47 | return &logTags, err 48 | } 49 | -------------------------------------------------------------------------------- /countries.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Countries Contains information about countries 9 | type Countries struct { 10 | tdCommon 11 | Countries []CountryInfo `json:"countries"` // The list of countries 12 | } 13 | 14 | // MessageType return the string telegram-type of Countries 15 | func (countries *Countries) MessageType() string { 16 | return "countries" 17 | } 18 | 19 | // NewCountries creates a new Countries 20 | // 21 | // @param countries The list of countries 22 | func NewCountries(countries []CountryInfo) *Countries { 23 | countriesTemp := Countries{ 24 | tdCommon: tdCommon{Type: "countries"}, 25 | Countries: countries, 26 | } 27 | 28 | return &countriesTemp 29 | } 30 | 31 | // GetCountries Returns information about existing countries. Can be called before authorization 32 | func (client *Client) GetCountries() (*Countries, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getCountries", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var countries Countries 46 | err = json.Unmarshal(result.Raw, &countries) 47 | return &countries, err 48 | } 49 | -------------------------------------------------------------------------------- /testInt.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TestInt A simple object containing a number; for testing only 9 | type TestInt struct { 10 | tdCommon 11 | Value int32 `json:"value"` // Number 12 | } 13 | 14 | // MessageType return the string telegram-type of TestInt 15 | func (testInt *TestInt) MessageType() string { 16 | return "testInt" 17 | } 18 | 19 | // NewTestInt creates a new TestInt 20 | // 21 | // @param value Number 22 | func NewTestInt(value int32) *TestInt { 23 | testIntTemp := TestInt{ 24 | tdCommon: tdCommon{Type: "testInt"}, 25 | Value: value, 26 | } 27 | 28 | return &testIntTemp 29 | } 30 | 31 | // TestSquareInt Returns the squared received number; for testing only. This is an offline method. Can be called before authorization 32 | // @param x Number to square 33 | func (client *Client) TestSquareInt(x int32) (*TestInt, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "testSquareInt", 36 | "x": x, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var testInt TestInt 48 | err = json.Unmarshal(result.Raw, &testInt) 49 | return &testInt, err 50 | } 51 | -------------------------------------------------------------------------------- /tMeURLs.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TMeUrls Contains a list of t.me URLs 9 | type TMeUrls struct { 10 | tdCommon 11 | Urls []TMeUrl `json:"urls"` // List of URLs 12 | } 13 | 14 | // MessageType return the string telegram-type of TMeUrls 15 | func (tMeUrls *TMeUrls) MessageType() string { 16 | return "tMeUrls" 17 | } 18 | 19 | // NewTMeUrls creates a new TMeUrls 20 | // 21 | // @param urls List of URLs 22 | func NewTMeUrls(urls []TMeUrl) *TMeUrls { 23 | tMeUrlsTemp := TMeUrls{ 24 | tdCommon: tdCommon{Type: "tMeUrls"}, 25 | Urls: urls, 26 | } 27 | 28 | return &tMeUrlsTemp 29 | } 30 | 31 | // GetRecentlyVisitedTMeUrls Returns t.me URLs recently visited by a newly registered user 32 | // @param referrer Google Play referrer to identify the user 33 | func (client *Client) GetRecentlyVisitedTMeUrls(referrer string) (*TMeUrls, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getRecentlyVisitedTMeUrls", 36 | "referrer": referrer, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var tMeUrls TMeUrls 48 | err = json.Unmarshal(result.Raw, &tMeUrls) 49 | return &tMeUrls, err 50 | } 51 | -------------------------------------------------------------------------------- /tMeURL.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // TMeUrl Represents a URL linking to an internal Telegram entity 8 | type TMeUrl struct { 9 | tdCommon 10 | Url string `json:"url"` // URL 11 | Type TMeUrlType `json:"type"` // Type of the URL 12 | } 13 | 14 | // MessageType return the string telegram-type of TMeUrl 15 | func (tMeUrl *TMeUrl) MessageType() string { 16 | return "tMeUrl" 17 | } 18 | 19 | // NewTMeUrl creates a new TMeUrl 20 | // 21 | // @param url URL 22 | // @param typeParam Type of the URL 23 | func NewTMeUrl(url string, typeParam TMeUrlType) *TMeUrl { 24 | tMeUrlTemp := TMeUrl{ 25 | tdCommon: tdCommon{Type: "tMeUrl"}, 26 | Url: url, 27 | Type: typeParam, 28 | } 29 | 30 | return &tMeUrlTemp 31 | } 32 | 33 | // UnmarshalJSON unmarshal to json 34 | func (tMeUrl *TMeUrl) UnmarshalJSON(b []byte) error { 35 | var objMap map[string]*json.RawMessage 36 | err := json.Unmarshal(b, &objMap) 37 | if err != nil { 38 | return err 39 | } 40 | tempObj := struct { 41 | tdCommon 42 | Url string `json:"url"` // URL 43 | 44 | }{} 45 | err = json.Unmarshal(b, &tempObj) 46 | if err != nil { 47 | return err 48 | } 49 | 50 | tMeUrl.tdCommon = tempObj.tdCommon 51 | tMeUrl.Url = tempObj.Url 52 | 53 | fieldType, _ := unmarshalTMeUrlType(objMap["type"]) 54 | tMeUrl.Type = fieldType 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /chatInviteLinkMember.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatInviteLinkMember Describes a chat member joined a chat via an invite link 4 | type ChatInviteLinkMember struct { 5 | tdCommon 6 | UserId int64 `json:"user_id"` // User identifier 7 | JoinedChatDate int32 `json:"joined_chat_date"` // Point in time (Unix timestamp) when the user joined the chat 8 | ApproverUserId int64 `json:"approver_user_id"` // User identifier of the chat administrator, approved user join request 9 | } 10 | 11 | // MessageType return the string telegram-type of ChatInviteLinkMember 12 | func (chatInviteLinkMember *ChatInviteLinkMember) MessageType() string { 13 | return "chatInviteLinkMember" 14 | } 15 | 16 | // NewChatInviteLinkMember creates a new ChatInviteLinkMember 17 | // 18 | // @param userId User identifier 19 | // @param joinedChatDate Point in time (Unix timestamp) when the user joined the chat 20 | // @param approverUserId User identifier of the chat administrator, approved user join request 21 | func NewChatInviteLinkMember(userId int64, joinedChatDate int32, approverUserId int64) *ChatInviteLinkMember { 22 | chatInviteLinkMemberTemp := ChatInviteLinkMember{ 23 | tdCommon: tdCommon{Type: "chatInviteLinkMember"}, 24 | UserId: userId, 25 | JoinedChatDate: joinedChatDate, 26 | ApproverUserId: approverUserId, 27 | } 28 | 29 | return &chatInviteLinkMemberTemp 30 | } 31 | -------------------------------------------------------------------------------- /testBytes.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TestBytes A simple object containing a sequence of bytes; for testing only 9 | type TestBytes struct { 10 | tdCommon 11 | Value []byte `json:"value"` // Bytes 12 | } 13 | 14 | // MessageType return the string telegram-type of TestBytes 15 | func (testBytes *TestBytes) MessageType() string { 16 | return "testBytes" 17 | } 18 | 19 | // NewTestBytes creates a new TestBytes 20 | // 21 | // @param value Bytes 22 | func NewTestBytes(value []byte) *TestBytes { 23 | testBytesTemp := TestBytes{ 24 | tdCommon: tdCommon{Type: "testBytes"}, 25 | Value: value, 26 | } 27 | 28 | return &testBytesTemp 29 | } 30 | 31 | // TestCallBytes Returns the received bytes; for testing only. This is an offline method. Can be called before authorization 32 | // @param x Bytes to return 33 | func (client *Client) TestCallBytes(x []byte) (*TestBytes, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "testCallBytes", 36 | "x": x, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var testBytes TestBytes 48 | err = json.Unmarshal(result.Raw, &testBytes) 49 | return &testBytes, err 50 | } 51 | -------------------------------------------------------------------------------- /location.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Location Describes a location on planet Earth 4 | type Location struct { 5 | tdCommon 6 | Latitude float64 `json:"latitude"` // Latitude of the location in degrees; as defined by the sender 7 | Longitude float64 `json:"longitude"` // Longitude of the location, in degrees; as defined by the sender 8 | HorizontalAccuracy float64 `json:"horizontal_accuracy"` // The estimated horizontal accuracy of the location, in meters; as defined by the sender. 0 if unknown 9 | } 10 | 11 | // MessageType return the string telegram-type of Location 12 | func (location *Location) MessageType() string { 13 | return "location" 14 | } 15 | 16 | // NewLocation creates a new Location 17 | // 18 | // @param latitude Latitude of the location in degrees; as defined by the sender 19 | // @param longitude Longitude of the location, in degrees; as defined by the sender 20 | // @param horizontalAccuracy The estimated horizontal accuracy of the location, in meters; as defined by the sender. 0 if unknown 21 | func NewLocation(latitude float64, longitude float64, horizontalAccuracy float64) *Location { 22 | locationTemp := Location{ 23 | tdCommon: tdCommon{Type: "location"}, 24 | Latitude: latitude, 25 | Longitude: longitude, 26 | HorizontalAccuracy: horizontalAccuracy, 27 | } 28 | 29 | return &locationTemp 30 | } 31 | -------------------------------------------------------------------------------- /chatInviteLinkCount.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatInviteLinkCount Describes a chat administrator with a number of active and revoked chat invite links 4 | type ChatInviteLinkCount struct { 5 | tdCommon 6 | UserId int64 `json:"user_id"` // Administrator's user identifier 7 | InviteLinkCount int32 `json:"invite_link_count"` // Number of active invite links 8 | RevokedInviteLinkCount int32 `json:"revoked_invite_link_count"` // Number of revoked invite links 9 | } 10 | 11 | // MessageType return the string telegram-type of ChatInviteLinkCount 12 | func (chatInviteLinkCount *ChatInviteLinkCount) MessageType() string { 13 | return "chatInviteLinkCount" 14 | } 15 | 16 | // NewChatInviteLinkCount creates a new ChatInviteLinkCount 17 | // 18 | // @param userId Administrator's user identifier 19 | // @param inviteLinkCount Number of active invite links 20 | // @param revokedInviteLinkCount Number of revoked invite links 21 | func NewChatInviteLinkCount(userId int64, inviteLinkCount int32, revokedInviteLinkCount int32) *ChatInviteLinkCount { 22 | chatInviteLinkCountTemp := ChatInviteLinkCount{ 23 | tdCommon: tdCommon{Type: "chatInviteLinkCount"}, 24 | UserId: userId, 25 | InviteLinkCount: inviteLinkCount, 26 | RevokedInviteLinkCount: revokedInviteLinkCount, 27 | } 28 | 29 | return &chatInviteLinkCountTemp 30 | } 31 | -------------------------------------------------------------------------------- /testString.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TestString A simple object containing a string; for testing only 9 | type TestString struct { 10 | tdCommon 11 | Value string `json:"value"` // String 12 | } 13 | 14 | // MessageType return the string telegram-type of TestString 15 | func (testString *TestString) MessageType() string { 16 | return "testString" 17 | } 18 | 19 | // NewTestString creates a new TestString 20 | // 21 | // @param value String 22 | func NewTestString(value string) *TestString { 23 | testStringTemp := TestString{ 24 | tdCommon: tdCommon{Type: "testString"}, 25 | Value: value, 26 | } 27 | 28 | return &testStringTemp 29 | } 30 | 31 | // TestCallString Returns the received string; for testing only. This is an offline method. Can be called before authorization 32 | // @param x String to return 33 | func (client *Client) TestCallString(x string) (*TestString, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "testCallString", 36 | "x": x, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var testString TestString 48 | err = json.Unmarshal(result.Raw, &testString) 49 | return &testString, err 50 | } 51 | -------------------------------------------------------------------------------- /updates.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Updates Contains a list of updates 9 | type Updates struct { 10 | tdCommon 11 | Updates []Update `json:"updates"` // List of updates 12 | } 13 | 14 | // MessageType return the string telegram-type of Updates 15 | func (updates *Updates) MessageType() string { 16 | return "updates" 17 | } 18 | 19 | // NewUpdates creates a new Updates 20 | // 21 | // @param updates List of updates 22 | func NewUpdates(updates []Update) *Updates { 23 | updatesTemp := Updates{ 24 | tdCommon: tdCommon{Type: "updates"}, 25 | Updates: updates, 26 | } 27 | 28 | return &updatesTemp 29 | } 30 | 31 | // 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 32 | func (client *Client) GetCurrentState() (*Updates, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getCurrentState", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var updates Updates 46 | err = json.Unmarshal(result.Raw, &updates) 47 | return &updates, err 48 | } 49 | -------------------------------------------------------------------------------- /chatLists.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ChatLists Contains a list of chat lists 9 | type ChatLists struct { 10 | tdCommon 11 | ChatLists []ChatList `json:"chat_lists"` // List of chat lists 12 | } 13 | 14 | // MessageType return the string telegram-type of ChatLists 15 | func (chatLists *ChatLists) MessageType() string { 16 | return "chatLists" 17 | } 18 | 19 | // NewChatLists creates a new ChatLists 20 | // 21 | // @param chatLists List of chat lists 22 | func NewChatLists(chatLists []ChatList) *ChatLists { 23 | chatListsTemp := ChatLists{ 24 | tdCommon: tdCommon{Type: "chatLists"}, 25 | ChatLists: chatLists, 26 | } 27 | 28 | return &chatListsTemp 29 | } 30 | 31 | // GetChatListsToAddChat Returns chat lists to which the chat can be added. This is an offline request 32 | // @param chatId Chat identifier 33 | func (client *Client) GetChatListsToAddChat(chatId int64) (*ChatLists, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getChatListsToAddChat", 36 | "chat_id": chatId, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var chatLists ChatLists 48 | err = json.Unmarshal(result.Raw, &chatLists) 49 | return &chatLists, err 50 | } 51 | -------------------------------------------------------------------------------- /seconds.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Seconds Contains a value representing a number of seconds 9 | type Seconds struct { 10 | tdCommon 11 | Seconds float64 `json:"seconds"` // Number of seconds 12 | } 13 | 14 | // MessageType return the string telegram-type of Seconds 15 | func (seconds *Seconds) MessageType() string { 16 | return "seconds" 17 | } 18 | 19 | // NewSeconds creates a new Seconds 20 | // 21 | // @param seconds Number of seconds 22 | func NewSeconds(seconds float64) *Seconds { 23 | secondsTemp := Seconds{ 24 | tdCommon: tdCommon{Type: "seconds"}, 25 | Seconds: seconds, 26 | } 27 | 28 | return &secondsTemp 29 | } 30 | 31 | // PingProxy Computes time needed to receive a response from a Telegram server through a proxy. Can be called before authorization 32 | // @param proxyId Proxy identifier. Use 0 to ping a Telegram server without a proxy 33 | func (client *Client) PingProxy(proxyId int32) (*Seconds, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "pingProxy", 36 | "proxy_id": proxyId, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var seconds Seconds 48 | err = json.Unmarshal(result.Raw, &seconds) 49 | return &seconds, err 50 | } 51 | -------------------------------------------------------------------------------- /voiceNote.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // 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 4 | type VoiceNote struct { 5 | tdCommon 6 | Duration int32 `json:"duration"` // Duration of the voice note, in seconds; as defined by the sender 7 | Waveform []byte `json:"waveform"` // A waveform representation of the voice note in 5-bit format 8 | MimeType string `json:"mime_type"` // MIME type of the file; as defined by the sender 9 | Voice *File `json:"voice"` // File containing the voice note 10 | } 11 | 12 | // MessageType return the string telegram-type of VoiceNote 13 | func (voiceNote *VoiceNote) MessageType() string { 14 | return "voiceNote" 15 | } 16 | 17 | // NewVoiceNote creates a new VoiceNote 18 | // 19 | // @param duration Duration of the voice note, in seconds; as defined by the sender 20 | // @param waveform A waveform representation of the voice note in 5-bit format 21 | // @param mimeType MIME type of the file; as defined by the sender 22 | // @param voice File containing the voice note 23 | func NewVoiceNote(duration int32, waveform []byte, mimeType string, voice *File) *VoiceNote { 24 | voiceNoteTemp := VoiceNote{ 25 | tdCommon: tdCommon{Type: "voiceNote"}, 26 | Duration: duration, 27 | Waveform: waveform, 28 | MimeType: mimeType, 29 | Voice: voice, 30 | } 31 | 32 | return &voiceNoteTemp 33 | } 34 | -------------------------------------------------------------------------------- /hashtags.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Hashtags Contains a list of hashtags 9 | type Hashtags struct { 10 | tdCommon 11 | Hashtags []string `json:"hashtags"` // A list of hashtags 12 | } 13 | 14 | // MessageType return the string telegram-type of Hashtags 15 | func (hashtags *Hashtags) MessageType() string { 16 | return "hashtags" 17 | } 18 | 19 | // NewHashtags creates a new Hashtags 20 | // 21 | // @param hashtags A list of hashtags 22 | func NewHashtags(hashtags []string) *Hashtags { 23 | hashtagsTemp := Hashtags{ 24 | tdCommon: tdCommon{Type: "hashtags"}, 25 | Hashtags: hashtags, 26 | } 27 | 28 | return &hashtagsTemp 29 | } 30 | 31 | // SearchHashtags Searches for recently used hashtags by their prefix 32 | // @param prefix Hashtag prefix to search for 33 | // @param limit The maximum number of hashtags to be returned 34 | func (client *Client) SearchHashtags(prefix string, limit int32) (*Hashtags, error) { 35 | result, err := client.SendAndCatch(UpdateData{ 36 | "@type": "searchHashtags", 37 | "prefix": prefix, 38 | "limit": limit, 39 | }) 40 | 41 | if err != nil { 42 | return nil, err 43 | } 44 | 45 | if result.Data["@type"].(string) == "error" { 46 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 47 | } 48 | 49 | var hashtags Hashtags 50 | err = json.Unmarshal(result.Raw, &hashtags) 51 | return &hashtags, err 52 | } 53 | -------------------------------------------------------------------------------- /address.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Address Describes an address 4 | type Address struct { 5 | tdCommon 6 | CountryCode string `json:"country_code"` // A two-letter ISO 3166-1 alpha-2 country code 7 | State string `json:"state"` // State, if applicable 8 | City string `json:"city"` // City 9 | StreetLine1 string `json:"street_line1"` // First line of the address 10 | StreetLine2 string `json:"street_line2"` // Second line of the address 11 | PostalCode string `json:"postal_code"` // Address postal code 12 | } 13 | 14 | // MessageType return the string telegram-type of Address 15 | func (address *Address) MessageType() string { 16 | return "address" 17 | } 18 | 19 | // NewAddress creates a new Address 20 | // 21 | // @param countryCode A two-letter ISO 3166-1 alpha-2 country code 22 | // @param state State, if applicable 23 | // @param city City 24 | // @param streetLine1 First line of the address 25 | // @param streetLine2 Second line of the address 26 | // @param postalCode Address postal code 27 | func NewAddress(countryCode string, state string, city string, streetLine1 string, streetLine2 string, postalCode string) *Address { 28 | addressTemp := Address{ 29 | tdCommon: tdCommon{Type: "address"}, 30 | CountryCode: countryCode, 31 | State: state, 32 | City: city, 33 | StreetLine1: streetLine1, 34 | StreetLine2: streetLine2, 35 | PostalCode: postalCode, 36 | } 37 | 38 | return &addressTemp 39 | } 40 | -------------------------------------------------------------------------------- /callID.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // CallId Contains the call identifier 9 | type CallId struct { 10 | tdCommon 11 | Id int32 `json:"id"` // Call identifier 12 | } 13 | 14 | // MessageType return the string telegram-type of CallId 15 | func (callId *CallId) MessageType() string { 16 | return "callId" 17 | } 18 | 19 | // NewCallId creates a new CallId 20 | // 21 | // @param id Call identifier 22 | func NewCallId(id int32) *CallId { 23 | callIdTemp := CallId{ 24 | tdCommon: tdCommon{Type: "callId"}, 25 | Id: id, 26 | } 27 | 28 | return &callIdTemp 29 | } 30 | 31 | // CreateCall Creates a new call 32 | // @param userId Identifier of the user to be called 33 | // @param protocol The call protocols supported by the application 34 | // @param isVideo True, if a video call needs to be created 35 | func (client *Client) CreateCall(userId int64, protocol *CallProtocol, isVideo bool) (*CallId, error) { 36 | result, err := client.SendAndCatch(UpdateData{ 37 | "@type": "createCall", 38 | "user_id": userId, 39 | "protocol": protocol, 40 | "is_video": isVideo, 41 | }) 42 | 43 | if err != nil { 44 | return nil, err 45 | } 46 | 47 | if result.Data["@type"].(string) == "error" { 48 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 49 | } 50 | 51 | var callId CallId 52 | err = json.Unmarshal(result.Raw, &callId) 53 | return &callId, err 54 | } 55 | -------------------------------------------------------------------------------- /contact.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Contact Describes a user contact 4 | type Contact struct { 5 | tdCommon 6 | PhoneNumber string `json:"phone_number"` // Phone number of the user 7 | FirstName string `json:"first_name"` // First name of the user; 1-255 characters in length 8 | LastName string `json:"last_name"` // Last name of the user 9 | Vcard string `json:"vcard"` // Additional data about the user in a form of vCard; 0-2048 bytes in length 10 | UserId int64 `json:"user_id"` // Identifier of the user, if known; otherwise 0 11 | } 12 | 13 | // MessageType return the string telegram-type of Contact 14 | func (contact *Contact) MessageType() string { 15 | return "contact" 16 | } 17 | 18 | // NewContact creates a new Contact 19 | // 20 | // @param phoneNumber Phone number of the user 21 | // @param firstName First name of the user; 1-255 characters in length 22 | // @param lastName Last name of the user 23 | // @param vcard Additional data about the user in a form of vCard; 0-2048 bytes in length 24 | // @param userId Identifier of the user, if known; otherwise 0 25 | func NewContact(phoneNumber string, firstName string, lastName string, vcard string, userId int64) *Contact { 26 | contactTemp := Contact{ 27 | tdCommon: tdCommon{Type: "contact"}, 28 | PhoneNumber: phoneNumber, 29 | FirstName: firstName, 30 | LastName: lastName, 31 | Vcard: vcard, 32 | UserId: userId, 33 | } 34 | 35 | return &contactTemp 36 | } 37 | -------------------------------------------------------------------------------- /chatStatisticsMessageInteractionInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatStatisticsMessageInteractionInfo Contains statistics about interactions with a message 4 | type ChatStatisticsMessageInteractionInfo struct { 5 | tdCommon 6 | MessageId int64 `json:"message_id"` // Message identifier 7 | ViewCount int32 `json:"view_count"` // Number of times the message was viewed 8 | ForwardCount int32 `json:"forward_count"` // Number of times the message was forwarded 9 | } 10 | 11 | // MessageType return the string telegram-type of ChatStatisticsMessageInteractionInfo 12 | func (chatStatisticsMessageInteractionInfo *ChatStatisticsMessageInteractionInfo) MessageType() string { 13 | return "chatStatisticsMessageInteractionInfo" 14 | } 15 | 16 | // NewChatStatisticsMessageInteractionInfo creates a new ChatStatisticsMessageInteractionInfo 17 | // 18 | // @param messageId Message identifier 19 | // @param viewCount Number of times the message was viewed 20 | // @param forwardCount Number of times the message was forwarded 21 | func NewChatStatisticsMessageInteractionInfo(messageId int64, viewCount int32, forwardCount int32) *ChatStatisticsMessageInteractionInfo { 22 | chatStatisticsMessageInteractionInfoTemp := ChatStatisticsMessageInteractionInfo{ 23 | tdCommon: tdCommon{Type: "chatStatisticsMessageInteractionInfo"}, 24 | MessageId: messageId, 25 | ViewCount: viewCount, 26 | ForwardCount: forwardCount, 27 | } 28 | 29 | return &chatStatisticsMessageInteractionInfoTemp 30 | } 31 | -------------------------------------------------------------------------------- /backgrounds.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Backgrounds Contains a list of backgrounds 9 | type Backgrounds struct { 10 | tdCommon 11 | Backgrounds []Background `json:"backgrounds"` // A list of backgrounds 12 | } 13 | 14 | // MessageType return the string telegram-type of Backgrounds 15 | func (backgrounds *Backgrounds) MessageType() string { 16 | return "backgrounds" 17 | } 18 | 19 | // NewBackgrounds creates a new Backgrounds 20 | // 21 | // @param backgrounds A list of backgrounds 22 | func NewBackgrounds(backgrounds []Background) *Backgrounds { 23 | backgroundsTemp := Backgrounds{ 24 | tdCommon: tdCommon{Type: "backgrounds"}, 25 | Backgrounds: backgrounds, 26 | } 27 | 28 | return &backgroundsTemp 29 | } 30 | 31 | // GetBackgrounds Returns backgrounds installed by the user 32 | // @param forDarkTheme True, if the backgrounds must be ordered for dark theme 33 | func (client *Client) GetBackgrounds(forDarkTheme bool) (*Backgrounds, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getBackgrounds", 36 | "for_dark_theme": forDarkTheme, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var backgrounds Backgrounds 48 | err = json.Unmarshal(result.Raw, &backgrounds) 49 | return &backgrounds, err 50 | } 51 | -------------------------------------------------------------------------------- /testVectorInt.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TestVectorInt A simple object containing a vector of numbers; for testing only 9 | type TestVectorInt struct { 10 | tdCommon 11 | Value []int32 `json:"value"` // Vector of numbers 12 | } 13 | 14 | // MessageType return the string telegram-type of TestVectorInt 15 | func (testVectorInt *TestVectorInt) MessageType() string { 16 | return "testVectorInt" 17 | } 18 | 19 | // NewTestVectorInt creates a new TestVectorInt 20 | // 21 | // @param value Vector of numbers 22 | func NewTestVectorInt(value []int32) *TestVectorInt { 23 | testVectorIntTemp := TestVectorInt{ 24 | tdCommon: tdCommon{Type: "testVectorInt"}, 25 | Value: value, 26 | } 27 | 28 | return &testVectorIntTemp 29 | } 30 | 31 | // TestCallVectorInt Returns the received vector of numbers; for testing only. This is an offline method. Can be called before authorization 32 | // @param x Vector of numbers to return 33 | func (client *Client) TestCallVectorInt(x []int32) (*TestVectorInt, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "testCallVectorInt", 36 | "x": x, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var testVectorInt TestVectorInt 48 | err = json.Unmarshal(result.Raw, &testVectorInt) 49 | return &testVectorInt, err 50 | } 51 | -------------------------------------------------------------------------------- /chatStatisticsMessageSenderInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatStatisticsMessageSenderInfo Contains statistics about messages sent by a user 4 | type ChatStatisticsMessageSenderInfo struct { 5 | tdCommon 6 | UserId int64 `json:"user_id"` // User identifier 7 | SentMessageCount int32 `json:"sent_message_count"` // Number of sent messages 8 | AverageCharacterCount int32 `json:"average_character_count"` // Average number of characters in sent messages; 0 if unknown 9 | } 10 | 11 | // MessageType return the string telegram-type of ChatStatisticsMessageSenderInfo 12 | func (chatStatisticsMessageSenderInfo *ChatStatisticsMessageSenderInfo) MessageType() string { 13 | return "chatStatisticsMessageSenderInfo" 14 | } 15 | 16 | // NewChatStatisticsMessageSenderInfo creates a new ChatStatisticsMessageSenderInfo 17 | // 18 | // @param userId User identifier 19 | // @param sentMessageCount Number of sent messages 20 | // @param averageCharacterCount Average number of characters in sent messages; 0 if unknown 21 | func NewChatStatisticsMessageSenderInfo(userId int64, sentMessageCount int32, averageCharacterCount int32) *ChatStatisticsMessageSenderInfo { 22 | chatStatisticsMessageSenderInfoTemp := ChatStatisticsMessageSenderInfo{ 23 | tdCommon: tdCommon{Type: "chatStatisticsMessageSenderInfo"}, 24 | UserId: userId, 25 | SentMessageCount: sentMessageCount, 26 | AverageCharacterCount: averageCharacterCount, 27 | } 28 | 29 | return &chatStatisticsMessageSenderInfoTemp 30 | } 31 | -------------------------------------------------------------------------------- /connectedWebsites.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ConnectedWebsites Contains a list of websites the current user is logged in with Telegram 9 | type ConnectedWebsites struct { 10 | tdCommon 11 | Websites []ConnectedWebsite `json:"websites"` // List of connected websites 12 | } 13 | 14 | // MessageType return the string telegram-type of ConnectedWebsites 15 | func (connectedWebsites *ConnectedWebsites) MessageType() string { 16 | return "connectedWebsites" 17 | } 18 | 19 | // NewConnectedWebsites creates a new ConnectedWebsites 20 | // 21 | // @param websites List of connected websites 22 | func NewConnectedWebsites(websites []ConnectedWebsite) *ConnectedWebsites { 23 | connectedWebsitesTemp := ConnectedWebsites{ 24 | tdCommon: tdCommon{Type: "connectedWebsites"}, 25 | Websites: websites, 26 | } 27 | 28 | return &connectedWebsitesTemp 29 | } 30 | 31 | // GetConnectedWebsites Returns all website where the current user used Telegram to log in 32 | func (client *Client) GetConnectedWebsites() (*ConnectedWebsites, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getConnectedWebsites", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var connectedWebsites ConnectedWebsites 46 | err = json.Unmarshal(result.Raw, &connectedWebsites) 47 | return &connectedWebsites, err 48 | } 49 | -------------------------------------------------------------------------------- /databaseStatistics.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // DatabaseStatistics Contains database statistics 9 | type DatabaseStatistics struct { 10 | tdCommon 11 | Statistics string `json:"statistics"` // Database statistics in an unspecified human-readable format 12 | } 13 | 14 | // MessageType return the string telegram-type of DatabaseStatistics 15 | func (databaseStatistics *DatabaseStatistics) MessageType() string { 16 | return "databaseStatistics" 17 | } 18 | 19 | // NewDatabaseStatistics creates a new DatabaseStatistics 20 | // 21 | // @param statistics Database statistics in an unspecified human-readable format 22 | func NewDatabaseStatistics(statistics string) *DatabaseStatistics { 23 | databaseStatisticsTemp := DatabaseStatistics{ 24 | tdCommon: tdCommon{Type: "databaseStatistics"}, 25 | Statistics: statistics, 26 | } 27 | 28 | return &databaseStatisticsTemp 29 | } 30 | 31 | // GetDatabaseStatistics Returns database statistics 32 | func (client *Client) GetDatabaseStatistics() (*DatabaseStatistics, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getDatabaseStatistics", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var databaseStatistics DatabaseStatistics 46 | err = json.Unmarshal(result.Raw, &databaseStatistics) 47 | return &databaseStatistics, err 48 | } 49 | -------------------------------------------------------------------------------- /countryInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // CountryInfo Contains information about a country 4 | type CountryInfo struct { 5 | tdCommon 6 | CountryCode string `json:"country_code"` // A two-letter ISO 3166-1 alpha-2 country code 7 | Name string `json:"name"` // Native name of the country 8 | EnglishName string `json:"english_name"` // English name of the country 9 | IsHidden bool `json:"is_hidden"` // True, if the country must be hidden from the list of all countries 10 | CallingCodes []string `json:"calling_codes"` // List of country calling codes 11 | } 12 | 13 | // MessageType return the string telegram-type of CountryInfo 14 | func (countryInfo *CountryInfo) MessageType() string { 15 | return "countryInfo" 16 | } 17 | 18 | // NewCountryInfo creates a new CountryInfo 19 | // 20 | // @param countryCode A two-letter ISO 3166-1 alpha-2 country code 21 | // @param name Native name of the country 22 | // @param englishName English name of the country 23 | // @param isHidden True, if the country must be hidden from the list of all countries 24 | // @param callingCodes List of country calling codes 25 | func NewCountryInfo(countryCode string, name string, englishName string, isHidden bool, callingCodes []string) *CountryInfo { 26 | countryInfoTemp := CountryInfo{ 27 | tdCommon: tdCommon{Type: "countryInfo"}, 28 | CountryCode: countryCode, 29 | Name: name, 30 | EnglishName: englishName, 31 | IsHidden: isHidden, 32 | CallingCodes: callingCodes, 33 | } 34 | 35 | return &countryInfoTemp 36 | } 37 | -------------------------------------------------------------------------------- /storageStatisticsByChat.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // StorageStatisticsByChat Contains the storage usage statistics for a specific chat 4 | type StorageStatisticsByChat struct { 5 | tdCommon 6 | ChatId int64 `json:"chat_id"` // Chat identifier; 0 if none 7 | Size int64 `json:"size"` // Total size of the files in the chat, in bytes 8 | Count int32 `json:"count"` // Total number of files in the chat 9 | ByFileType []StorageStatisticsByFileType `json:"by_file_type"` // Statistics split by file types 10 | } 11 | 12 | // MessageType return the string telegram-type of StorageStatisticsByChat 13 | func (storageStatisticsByChat *StorageStatisticsByChat) MessageType() string { 14 | return "storageStatisticsByChat" 15 | } 16 | 17 | // NewStorageStatisticsByChat creates a new StorageStatisticsByChat 18 | // 19 | // @param chatId Chat identifier; 0 if none 20 | // @param size Total size of the files in the chat, in bytes 21 | // @param count Total number of files in the chat 22 | // @param byFileType Statistics split by file types 23 | func NewStorageStatisticsByChat(chatId int64, size int64, count int32, byFileType []StorageStatisticsByFileType) *StorageStatisticsByChat { 24 | storageStatisticsByChatTemp := StorageStatisticsByChat{ 25 | tdCommon: tdCommon{Type: "storageStatisticsByChat"}, 26 | ChatId: chatId, 27 | Size: size, 28 | Count: count, 29 | ByFileType: byFileType, 30 | } 31 | 32 | return &storageStatisticsByChatTemp 33 | } 34 | -------------------------------------------------------------------------------- /accountTTL.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // AccountTtl Contains information about the period of inactivity after which the current user's account will automatically be deleted 9 | type AccountTtl struct { 10 | tdCommon 11 | Days int32 `json:"days"` // Number of days of inactivity before the account will be flagged for deletion; 30-366 days 12 | } 13 | 14 | // MessageType return the string telegram-type of AccountTtl 15 | func (accountTtl *AccountTtl) MessageType() string { 16 | return "accountTtl" 17 | } 18 | 19 | // NewAccountTtl creates a new AccountTtl 20 | // 21 | // @param days Number of days of inactivity before the account will be flagged for deletion; 30-366 days 22 | func NewAccountTtl(days int32) *AccountTtl { 23 | accountTtlTemp := AccountTtl{ 24 | tdCommon: tdCommon{Type: "accountTtl"}, 25 | Days: days, 26 | } 27 | 28 | return &accountTtlTemp 29 | } 30 | 31 | // GetAccountTtl Returns the period of inactivity after which the account of the current user will automatically be deleted 32 | func (client *Client) GetAccountTtl() (*AccountTtl, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getAccountTtl", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var accountTtl AccountTtl 46 | err = json.Unmarshal(result.Raw, &accountTtl) 47 | return &accountTtl, err 48 | } 49 | -------------------------------------------------------------------------------- /textEntities.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TextEntities Contains a list of text entities 9 | type TextEntities struct { 10 | tdCommon 11 | Entities []TextEntity `json:"entities"` // List of text entities 12 | } 13 | 14 | // MessageType return the string telegram-type of TextEntities 15 | func (textEntities *TextEntities) MessageType() string { 16 | return "textEntities" 17 | } 18 | 19 | // NewTextEntities creates a new TextEntities 20 | // 21 | // @param entities List of text entities 22 | func NewTextEntities(entities []TextEntity) *TextEntities { 23 | textEntitiesTemp := TextEntities{ 24 | tdCommon: tdCommon{Type: "textEntities"}, 25 | Entities: entities, 26 | } 27 | 28 | return &textEntitiesTemp 29 | } 30 | 31 | // GetTextEntities Returns all entities (mentions, hashtags, cashtags, bot commands, bank card numbers, URLs, and email addresses) contained in the text. Can be called synchronously 32 | // @param text The text in which to look for entites 33 | func (client *Client) GetTextEntities(text string) (*TextEntities, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getTextEntities", 36 | "text": text, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var textEntities TextEntities 48 | err = json.Unmarshal(result.Raw, &textEntities) 49 | return &textEntities, err 50 | } 51 | -------------------------------------------------------------------------------- /jsonObjectMember.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // JsonObjectMember Represents one member of a JSON object 8 | type JsonObjectMember struct { 9 | tdCommon 10 | Key string `json:"key"` // Member's key 11 | Value JsonValue `json:"value"` // Member's value 12 | } 13 | 14 | // MessageType return the string telegram-type of JsonObjectMember 15 | func (jsonObjectMember *JsonObjectMember) MessageType() string { 16 | return "jsonObjectMember" 17 | } 18 | 19 | // NewJsonObjectMember creates a new JsonObjectMember 20 | // 21 | // @param key Member's key 22 | // @param value Member's value 23 | func NewJsonObjectMember(key string, value JsonValue) *JsonObjectMember { 24 | jsonObjectMemberTemp := JsonObjectMember{ 25 | tdCommon: tdCommon{Type: "jsonObjectMember"}, 26 | Key: key, 27 | Value: value, 28 | } 29 | 30 | return &jsonObjectMemberTemp 31 | } 32 | 33 | // UnmarshalJSON unmarshal to json 34 | func (jsonObjectMember *JsonObjectMember) UnmarshalJSON(b []byte) error { 35 | var objMap map[string]*json.RawMessage 36 | err := json.Unmarshal(b, &objMap) 37 | if err != nil { 38 | return err 39 | } 40 | tempObj := struct { 41 | tdCommon 42 | Key string `json:"key"` // Member's key 43 | 44 | }{} 45 | err = json.Unmarshal(b, &tempObj) 46 | if err != nil { 47 | return err 48 | } 49 | 50 | jsonObjectMember.tdCommon = tempObj.tdCommon 51 | jsonObjectMember.Key = tempObj.Key 52 | 53 | fieldValue, _ := unmarshalJsonValue(objMap["value"]) 54 | jsonObjectMember.Value = fieldValue 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /testVectorString.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TestVectorString A simple object containing a vector of strings; for testing only 9 | type TestVectorString struct { 10 | tdCommon 11 | Value []string `json:"value"` // Vector of strings 12 | } 13 | 14 | // MessageType return the string telegram-type of TestVectorString 15 | func (testVectorString *TestVectorString) MessageType() string { 16 | return "testVectorString" 17 | } 18 | 19 | // NewTestVectorString creates a new TestVectorString 20 | // 21 | // @param value Vector of strings 22 | func NewTestVectorString(value []string) *TestVectorString { 23 | testVectorStringTemp := TestVectorString{ 24 | tdCommon: tdCommon{Type: "testVectorString"}, 25 | Value: value, 26 | } 27 | 28 | return &testVectorStringTemp 29 | } 30 | 31 | // TestCallVectorString Returns the received vector of strings; for testing only. This is an offline method. Can be called before authorization 32 | // @param x Vector of strings to return 33 | func (client *Client) TestCallVectorString(x []string) (*TestVectorString, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "testCallVectorString", 36 | "x": x, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var testVectorString TestVectorString 48 | err = json.Unmarshal(result.Raw, &testVectorString) 49 | return &testVectorString, err 50 | } 51 | -------------------------------------------------------------------------------- /passportElements.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // PassportElements Contains information about saved Telegram Passport elements 9 | type PassportElements struct { 10 | tdCommon 11 | Elements []PassportElement `json:"elements"` // Telegram Passport elements 12 | } 13 | 14 | // MessageType return the string telegram-type of PassportElements 15 | func (passportElements *PassportElements) MessageType() string { 16 | return "passportElements" 17 | } 18 | 19 | // NewPassportElements creates a new PassportElements 20 | // 21 | // @param elements Telegram Passport elements 22 | func NewPassportElements(elements []PassportElement) *PassportElements { 23 | passportElementsTemp := PassportElements{ 24 | tdCommon: tdCommon{Type: "passportElements"}, 25 | Elements: elements, 26 | } 27 | 28 | return &passportElementsTemp 29 | } 30 | 31 | // GetAllPassportElements Returns all available Telegram Passport elements 32 | // @param password Password of the current user 33 | func (client *Client) GetAllPassportElements(password string) (*PassportElements, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getAllPassportElements", 36 | "password": password, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var passportElements PassportElements 48 | err = json.Unmarshal(result.Raw, &passportElements) 49 | return &passportElements, err 50 | } 51 | -------------------------------------------------------------------------------- /examples/authorization/botAuthorization.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/c0re100/go-tdlib" 7 | ) 8 | 9 | const botToken = "" 10 | 11 | func main() { 12 | tdlib.SetLogVerbosityLevel(1) 13 | tdlib.SetFilePath("./errors.txt") 14 | 15 | // Create new instance of client 16 | client := tdlib.NewClient(tdlib.Config{ 17 | APIID: "187786", 18 | APIHash: "e782045df67ba48e441ccb105da8fc85", 19 | SystemLanguageCode: "en", 20 | DeviceModel: "Server", 21 | SystemVersion: "1.0.0", 22 | ApplicationVersion: "1.0.0", 23 | UseMessageDatabase: true, 24 | UseFileDatabase: true, 25 | UseChatInfoDatabase: true, 26 | UseTestDataCenter: false, 27 | DatabaseDirectory: "./tdlib-db", 28 | FileDirectory: "./tdlib-files", 29 | IgnoreFileNames: false, 30 | }) 31 | 32 | for { 33 | currentState, _ := client.Authorize() 34 | if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPhoneNumberType { 35 | _, err := client.CheckAuthenticationBotToken(botToken) 36 | if err != nil { 37 | fmt.Printf("Error check bot token: %v", err) 38 | return 39 | } 40 | } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateReadyType { 41 | fmt.Println("Authorization Ready! Let's rock") 42 | break 43 | } 44 | } 45 | 46 | // rawUpdates gets all updates comming from tdlib 47 | rawUpdates := client.GetRawUpdatesChannel(100) 48 | for update := range rawUpdates { 49 | // Show all updates 50 | fmt.Println(update.Data) 51 | fmt.Print("\n\n") 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /keyboardButton.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // KeyboardButton Represents a single button in a bot keyboard 8 | type KeyboardButton struct { 9 | tdCommon 10 | Text string `json:"text"` // Text of the button 11 | Type KeyboardButtonType `json:"type"` // Type of the button 12 | } 13 | 14 | // MessageType return the string telegram-type of KeyboardButton 15 | func (keyboardButton *KeyboardButton) MessageType() string { 16 | return "keyboardButton" 17 | } 18 | 19 | // NewKeyboardButton creates a new KeyboardButton 20 | // 21 | // @param text Text of the button 22 | // @param typeParam Type of the button 23 | func NewKeyboardButton(text string, typeParam KeyboardButtonType) *KeyboardButton { 24 | keyboardButtonTemp := KeyboardButton{ 25 | tdCommon: tdCommon{Type: "keyboardButton"}, 26 | Text: text, 27 | Type: typeParam, 28 | } 29 | 30 | return &keyboardButtonTemp 31 | } 32 | 33 | // UnmarshalJSON unmarshal to json 34 | func (keyboardButton *KeyboardButton) UnmarshalJSON(b []byte) error { 35 | var objMap map[string]*json.RawMessage 36 | err := json.Unmarshal(b, &objMap) 37 | if err != nil { 38 | return err 39 | } 40 | tempObj := struct { 41 | tdCommon 42 | Text string `json:"text"` // Text of the button 43 | 44 | }{} 45 | err = json.Unmarshal(b, &tempObj) 46 | if err != nil { 47 | return err 48 | } 49 | 50 | keyboardButton.tdCommon = tempObj.tdCommon 51 | keyboardButton.Text = tempObj.Text 52 | 53 | fieldType, _ := unmarshalKeyboardButtonType(objMap["type"]) 54 | keyboardButton.Type = fieldType 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /photoSize.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PhotoSize Describes an image in JPEG format 4 | type PhotoSize struct { 5 | tdCommon 6 | Type string `json:"type"` // Image type (see https://core.telegram.org/constructor/photoSize) 7 | Photo *File `json:"photo"` // Information about the image file 8 | Width int32 `json:"width"` // Image width 9 | Height int32 `json:"height"` // Image height 10 | ProgressiveSizes []int32 `json:"progressive_sizes"` // Sizes of progressive JPEG file prefixes, which can be used to preliminarily show the image; in bytes 11 | } 12 | 13 | // MessageType return the string telegram-type of PhotoSize 14 | func (photoSize *PhotoSize) MessageType() string { 15 | return "photoSize" 16 | } 17 | 18 | // NewPhotoSize creates a new PhotoSize 19 | // 20 | // @param typeParam Image type (see https://core.telegram.org/constructor/photoSize) 21 | // @param photo Information about the image file 22 | // @param width Image width 23 | // @param height Image height 24 | // @param progressiveSizes Sizes of progressive JPEG file prefixes, which can be used to preliminarily show the image; in bytes 25 | func NewPhotoSize(typeParam string, photo *File, width int32, height int32, progressiveSizes []int32) *PhotoSize { 26 | photoSizeTemp := PhotoSize{ 27 | tdCommon: tdCommon{Type: "photoSize"}, 28 | Type: typeParam, 29 | Photo: photo, 30 | Width: width, 31 | Height: height, 32 | ProgressiveSizes: progressiveSizes, 33 | } 34 | 35 | return &photoSizeTemp 36 | } 37 | -------------------------------------------------------------------------------- /groupCallParticipantVideoInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // GroupCallParticipantVideoInfo Contains information about a group call participant's video channel 4 | type GroupCallParticipantVideoInfo struct { 5 | tdCommon 6 | SourceGroups []GroupCallVideoSourceGroup `json:"source_groups"` // List of synchronization source groups of the video 7 | EndpointId string `json:"endpoint_id"` // Video channel endpoint identifier 8 | IsPaused bool `json:"is_paused"` // True if the video is paused. This flag needs to be ignored, if new video frames are received 9 | } 10 | 11 | // MessageType return the string telegram-type of GroupCallParticipantVideoInfo 12 | func (groupCallParticipantVideoInfo *GroupCallParticipantVideoInfo) MessageType() string { 13 | return "groupCallParticipantVideoInfo" 14 | } 15 | 16 | // NewGroupCallParticipantVideoInfo creates a new GroupCallParticipantVideoInfo 17 | // 18 | // @param sourceGroups List of synchronization source groups of the video 19 | // @param endpointId Video channel endpoint identifier 20 | // @param isPaused True if the video is paused. This flag needs to be ignored, if new video frames are received 21 | func NewGroupCallParticipantVideoInfo(sourceGroups []GroupCallVideoSourceGroup, endpointId string, isPaused bool) *GroupCallParticipantVideoInfo { 22 | groupCallParticipantVideoInfoTemp := GroupCallParticipantVideoInfo{ 23 | tdCommon: tdCommon{Type: "groupCallParticipantVideoInfo"}, 24 | SourceGroups: sourceGroups, 25 | EndpointId: endpointId, 26 | IsPaused: isPaused, 27 | } 28 | 29 | return &groupCallParticipantVideoInfoTemp 30 | } 31 | -------------------------------------------------------------------------------- /paymentsProviderStripe.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PaymentsProviderStripe Stripe payment provider 4 | type PaymentsProviderStripe struct { 5 | tdCommon 6 | PublishableKey string `json:"publishable_key"` // Stripe API publishable key 7 | NeedCountry bool `json:"need_country"` // True, if the user country must be provided 8 | NeedPostalCode bool `json:"need_postal_code"` // True, if the user ZIP/postal code must be provided 9 | NeedCardholderName bool `json:"need_cardholder_name"` // True, if the cardholder name must be provided 10 | } 11 | 12 | // MessageType return the string telegram-type of PaymentsProviderStripe 13 | func (paymentsProviderStripe *PaymentsProviderStripe) MessageType() string { 14 | return "paymentsProviderStripe" 15 | } 16 | 17 | // NewPaymentsProviderStripe creates a new PaymentsProviderStripe 18 | // 19 | // @param publishableKey Stripe API publishable key 20 | // @param needCountry True, if the user country must be provided 21 | // @param needPostalCode True, if the user ZIP/postal code must be provided 22 | // @param needCardholderName True, if the cardholder name must be provided 23 | func NewPaymentsProviderStripe(publishableKey string, needCountry bool, needPostalCode bool, needCardholderName bool) *PaymentsProviderStripe { 24 | paymentsProviderStripeTemp := PaymentsProviderStripe{ 25 | tdCommon: tdCommon{Type: "paymentsProviderStripe"}, 26 | PublishableKey: publishableKey, 27 | NeedCountry: needCountry, 28 | NeedPostalCode: needPostalCode, 29 | NeedCardholderName: needCardholderName, 30 | } 31 | 32 | return &paymentsProviderStripeTemp 33 | } 34 | -------------------------------------------------------------------------------- /recommendedChatFilters.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // RecommendedChatFilters Contains a list of recommended chat filters 9 | type RecommendedChatFilters struct { 10 | tdCommon 11 | ChatFilters []RecommendedChatFilter `json:"chat_filters"` // List of recommended chat filters 12 | } 13 | 14 | // MessageType return the string telegram-type of RecommendedChatFilters 15 | func (recommendedChatFilters *RecommendedChatFilters) MessageType() string { 16 | return "recommendedChatFilters" 17 | } 18 | 19 | // NewRecommendedChatFilters creates a new RecommendedChatFilters 20 | // 21 | // @param chatFilters List of recommended chat filters 22 | func NewRecommendedChatFilters(chatFilters []RecommendedChatFilter) *RecommendedChatFilters { 23 | recommendedChatFiltersTemp := RecommendedChatFilters{ 24 | tdCommon: tdCommon{Type: "recommendedChatFilters"}, 25 | ChatFilters: chatFilters, 26 | } 27 | 28 | return &recommendedChatFiltersTemp 29 | } 30 | 31 | // GetRecommendedChatFilters Returns recommended chat filters for the current user 32 | func (client *Client) GetRecommendedChatFilters() (*RecommendedChatFilters, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getRecommendedChatFilters", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var recommendedChatFilters RecommendedChatFilters 46 | err = json.Unmarshal(result.Raw, &recommendedChatFilters) 47 | return &recommendedChatFilters, err 48 | } 49 | -------------------------------------------------------------------------------- /chatAdministrators.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ChatAdministrators Represents a list of chat administrators 9 | type ChatAdministrators struct { 10 | tdCommon 11 | Administrators []ChatAdministrator `json:"administrators"` // A list of chat administrators 12 | } 13 | 14 | // MessageType return the string telegram-type of ChatAdministrators 15 | func (chatAdministrators *ChatAdministrators) MessageType() string { 16 | return "chatAdministrators" 17 | } 18 | 19 | // NewChatAdministrators creates a new ChatAdministrators 20 | // 21 | // @param administrators A list of chat administrators 22 | func NewChatAdministrators(administrators []ChatAdministrator) *ChatAdministrators { 23 | chatAdministratorsTemp := ChatAdministrators{ 24 | tdCommon: tdCommon{Type: "chatAdministrators"}, 25 | Administrators: administrators, 26 | } 27 | 28 | return &chatAdministratorsTemp 29 | } 30 | 31 | // GetChatAdministrators Returns a list of administrators of the chat with their custom titles 32 | // @param chatId Chat identifier 33 | func (client *Client) GetChatAdministrators(chatId int64) (*ChatAdministrators, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getChatAdministrators", 36 | "chat_id": chatId, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var chatAdministrators ChatAdministrators 48 | err = json.Unmarshal(result.Raw, &chatAdministrators) 49 | return &chatAdministrators, err 50 | } 51 | -------------------------------------------------------------------------------- /callProtocol.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // CallProtocol Specifies the supported call protocols 4 | type CallProtocol struct { 5 | tdCommon 6 | UdpP2p bool `json:"udp_p2p"` // True, if UDP peer-to-peer connections are supported 7 | UdpReflector bool `json:"udp_reflector"` // True, if connection through UDP reflectors is supported 8 | MinLayer int32 `json:"min_layer"` // The minimum supported API layer; use 65 9 | MaxLayer int32 `json:"max_layer"` // The maximum supported API layer; use 65 10 | LibraryVersions []string `json:"library_versions"` // List of supported tgcalls versions 11 | } 12 | 13 | // MessageType return the string telegram-type of CallProtocol 14 | func (callProtocol *CallProtocol) MessageType() string { 15 | return "callProtocol" 16 | } 17 | 18 | // NewCallProtocol creates a new CallProtocol 19 | // 20 | // @param udpP2p True, if UDP peer-to-peer connections are supported 21 | // @param udpReflector True, if connection through UDP reflectors is supported 22 | // @param minLayer The minimum supported API layer; use 65 23 | // @param maxLayer The maximum supported API layer; use 65 24 | // @param libraryVersions List of supported tgcalls versions 25 | func NewCallProtocol(udpP2p bool, udpReflector bool, minLayer int32, maxLayer int32, libraryVersions []string) *CallProtocol { 26 | callProtocolTemp := CallProtocol{ 27 | tdCommon: tdCommon{Type: "callProtocol"}, 28 | UdpP2p: udpP2p, 29 | UdpReflector: udpReflector, 30 | MinLayer: minLayer, 31 | MaxLayer: maxLayer, 32 | LibraryVersions: libraryVersions, 33 | } 34 | 35 | return &callProtocolTemp 36 | } 37 | -------------------------------------------------------------------------------- /customRequestResult.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // CustomRequestResult Contains the result of a custom request 9 | type CustomRequestResult struct { 10 | tdCommon 11 | Result string `json:"result"` // A JSON-serialized result 12 | } 13 | 14 | // MessageType return the string telegram-type of CustomRequestResult 15 | func (customRequestResult *CustomRequestResult) MessageType() string { 16 | return "customRequestResult" 17 | } 18 | 19 | // NewCustomRequestResult creates a new CustomRequestResult 20 | // 21 | // @param result A JSON-serialized result 22 | func NewCustomRequestResult(result string) *CustomRequestResult { 23 | customRequestResultTemp := CustomRequestResult{ 24 | tdCommon: tdCommon{Type: "customRequestResult"}, 25 | Result: result, 26 | } 27 | 28 | return &customRequestResultTemp 29 | } 30 | 31 | // SendCustomRequest Sends a custom request; for bots only 32 | // @param method The method name 33 | // @param parameters JSON-serialized method parameters 34 | func (client *Client) SendCustomRequest(method string, parameters string) (*CustomRequestResult, error) { 35 | result, err := client.SendAndCatch(UpdateData{ 36 | "@type": "sendCustomRequest", 37 | "method": method, 38 | "parameters": parameters, 39 | }) 40 | 41 | if err != nil { 42 | return nil, err 43 | } 44 | 45 | if result.Data["@type"].(string) == "error" { 46 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 47 | } 48 | 49 | var customRequestResult CustomRequestResult 50 | err = json.Unmarshal(result.Raw, &customRequestResult) 51 | return &customRequestResult, err 52 | } 53 | -------------------------------------------------------------------------------- /chatPhoto.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatPhoto Describes a chat or user profile photo 4 | type ChatPhoto struct { 5 | tdCommon 6 | Id JSONInt64 `json:"id"` // Unique photo identifier 7 | AddedDate int32 `json:"added_date"` // Point in time (Unix timestamp) when the photo has been added 8 | Minithumbnail *Minithumbnail `json:"minithumbnail"` // Photo minithumbnail; may be null 9 | Sizes []PhotoSize `json:"sizes"` // Available variants of the photo in JPEG format, in different size 10 | Animation *AnimatedChatPhoto `json:"animation"` // Animated variant of the photo in MPEG4 format; may be null 11 | } 12 | 13 | // MessageType return the string telegram-type of ChatPhoto 14 | func (chatPhoto *ChatPhoto) MessageType() string { 15 | return "chatPhoto" 16 | } 17 | 18 | // NewChatPhoto creates a new ChatPhoto 19 | // 20 | // @param id Unique photo identifier 21 | // @param addedDate Point in time (Unix timestamp) when the photo has been added 22 | // @param minithumbnail Photo minithumbnail; may be null 23 | // @param sizes Available variants of the photo in JPEG format, in different size 24 | // @param animation Animated variant of the photo in MPEG4 format; may be null 25 | func NewChatPhoto(id JSONInt64, addedDate int32, minithumbnail *Minithumbnail, sizes []PhotoSize, animation *AnimatedChatPhoto) *ChatPhoto { 26 | chatPhotoTemp := ChatPhoto{ 27 | tdCommon: tdCommon{Type: "chatPhoto"}, 28 | Id: id, 29 | AddedDate: addedDate, 30 | Minithumbnail: minithumbnail, 31 | Sizes: sizes, 32 | Animation: animation, 33 | } 34 | 35 | return &chatPhotoTemp 36 | } 37 | -------------------------------------------------------------------------------- /sessions.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Sessions Contains a list of sessions 9 | type Sessions struct { 10 | tdCommon 11 | Sessions []Session `json:"sessions"` // List of sessions 12 | InactiveSessionTtlDays int32 `json:"inactive_session_ttl_days"` // Number of days of inactivity before sessions will automatically be terminated; 1-366 days 13 | } 14 | 15 | // MessageType return the string telegram-type of Sessions 16 | func (sessions *Sessions) MessageType() string { 17 | return "sessions" 18 | } 19 | 20 | // NewSessions creates a new Sessions 21 | // 22 | // @param sessions List of sessions 23 | // @param inactiveSessionTtlDays Number of days of inactivity before sessions will automatically be terminated; 1-366 days 24 | func NewSessions(sessions []Session, inactiveSessionTtlDays int32) *Sessions { 25 | sessionsTemp := Sessions{ 26 | tdCommon: tdCommon{Type: "sessions"}, 27 | Sessions: sessions, 28 | InactiveSessionTtlDays: inactiveSessionTtlDays, 29 | } 30 | 31 | return &sessionsTemp 32 | } 33 | 34 | // GetActiveSessions Returns all active sessions of the current user 35 | func (client *Client) GetActiveSessions() (*Sessions, error) { 36 | result, err := client.SendAndCatch(UpdateData{ 37 | "@type": "getActiveSessions", 38 | }) 39 | 40 | if err != nil { 41 | return nil, err 42 | } 43 | 44 | if result.Data["@type"].(string) == "error" { 45 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 46 | } 47 | 48 | var sessions Sessions 49 | err = json.Unmarshal(result.Raw, &sessions) 50 | return &sessions, err 51 | } 52 | -------------------------------------------------------------------------------- /pollOption.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PollOption Describes one answer option of a poll 4 | type PollOption struct { 5 | tdCommon 6 | Text string `json:"text"` // Option text; 1-100 characters 7 | VoterCount int32 `json:"voter_count"` // Number of voters for this option, available only for closed or voted polls 8 | VotePercentage int32 `json:"vote_percentage"` // The percentage of votes for this option; 0-100 9 | IsChosen bool `json:"is_chosen"` // True, if the option was chosen by the user 10 | IsBeingChosen bool `json:"is_being_chosen"` // True, if the option is being chosen by a pending setPollAnswer request 11 | } 12 | 13 | // MessageType return the string telegram-type of PollOption 14 | func (pollOption *PollOption) MessageType() string { 15 | return "pollOption" 16 | } 17 | 18 | // NewPollOption creates a new PollOption 19 | // 20 | // @param text Option text; 1-100 characters 21 | // @param voterCount Number of voters for this option, available only for closed or voted polls 22 | // @param votePercentage The percentage of votes for this option; 0-100 23 | // @param isChosen True, if the option was chosen by the user 24 | // @param isBeingChosen True, if the option is being chosen by a pending setPollAnswer request 25 | func NewPollOption(text string, voterCount int32, votePercentage int32, isChosen bool, isBeingChosen bool) *PollOption { 26 | pollOptionTemp := PollOption{ 27 | tdCommon: tdCommon{Type: "pollOption"}, 28 | Text: text, 29 | VoterCount: voterCount, 30 | VotePercentage: votePercentage, 31 | IsChosen: isChosen, 32 | IsBeingChosen: isBeingChosen, 33 | } 34 | 35 | return &pollOptionTemp 36 | } 37 | -------------------------------------------------------------------------------- /chatPhotoInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatPhotoInfo Contains basic information about the photo of a chat 4 | type ChatPhotoInfo struct { 5 | tdCommon 6 | Small *File `json:"small"` // A small (160x160) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed 7 | Big *File `json:"big"` // A big (640x640) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed 8 | Minithumbnail *Minithumbnail `json:"minithumbnail"` // Chat photo minithumbnail; may be null 9 | HasAnimation bool `json:"has_animation"` // True, if the photo has animated variant 10 | } 11 | 12 | // MessageType return the string telegram-type of ChatPhotoInfo 13 | func (chatPhotoInfo *ChatPhotoInfo) MessageType() string { 14 | return "chatPhotoInfo" 15 | } 16 | 17 | // NewChatPhotoInfo creates a new ChatPhotoInfo 18 | // 19 | // @param small A small (160x160) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed 20 | // @param big A big (640x640) chat photo variant in JPEG format. The file can be downloaded only before the photo is changed 21 | // @param minithumbnail Chat photo minithumbnail; may be null 22 | // @param hasAnimation True, if the photo has animated variant 23 | func NewChatPhotoInfo(small *File, big *File, minithumbnail *Minithumbnail, hasAnimation bool) *ChatPhotoInfo { 24 | chatPhotoInfoTemp := ChatPhotoInfo{ 25 | tdCommon: tdCommon{Type: "chatPhotoInfo"}, 26 | Small: small, 27 | Big: big, 28 | Minithumbnail: minithumbnail, 29 | HasAnimation: hasAnimation, 30 | } 31 | 32 | return &chatPhotoInfoTemp 33 | } 34 | -------------------------------------------------------------------------------- /testVectorIntObject.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TestVectorIntObject A simple object containing a vector of objects that hold a number; for testing only 9 | type TestVectorIntObject struct { 10 | tdCommon 11 | Value []TestInt `json:"value"` // Vector of objects 12 | } 13 | 14 | // MessageType return the string telegram-type of TestVectorIntObject 15 | func (testVectorIntObject *TestVectorIntObject) MessageType() string { 16 | return "testVectorIntObject" 17 | } 18 | 19 | // NewTestVectorIntObject creates a new TestVectorIntObject 20 | // 21 | // @param value Vector of objects 22 | func NewTestVectorIntObject(value []TestInt) *TestVectorIntObject { 23 | testVectorIntObjectTemp := TestVectorIntObject{ 24 | tdCommon: tdCommon{Type: "testVectorIntObject"}, 25 | Value: value, 26 | } 27 | 28 | return &testVectorIntObjectTemp 29 | } 30 | 31 | // TestCallVectorIntObject Returns the received vector of objects containing a number; for testing only. This is an offline method. Can be called before authorization 32 | // @param x Vector of objects to return 33 | func (client *Client) TestCallVectorIntObject(x []TestInt) (*TestVectorIntObject, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "testCallVectorIntObject", 36 | "x": x, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var testVectorIntObject TestVectorIntObject 48 | err = json.Unmarshal(result.Raw, &testVectorIntObject) 49 | return &testVectorIntObject, err 50 | } 51 | -------------------------------------------------------------------------------- /game.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Game Describes a game 4 | type Game struct { 5 | tdCommon 6 | Id JSONInt64 `json:"id"` // Game ID 7 | ShortName string `json:"short_name"` // Game short name. To share a game use the URL https://t.me/{bot_username}?game={game_short_name} 8 | Title string `json:"title"` // Game title 9 | Text *FormattedText `json:"text"` // Game text, usually containing scoreboards for a game 10 | Description string `json:"description"` // Game description 11 | Photo *Photo `json:"photo"` // Game photo 12 | Animation *Animation `json:"animation"` // Game animation; may be null 13 | } 14 | 15 | // MessageType return the string telegram-type of Game 16 | func (game *Game) MessageType() string { 17 | return "game" 18 | } 19 | 20 | // NewGame creates a new Game 21 | // 22 | // @param id Game ID 23 | // @param shortName Game short name. To share a game use the URL https://t.me/{bot_username}?game={game_short_name} 24 | // @param title Game title 25 | // @param text Game text, usually containing scoreboards for a game 26 | // @param description Game description 27 | // @param photo Game photo 28 | // @param animation Game animation; may be null 29 | func NewGame(id JSONInt64, shortName string, title string, text *FormattedText, description string, photo *Photo, animation *Animation) *Game { 30 | gameTemp := Game{ 31 | tdCommon: tdCommon{Type: "game"}, 32 | Id: id, 33 | ShortName: shortName, 34 | Title: title, 35 | Text: text, 36 | Description: description, 37 | Photo: photo, 38 | Animation: animation, 39 | } 40 | 41 | return &gameTemp 42 | } 43 | -------------------------------------------------------------------------------- /messageInteractionInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // MessageInteractionInfo Contains information about interactions with a message 4 | type MessageInteractionInfo struct { 5 | tdCommon 6 | ViewCount int32 `json:"view_count"` // Number of times the message was viewed 7 | ForwardCount int32 `json:"forward_count"` // Number of times the message was forwarded 8 | ReplyInfo *MessageReplyInfo `json:"reply_info"` // 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 9 | } 10 | 11 | // MessageType return the string telegram-type of MessageInteractionInfo 12 | func (messageInteractionInfo *MessageInteractionInfo) MessageType() string { 13 | return "messageInteractionInfo" 14 | } 15 | 16 | // NewMessageInteractionInfo creates a new MessageInteractionInfo 17 | // 18 | // @param viewCount Number of times the message was viewed 19 | // @param forwardCount Number of times the message was forwarded 20 | // @param replyInfo 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 21 | func NewMessageInteractionInfo(viewCount int32, forwardCount int32, replyInfo *MessageReplyInfo) *MessageInteractionInfo { 22 | messageInteractionInfoTemp := MessageInteractionInfo{ 23 | tdCommon: tdCommon{Type: "messageInteractionInfo"}, 24 | ViewCount: viewCount, 25 | ForwardCount: forwardCount, 26 | ReplyInfo: replyInfo, 27 | } 28 | 29 | return &messageInteractionInfoTemp 30 | } 31 | -------------------------------------------------------------------------------- /pageBlockCaption.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // PageBlockCaption Contains a caption of an instant view web page block, consisting of a text and a trailing credit 8 | type PageBlockCaption struct { 9 | tdCommon 10 | Text RichText `json:"text"` // Content of the caption 11 | Credit RichText `json:"credit"` // Block credit (like HTML tag ) 12 | } 13 | 14 | // MessageType return the string telegram-type of PageBlockCaption 15 | func (pageBlockCaption *PageBlockCaption) MessageType() string { 16 | return "pageBlockCaption" 17 | } 18 | 19 | // NewPageBlockCaption creates a new PageBlockCaption 20 | // 21 | // @param text Content of the caption 22 | // @param credit Block credit (like HTML tag ) 23 | func NewPageBlockCaption(text RichText, credit RichText) *PageBlockCaption { 24 | pageBlockCaptionTemp := PageBlockCaption{ 25 | tdCommon: tdCommon{Type: "pageBlockCaption"}, 26 | Text: text, 27 | Credit: credit, 28 | } 29 | 30 | return &pageBlockCaptionTemp 31 | } 32 | 33 | // UnmarshalJSON unmarshal to json 34 | func (pageBlockCaption *PageBlockCaption) UnmarshalJSON(b []byte) error { 35 | var objMap map[string]*json.RawMessage 36 | err := json.Unmarshal(b, &objMap) 37 | if err != nil { 38 | return err 39 | } 40 | tempObj := struct { 41 | tdCommon 42 | }{} 43 | err = json.Unmarshal(b, &tempObj) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | pageBlockCaption.tdCommon = tempObj.tdCommon 49 | 50 | fieldText, _ := unmarshalRichText(objMap["text"]) 51 | pageBlockCaption.Text = fieldText 52 | 53 | fieldCredit, _ := unmarshalRichText(objMap["credit"]) 54 | pageBlockCaption.Credit = fieldCredit 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /videoNote.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // VideoNote Describes a video note. The video must be equal in width and height, cropped to a circle, and stored in MPEG4 format 4 | type VideoNote struct { 5 | tdCommon 6 | Duration int32 `json:"duration"` // Duration of the video, in seconds; as defined by the sender 7 | Length int32 `json:"length"` // Video width and height; as defined by the sender 8 | Minithumbnail *Minithumbnail `json:"minithumbnail"` // Video minithumbnail; may be null 9 | Thumbnail *Thumbnail `json:"thumbnail"` // Video thumbnail in JPEG format; as defined by the sender; may be null 10 | Video *File `json:"video"` // File containing the video 11 | } 12 | 13 | // MessageType return the string telegram-type of VideoNote 14 | func (videoNote *VideoNote) MessageType() string { 15 | return "videoNote" 16 | } 17 | 18 | // NewVideoNote creates a new VideoNote 19 | // 20 | // @param duration Duration of the video, in seconds; as defined by the sender 21 | // @param length Video width and height; as defined by the sender 22 | // @param minithumbnail Video minithumbnail; may be null 23 | // @param thumbnail Video thumbnail in JPEG format; as defined by the sender; may be null 24 | // @param video File containing the video 25 | func NewVideoNote(duration int32, length int32, minithumbnail *Minithumbnail, thumbnail *Thumbnail, video *File) *VideoNote { 26 | videoNoteTemp := VideoNote{ 27 | tdCommon: tdCommon{Type: "videoNote"}, 28 | Duration: duration, 29 | Length: length, 30 | Minithumbnail: minithumbnail, 31 | Thumbnail: thumbnail, 32 | Video: video, 33 | } 34 | 35 | return &videoNoteTemp 36 | } 37 | -------------------------------------------------------------------------------- /bankCardInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // BankCardInfo Information about a bank card 9 | type BankCardInfo struct { 10 | tdCommon 11 | Title string `json:"title"` // Title of the bank card description 12 | Actions []BankCardActionOpenUrl `json:"actions"` // Actions that can be done with the bank card number 13 | } 14 | 15 | // MessageType return the string telegram-type of BankCardInfo 16 | func (bankCardInfo *BankCardInfo) MessageType() string { 17 | return "bankCardInfo" 18 | } 19 | 20 | // NewBankCardInfo creates a new BankCardInfo 21 | // 22 | // @param title Title of the bank card description 23 | // @param actions Actions that can be done with the bank card number 24 | func NewBankCardInfo(title string, actions []BankCardActionOpenUrl) *BankCardInfo { 25 | bankCardInfoTemp := BankCardInfo{ 26 | tdCommon: tdCommon{Type: "bankCardInfo"}, 27 | Title: title, 28 | Actions: actions, 29 | } 30 | 31 | return &bankCardInfoTemp 32 | } 33 | 34 | // GetBankCardInfo Returns information about a bank card 35 | // @param bankCardNumber The bank card number 36 | func (client *Client) GetBankCardInfo(bankCardNumber string) (*BankCardInfo, error) { 37 | result, err := client.SendAndCatch(UpdateData{ 38 | "@type": "getBankCardInfo", 39 | "bank_card_number": bankCardNumber, 40 | }) 41 | 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | if result.Data["@type"].(string) == "error" { 47 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 48 | } 49 | 50 | var bankCardInfo BankCardInfo 51 | err = json.Unmarshal(result.Raw, &bankCardInfo) 52 | return &bankCardInfo, err 53 | } 54 | -------------------------------------------------------------------------------- /document.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Document Describes a document of any type 4 | type Document struct { 5 | tdCommon 6 | FileName string `json:"file_name"` // Original name of the file; as defined by the sender 7 | MimeType string `json:"mime_type"` // MIME type of the file; as defined by the sender 8 | Minithumbnail *Minithumbnail `json:"minithumbnail"` // Document minithumbnail; may be null 9 | 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 10 | Document *File `json:"document"` // File containing the document 11 | } 12 | 13 | // MessageType return the string telegram-type of Document 14 | func (document *Document) MessageType() string { 15 | return "document" 16 | } 17 | 18 | // NewDocument creates a new Document 19 | // 20 | // @param fileName Original name of the file; as defined by the sender 21 | // @param mimeType MIME type of the file; as defined by the sender 22 | // @param minithumbnail Document minithumbnail; may be null 23 | // @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 24 | // @param document File containing the document 25 | func NewDocument(fileName string, mimeType string, minithumbnail *Minithumbnail, thumbnail *Thumbnail, document *File) *Document { 26 | documentTemp := Document{ 27 | tdCommon: tdCommon{Type: "document"}, 28 | FileName: fileName, 29 | MimeType: mimeType, 30 | Minithumbnail: minithumbnail, 31 | Thumbnail: thumbnail, 32 | Document: document, 33 | } 34 | 35 | return &documentTemp 36 | } 37 | -------------------------------------------------------------------------------- /inlineKeyboardButton.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // InlineKeyboardButton Represents a single button in an inline keyboard 8 | type InlineKeyboardButton struct { 9 | tdCommon 10 | Text string `json:"text"` // Text of the button 11 | Type InlineKeyboardButtonType `json:"type"` // Type of the button 12 | } 13 | 14 | // MessageType return the string telegram-type of InlineKeyboardButton 15 | func (inlineKeyboardButton *InlineKeyboardButton) MessageType() string { 16 | return "inlineKeyboardButton" 17 | } 18 | 19 | // NewInlineKeyboardButton creates a new InlineKeyboardButton 20 | // 21 | // @param text Text of the button 22 | // @param typeParam Type of the button 23 | func NewInlineKeyboardButton(text string, typeParam InlineKeyboardButtonType) *InlineKeyboardButton { 24 | inlineKeyboardButtonTemp := InlineKeyboardButton{ 25 | tdCommon: tdCommon{Type: "inlineKeyboardButton"}, 26 | Text: text, 27 | Type: typeParam, 28 | } 29 | 30 | return &inlineKeyboardButtonTemp 31 | } 32 | 33 | // UnmarshalJSON unmarshal to json 34 | func (inlineKeyboardButton *InlineKeyboardButton) UnmarshalJSON(b []byte) error { 35 | var objMap map[string]*json.RawMessage 36 | err := json.Unmarshal(b, &objMap) 37 | if err != nil { 38 | return err 39 | } 40 | tempObj := struct { 41 | tdCommon 42 | Text string `json:"text"` // Text of the button 43 | 44 | }{} 45 | err = json.Unmarshal(b, &tempObj) 46 | if err != nil { 47 | return err 48 | } 49 | 50 | inlineKeyboardButton.tdCommon = tempObj.tdCommon 51 | inlineKeyboardButton.Text = tempObj.Text 52 | 53 | fieldType, _ := unmarshalInlineKeyboardButtonType(objMap["type"]) 54 | inlineKeyboardButton.Type = fieldType 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /chatInviteLinkCounts.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ChatInviteLinkCounts Contains a list of chat invite link counts 9 | type ChatInviteLinkCounts struct { 10 | tdCommon 11 | InviteLinkCounts []ChatInviteLinkCount `json:"invite_link_counts"` // List of invite link counts 12 | } 13 | 14 | // MessageType return the string telegram-type of ChatInviteLinkCounts 15 | func (chatInviteLinkCounts *ChatInviteLinkCounts) MessageType() string { 16 | return "chatInviteLinkCounts" 17 | } 18 | 19 | // NewChatInviteLinkCounts creates a new ChatInviteLinkCounts 20 | // 21 | // @param inviteLinkCounts List of invite link counts 22 | func NewChatInviteLinkCounts(inviteLinkCounts []ChatInviteLinkCount) *ChatInviteLinkCounts { 23 | chatInviteLinkCountsTemp := ChatInviteLinkCounts{ 24 | tdCommon: tdCommon{Type: "chatInviteLinkCounts"}, 25 | InviteLinkCounts: inviteLinkCounts, 26 | } 27 | 28 | return &chatInviteLinkCountsTemp 29 | } 30 | 31 | // GetChatInviteLinkCounts Returns list of chat administrators with number of their invite links. Requires owner privileges in the chat 32 | // @param chatId Chat identifier 33 | func (client *Client) GetChatInviteLinkCounts(chatId int64) (*ChatInviteLinkCounts, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getChatInviteLinkCounts", 36 | "chat_id": chatId, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var chatInviteLinkCounts ChatInviteLinkCounts 48 | err = json.Unmarshal(result.Raw, &chatInviteLinkCounts) 49 | return &chatInviteLinkCounts, err 50 | } 51 | -------------------------------------------------------------------------------- /testVectorStringObject.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // TestVectorStringObject A simple object containing a vector of objects that hold a string; for testing only 9 | type TestVectorStringObject struct { 10 | tdCommon 11 | Value []TestString `json:"value"` // Vector of objects 12 | } 13 | 14 | // MessageType return the string telegram-type of TestVectorStringObject 15 | func (testVectorStringObject *TestVectorStringObject) MessageType() string { 16 | return "testVectorStringObject" 17 | } 18 | 19 | // NewTestVectorStringObject creates a new TestVectorStringObject 20 | // 21 | // @param value Vector of objects 22 | func NewTestVectorStringObject(value []TestString) *TestVectorStringObject { 23 | testVectorStringObjectTemp := TestVectorStringObject{ 24 | tdCommon: tdCommon{Type: "testVectorStringObject"}, 25 | Value: value, 26 | } 27 | 28 | return &testVectorStringObjectTemp 29 | } 30 | 31 | // TestCallVectorStringObject Returns the received vector of objects containing a string; for testing only. This is an offline method. Can be called before authorization 32 | // @param x Vector of objects to return 33 | func (client *Client) TestCallVectorStringObject(x []TestString) (*TestVectorStringObject, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "testCallVectorStringObject", 36 | "x": x, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var testVectorStringObject TestVectorStringObject 48 | err = json.Unmarshal(result.Raw, &testVectorStringObject) 49 | return &testVectorStringObject, err 50 | } 51 | -------------------------------------------------------------------------------- /languagePackString.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // LanguagePackString Represents one language pack string 8 | type LanguagePackString struct { 9 | tdCommon 10 | Key string `json:"key"` // String key 11 | Value LanguagePackStringValue `json:"value"` // String value; pass null if the string needs to be taken from the built-in English language pack 12 | } 13 | 14 | // MessageType return the string telegram-type of LanguagePackString 15 | func (languagePackString *LanguagePackString) MessageType() string { 16 | return "languagePackString" 17 | } 18 | 19 | // NewLanguagePackString creates a new LanguagePackString 20 | // 21 | // @param key String key 22 | // @param value String value; pass null if the string needs to be taken from the built-in English language pack 23 | func NewLanguagePackString(key string, value LanguagePackStringValue) *LanguagePackString { 24 | languagePackStringTemp := LanguagePackString{ 25 | tdCommon: tdCommon{Type: "languagePackString"}, 26 | Key: key, 27 | Value: value, 28 | } 29 | 30 | return &languagePackStringTemp 31 | } 32 | 33 | // UnmarshalJSON unmarshal to json 34 | func (languagePackString *LanguagePackString) UnmarshalJSON(b []byte) error { 35 | var objMap map[string]*json.RawMessage 36 | err := json.Unmarshal(b, &objMap) 37 | if err != nil { 38 | return err 39 | } 40 | tempObj := struct { 41 | tdCommon 42 | Key string `json:"key"` // String key 43 | 44 | }{} 45 | err = json.Unmarshal(b, &tempObj) 46 | if err != nil { 47 | return err 48 | } 49 | 50 | languagePackString.tdCommon = tempObj.tdCommon 51 | languagePackString.Key = tempObj.Key 52 | 53 | fieldValue, _ := unmarshalLanguagePackStringValue(objMap["value"]) 54 | languagePackString.Value = fieldValue 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /pageBlockRelatedArticle.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PageBlockRelatedArticle Contains information about a related article 4 | type PageBlockRelatedArticle struct { 5 | tdCommon 6 | Url string `json:"url"` // Related article URL 7 | Title string `json:"title"` // Article title; may be empty 8 | Description string `json:"description"` // Article description; may be empty 9 | Photo *Photo `json:"photo"` // Article photo; may be null 10 | Author string `json:"author"` // Article author; may be empty 11 | PublishDate int32 `json:"publish_date"` // Point in time (Unix timestamp) when the article was published; 0 if unknown 12 | } 13 | 14 | // MessageType return the string telegram-type of PageBlockRelatedArticle 15 | func (pageBlockRelatedArticle *PageBlockRelatedArticle) MessageType() string { 16 | return "pageBlockRelatedArticle" 17 | } 18 | 19 | // NewPageBlockRelatedArticle creates a new PageBlockRelatedArticle 20 | // 21 | // @param url Related article URL 22 | // @param title Article title; may be empty 23 | // @param description Article description; may be empty 24 | // @param photo Article photo; may be null 25 | // @param author Article author; may be empty 26 | // @param publishDate Point in time (Unix timestamp) when the article was published; 0 if unknown 27 | func NewPageBlockRelatedArticle(url string, title string, description string, photo *Photo, author string, publishDate int32) *PageBlockRelatedArticle { 28 | pageBlockRelatedArticleTemp := PageBlockRelatedArticle{ 29 | tdCommon: tdCommon{Type: "pageBlockRelatedArticle"}, 30 | Url: url, 31 | Title: title, 32 | Description: description, 33 | Photo: photo, 34 | Author: author, 35 | PublishDate: publishDate, 36 | } 37 | 38 | return &pageBlockRelatedArticleTemp 39 | } 40 | -------------------------------------------------------------------------------- /userPrivacySettingRules.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // 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 9 | type UserPrivacySettingRules struct { 10 | tdCommon 11 | Rules []UserPrivacySettingRule `json:"rules"` // A list of rules 12 | } 13 | 14 | // MessageType return the string telegram-type of UserPrivacySettingRules 15 | func (userPrivacySettingRules *UserPrivacySettingRules) MessageType() string { 16 | return "userPrivacySettingRules" 17 | } 18 | 19 | // NewUserPrivacySettingRules creates a new UserPrivacySettingRules 20 | // 21 | // @param rules A list of rules 22 | func NewUserPrivacySettingRules(rules []UserPrivacySettingRule) *UserPrivacySettingRules { 23 | userPrivacySettingRulesTemp := UserPrivacySettingRules{ 24 | tdCommon: tdCommon{Type: "userPrivacySettingRules"}, 25 | Rules: rules, 26 | } 27 | 28 | return &userPrivacySettingRulesTemp 29 | } 30 | 31 | // GetUserPrivacySettingRules Returns the current privacy settings 32 | // @param setting The privacy setting 33 | func (client *Client) GetUserPrivacySettingRules(setting UserPrivacySetting) (*UserPrivacySettingRules, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getUserPrivacySettingRules", 36 | "setting": setting, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var userPrivacySettingRules UserPrivacySettingRules 48 | err = json.Unmarshal(result.Raw, &userPrivacySettingRules) 49 | return &userPrivacySettingRules, err 50 | } 51 | -------------------------------------------------------------------------------- /recoveryEmailAddress.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // RecoveryEmailAddress Contains information about the current recovery email address 9 | type RecoveryEmailAddress struct { 10 | tdCommon 11 | RecoveryEmailAddress string `json:"recovery_email_address"` // Recovery email address 12 | } 13 | 14 | // MessageType return the string telegram-type of RecoveryEmailAddress 15 | func (recoveryEmailAddress *RecoveryEmailAddress) MessageType() string { 16 | return "recoveryEmailAddress" 17 | } 18 | 19 | // NewRecoveryEmailAddress creates a new RecoveryEmailAddress 20 | // 21 | // @param recoveryEmailAddress Recovery email address 22 | func NewRecoveryEmailAddress(recoveryEmailAddress string) *RecoveryEmailAddress { 23 | recoveryEmailAddressTemp := RecoveryEmailAddress{ 24 | tdCommon: tdCommon{Type: "recoveryEmailAddress"}, 25 | RecoveryEmailAddress: recoveryEmailAddress, 26 | } 27 | 28 | return &recoveryEmailAddressTemp 29 | } 30 | 31 | // 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 32 | // @param password The password for the current user 33 | func (client *Client) GetRecoveryEmailAddress(password string) (*RecoveryEmailAddress, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getRecoveryEmailAddress", 36 | "password": password, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var recoveryEmailAddress RecoveryEmailAddress 48 | err = json.Unmarshal(result.Raw, &recoveryEmailAddress) 49 | return &recoveryEmailAddress, err 50 | } 51 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Error An object of this type can be returned on every function call, in case of an error 9 | type Error struct { 10 | tdCommon 11 | 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 12 | Message string `json:"message"` // Error message; subject to future changes 13 | } 14 | 15 | // MessageType return the string telegram-type of Error 16 | func (error *Error) MessageType() string { 17 | return "error" 18 | } 19 | 20 | // NewError creates a new Error 21 | // 22 | // @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 23 | // @param message Error message; subject to future changes 24 | func NewError(code int32, message string) *Error { 25 | errorTemp := Error{ 26 | tdCommon: tdCommon{Type: "error"}, 27 | Code: code, 28 | Message: message, 29 | } 30 | 31 | return &errorTemp 32 | } 33 | 34 | // TestReturnError Returns the specified error and ensures that the Error object is used; for testing only. Can be called synchronously 35 | // @param error The error to be returned 36 | func (client *Client) TestReturnError(error *Error) (*Error, error) { 37 | result, err := client.SendAndCatch(UpdateData{ 38 | "@type": "testReturnError", 39 | "error": error, 40 | }) 41 | 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | if result.Data["@type"].(string) == "error" { 47 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 48 | } 49 | 50 | var errorDummy Error 51 | err = json.Unmarshal(result.Raw, &errorDummy) 52 | return &errorDummy, err 53 | } 54 | -------------------------------------------------------------------------------- /venue.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // Venue Describes a venue 4 | type Venue struct { 5 | tdCommon 6 | Location *Location `json:"location"` // Venue location; as defined by the sender 7 | Title string `json:"title"` // Venue name; as defined by the sender 8 | Address string `json:"address"` // Venue address; as defined by the sender 9 | 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 10 | Id string `json:"id"` // Identifier of the venue in the provider database; as defined by the sender 11 | Type string `json:"type"` // Type of the venue in the provider database; as defined by the sender 12 | } 13 | 14 | // MessageType return the string telegram-type of Venue 15 | func (venue *Venue) MessageType() string { 16 | return "venue" 17 | } 18 | 19 | // NewVenue creates a new Venue 20 | // 21 | // @param location Venue location; as defined by the sender 22 | // @param title Venue name; as defined by the sender 23 | // @param address Venue address; as defined by the sender 24 | // @param provider Provider of the venue database; as defined by the sender. Currently, only "foursquare" and "gplaces" (Google Places) need to be supported 25 | // @param id Identifier of the venue in the provider database; as defined by the sender 26 | // @param typeParam Type of the venue in the provider database; as defined by the sender 27 | func NewVenue(location *Location, title string, address string, provider string, id string, typeParam string) *Venue { 28 | venueTemp := Venue{ 29 | tdCommon: tdCommon{Type: "venue"}, 30 | Location: location, 31 | Title: title, 32 | Address: address, 33 | Provider: provider, 34 | Id: id, 35 | Type: typeParam, 36 | } 37 | 38 | return &venueTemp 39 | } 40 | -------------------------------------------------------------------------------- /examples/sendPhoto/sendPhoto.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "os/signal" 6 | "syscall" 7 | "time" 8 | 9 | "github.com/c0re100/go-tdlib" 10 | ) 11 | 12 | func main() { 13 | tdlib.SetLogVerbosityLevel(1) 14 | tdlib.SetFilePath("./errors.txt") 15 | 16 | // Create new instance of client 17 | client := tdlib.NewClient(tdlib.Config{ 18 | APIID: "187786", 19 | APIHash: "e782045df67ba48e441ccb105da8fc85", 20 | SystemLanguageCode: "en", 21 | DeviceModel: "Server", 22 | SystemVersion: "1.0.0", 23 | ApplicationVersion: "1.0.0", 24 | UseMessageDatabase: true, 25 | UseFileDatabase: true, 26 | UseChatInfoDatabase: true, 27 | UseTestDataCenter: false, 28 | DatabaseDirectory: "./tdlib-db", 29 | FileDirectory: "./tdlib-files", 30 | IgnoreFileNames: false, 31 | }) 32 | 33 | // Handle Ctrl+C 34 | ch := make(chan os.Signal, 2) 35 | signal.Notify(ch, os.Interrupt, syscall.SIGTERM) 36 | go func() { 37 | <-ch 38 | client.DestroyInstance() 39 | os.Exit(1) 40 | }() 41 | 42 | // Wait while we get AuthorizationReady! 43 | // Note: See authorization example for complete auhtorization sequence example 44 | currentState, _ := client.Authorize() 45 | for ; currentState.GetAuthorizationStateEnum() != tdlib.AuthorizationStateReadyType; currentState, _ = client.Authorize() { 46 | time.Sleep(300 * time.Millisecond) 47 | } 48 | 49 | // Send "/start" text every 5 seconds to Forsquare bot chat 50 | // Should get chatID somehow, check out "getChats" example 51 | chatID := int64(198529620) // Foursquare bot chat id 52 | 53 | inputMsg := tdlib.NewInputMessagePhoto(tdlib.NewInputFileLocal("./bunny.jpg"), nil, nil, 400, 400, 54 | tdlib.NewFormattedText("A photo sent from go-tdlib!", nil), 0) 55 | client.SendMessage(chatID, 0, false, false, nil, inputMsg) 56 | 57 | } 58 | -------------------------------------------------------------------------------- /botCommands.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // BotCommands Contains a list of bot commands 9 | type BotCommands struct { 10 | tdCommon 11 | BotUserId int64 `json:"bot_user_id"` // Bot's user identifier 12 | Commands []BotCommand `json:"commands"` // List of bot commands 13 | } 14 | 15 | // MessageType return the string telegram-type of BotCommands 16 | func (botCommands *BotCommands) MessageType() string { 17 | return "botCommands" 18 | } 19 | 20 | // NewBotCommands creates a new BotCommands 21 | // 22 | // @param botUserId Bot's user identifier 23 | // @param commands List of bot commands 24 | func NewBotCommands(botUserId int64, commands []BotCommand) *BotCommands { 25 | botCommandsTemp := BotCommands{ 26 | tdCommon: tdCommon{Type: "botCommands"}, 27 | BotUserId: botUserId, 28 | Commands: commands, 29 | } 30 | 31 | return &botCommandsTemp 32 | } 33 | 34 | // GetCommands Returns the list of commands supported by the bot for the given user scope and language; for bots only 35 | // @param scope The scope to which the commands are relevant; pass null to get commands in the default bot command scope 36 | // @param languageCode A two-letter ISO 639-1 country code or an empty string 37 | func (client *Client) GetCommands(scope BotCommandScope, languageCode string) (*BotCommands, error) { 38 | result, err := client.SendAndCatch(UpdateData{ 39 | "@type": "getCommands", 40 | "scope": scope, 41 | "language_code": languageCode, 42 | }) 43 | 44 | if err != nil { 45 | return nil, err 46 | } 47 | 48 | if result.Data["@type"].(string) == "error" { 49 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 50 | } 51 | 52 | var botCommands BotCommands 53 | err = json.Unmarshal(result.Raw, &botCommands) 54 | return &botCommands, err 55 | } 56 | -------------------------------------------------------------------------------- /messageCopyOptions.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // MessageCopyOptions Options to be used when a message content is copied without reference to the original sender. Service messages and messageInvoice can't be copied 4 | type MessageCopyOptions struct { 5 | tdCommon 6 | SendCopy bool `json:"send_copy"` // True, if content of the message needs to be copied without reference to the original sender. Always true if the message is forwarded to a secret chat or is local 7 | ReplaceCaption bool `json:"replace_caption"` // True, if media caption of the message copy needs to be replaced. Ignored if send_copy is false 8 | NewCaption *FormattedText `json:"new_caption"` // New message caption; pass null to copy message without caption. Ignored if replace_caption is false 9 | } 10 | 11 | // MessageType return the string telegram-type of MessageCopyOptions 12 | func (messageCopyOptions *MessageCopyOptions) MessageType() string { 13 | return "messageCopyOptions" 14 | } 15 | 16 | // NewMessageCopyOptions creates a new MessageCopyOptions 17 | // 18 | // @param sendCopy True, if content of the message needs to be copied without reference to the original sender. Always true if the message is forwarded to a secret chat or is local 19 | // @param replaceCaption True, if media caption of the message copy needs to be replaced. Ignored if send_copy is false 20 | // @param newCaption New message caption; pass null to copy message without caption. Ignored if replace_caption is false 21 | func NewMessageCopyOptions(sendCopy bool, replaceCaption bool, newCaption *FormattedText) *MessageCopyOptions { 22 | messageCopyOptionsTemp := MessageCopyOptions{ 23 | tdCommon: tdCommon{Type: "messageCopyOptions"}, 24 | SendCopy: sendCopy, 25 | ReplaceCaption: replaceCaption, 26 | NewCaption: newCaption, 27 | } 28 | 29 | return &messageCopyOptionsTemp 30 | } 31 | -------------------------------------------------------------------------------- /chatPhotos.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ChatPhotos Contains a list of chat or user profile photos 9 | type ChatPhotos struct { 10 | tdCommon 11 | TotalCount int32 `json:"total_count"` // Total number of photos 12 | Photos []ChatPhoto `json:"photos"` // List of photos 13 | } 14 | 15 | // MessageType return the string telegram-type of ChatPhotos 16 | func (chatPhotos *ChatPhotos) MessageType() string { 17 | return "chatPhotos" 18 | } 19 | 20 | // NewChatPhotos creates a new ChatPhotos 21 | // 22 | // @param totalCount Total number of photos 23 | // @param photos List of photos 24 | func NewChatPhotos(totalCount int32, photos []ChatPhoto) *ChatPhotos { 25 | chatPhotosTemp := ChatPhotos{ 26 | tdCommon: tdCommon{Type: "chatPhotos"}, 27 | TotalCount: totalCount, 28 | Photos: photos, 29 | } 30 | 31 | return &chatPhotosTemp 32 | } 33 | 34 | // GetUserProfilePhotos Returns the profile photos of a user. The result of this query may be outdated: some photos might have been deleted already 35 | // @param userId User identifier 36 | // @param offset The number of photos to skip; must be non-negative 37 | // @param limit The maximum number of photos to be returned; up to 100 38 | func (client *Client) GetUserProfilePhotos(userId int64, offset int32, limit int32) (*ChatPhotos, error) { 39 | result, err := client.SendAndCatch(UpdateData{ 40 | "@type": "getUserProfilePhotos", 41 | "user_id": userId, 42 | "offset": offset, 43 | "limit": limit, 44 | }) 45 | 46 | if err != nil { 47 | return nil, err 48 | } 49 | 50 | if result.Data["@type"].(string) == "error" { 51 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 52 | } 53 | 54 | var chatPhotos ChatPhotos 55 | err = json.Unmarshal(result.Raw, &chatPhotos) 56 | return &chatPhotos, err 57 | } 58 | -------------------------------------------------------------------------------- /orderInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // OrderInfo Order information 9 | type OrderInfo struct { 10 | tdCommon 11 | Name string `json:"name"` // Name of the user 12 | PhoneNumber string `json:"phone_number"` // Phone number of the user 13 | EmailAddress string `json:"email_address"` // Email address of the user 14 | ShippingAddress *Address `json:"shipping_address"` // Shipping address for this order; may be null 15 | } 16 | 17 | // MessageType return the string telegram-type of OrderInfo 18 | func (orderInfo *OrderInfo) MessageType() string { 19 | return "orderInfo" 20 | } 21 | 22 | // NewOrderInfo creates a new OrderInfo 23 | // 24 | // @param name Name of the user 25 | // @param phoneNumber Phone number of the user 26 | // @param emailAddress Email address of the user 27 | // @param shippingAddress Shipping address for this order; may be null 28 | func NewOrderInfo(name string, phoneNumber string, emailAddress string, shippingAddress *Address) *OrderInfo { 29 | orderInfoTemp := OrderInfo{ 30 | tdCommon: tdCommon{Type: "orderInfo"}, 31 | Name: name, 32 | PhoneNumber: phoneNumber, 33 | EmailAddress: emailAddress, 34 | ShippingAddress: shippingAddress, 35 | } 36 | 37 | return &orderInfoTemp 38 | } 39 | 40 | // GetSavedOrderInfo Returns saved order info, if any 41 | func (client *Client) GetSavedOrderInfo() (*OrderInfo, error) { 42 | result, err := client.SendAndCatch(UpdateData{ 43 | "@type": "getSavedOrderInfo", 44 | }) 45 | 46 | if err != nil { 47 | return nil, err 48 | } 49 | 50 | if result.Data["@type"].(string) == "error" { 51 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 52 | } 53 | 54 | var orderInfo OrderInfo 55 | err = json.Unmarshal(result.Raw, &orderInfo) 56 | return &orderInfo, err 57 | } 58 | -------------------------------------------------------------------------------- /groupCallID.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // GroupCallId Contains the group call identifier 9 | type GroupCallId struct { 10 | tdCommon 11 | Id int32 `json:"id"` // Group call identifier 12 | } 13 | 14 | // MessageType return the string telegram-type of GroupCallId 15 | func (groupCallId *GroupCallId) MessageType() string { 16 | return "groupCallId" 17 | } 18 | 19 | // NewGroupCallId creates a new GroupCallId 20 | // 21 | // @param id Group call identifier 22 | func NewGroupCallId(id int32) *GroupCallId { 23 | groupCallIdTemp := GroupCallId{ 24 | tdCommon: tdCommon{Type: "groupCallId"}, 25 | Id: id, 26 | } 27 | 28 | return &groupCallIdTemp 29 | } 30 | 31 | // CreateVideoChat Creates a video chat (a group call bound to a chat). Available only for basic groups, supergroups and channels; requires can_manage_video_chats rights 32 | // @param chatId Chat identifier, in which the video chat will be created 33 | // @param title Group call title; if empty, chat title will be used 34 | // @param startDate Point in time (Unix timestamp) when the group call is supposed to be started by an administrator; 0 to start the video chat immediately. The date must be at least 10 seconds and at most 8 days in the future 35 | func (client *Client) CreateVideoChat(chatId int64, title string, startDate int32) (*GroupCallId, error) { 36 | result, err := client.SendAndCatch(UpdateData{ 37 | "@type": "createVideoChat", 38 | "chat_id": chatId, 39 | "title": title, 40 | "start_date": startDate, 41 | }) 42 | 43 | if err != nil { 44 | return nil, err 45 | } 46 | 47 | if result.Data["@type"].(string) == "error" { 48 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 49 | } 50 | 51 | var groupCallId GroupCallId 52 | err = json.Unmarshal(result.Raw, &groupCallId) 53 | return &groupCallId, err 54 | } 55 | -------------------------------------------------------------------------------- /thumbnail.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // Thumbnail Represents a thumbnail 8 | type Thumbnail struct { 9 | tdCommon 10 | Format ThumbnailFormat `json:"format"` // Thumbnail format 11 | Width int32 `json:"width"` // Thumbnail width 12 | Height int32 `json:"height"` // Thumbnail height 13 | File *File `json:"file"` // The thumbnail 14 | } 15 | 16 | // MessageType return the string telegram-type of Thumbnail 17 | func (thumbnail *Thumbnail) MessageType() string { 18 | return "thumbnail" 19 | } 20 | 21 | // NewThumbnail creates a new Thumbnail 22 | // 23 | // @param format Thumbnail format 24 | // @param width Thumbnail width 25 | // @param height Thumbnail height 26 | // @param file The thumbnail 27 | func NewThumbnail(format ThumbnailFormat, width int32, height int32, file *File) *Thumbnail { 28 | thumbnailTemp := Thumbnail{ 29 | tdCommon: tdCommon{Type: "thumbnail"}, 30 | Format: format, 31 | Width: width, 32 | Height: height, 33 | File: file, 34 | } 35 | 36 | return &thumbnailTemp 37 | } 38 | 39 | // UnmarshalJSON unmarshal to json 40 | func (thumbnail *Thumbnail) UnmarshalJSON(b []byte) error { 41 | var objMap map[string]*json.RawMessage 42 | err := json.Unmarshal(b, &objMap) 43 | if err != nil { 44 | return err 45 | } 46 | tempObj := struct { 47 | tdCommon 48 | Width int32 `json:"width"` // Thumbnail width 49 | Height int32 `json:"height"` // Thumbnail height 50 | File *File `json:"file"` // The thumbnail 51 | }{} 52 | err = json.Unmarshal(b, &tempObj) 53 | if err != nil { 54 | return err 55 | } 56 | 57 | thumbnail.tdCommon = tempObj.tdCommon 58 | thumbnail.Width = tempObj.Width 59 | thumbnail.Height = tempObj.Height 60 | thumbnail.File = tempObj.File 61 | 62 | fieldFormat, _ := unmarshalThumbnailFormat(objMap["format"]) 63 | thumbnail.Format = fieldFormat 64 | 65 | return nil 66 | } 67 | -------------------------------------------------------------------------------- /chatStatisticsAdministratorActionsInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ChatStatisticsAdministratorActionsInfo Contains statistics about administrator actions done by a user 4 | type ChatStatisticsAdministratorActionsInfo struct { 5 | tdCommon 6 | UserId int64 `json:"user_id"` // Administrator user identifier 7 | DeletedMessageCount int32 `json:"deleted_message_count"` // Number of messages deleted by the administrator 8 | BannedUserCount int32 `json:"banned_user_count"` // Number of users banned by the administrator 9 | RestrictedUserCount int32 `json:"restricted_user_count"` // Number of users restricted by the administrator 10 | } 11 | 12 | // MessageType return the string telegram-type of ChatStatisticsAdministratorActionsInfo 13 | func (chatStatisticsAdministratorActionsInfo *ChatStatisticsAdministratorActionsInfo) MessageType() string { 14 | return "chatStatisticsAdministratorActionsInfo" 15 | } 16 | 17 | // NewChatStatisticsAdministratorActionsInfo creates a new ChatStatisticsAdministratorActionsInfo 18 | // 19 | // @param userId Administrator user identifier 20 | // @param deletedMessageCount Number of messages deleted by the administrator 21 | // @param bannedUserCount Number of users banned by the administrator 22 | // @param restrictedUserCount Number of users restricted by the administrator 23 | func NewChatStatisticsAdministratorActionsInfo(userId int64, deletedMessageCount int32, bannedUserCount int32, restrictedUserCount int32) *ChatStatisticsAdministratorActionsInfo { 24 | chatStatisticsAdministratorActionsInfoTemp := ChatStatisticsAdministratorActionsInfo{ 25 | tdCommon: tdCommon{Type: "chatStatisticsAdministratorActionsInfo"}, 26 | UserId: userId, 27 | DeletedMessageCount: deletedMessageCount, 28 | BannedUserCount: bannedUserCount, 29 | RestrictedUserCount: restrictedUserCount, 30 | } 31 | 32 | return &chatStatisticsAdministratorActionsInfoTemp 33 | } 34 | -------------------------------------------------------------------------------- /profilePhoto.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // ProfilePhoto Describes a user profile photo 4 | type ProfilePhoto struct { 5 | tdCommon 6 | 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 7 | Small *File `json:"small"` // A small (160x160) user profile photo. The file can be downloaded only before the photo is changed 8 | Big *File `json:"big"` // A big (640x640) user profile photo. The file can be downloaded only before the photo is changed 9 | Minithumbnail *Minithumbnail `json:"minithumbnail"` // User profile photo minithumbnail; may be null 10 | HasAnimation bool `json:"has_animation"` // True, if the photo has animated variant 11 | } 12 | 13 | // MessageType return the string telegram-type of ProfilePhoto 14 | func (profilePhoto *ProfilePhoto) MessageType() string { 15 | return "profilePhoto" 16 | } 17 | 18 | // NewProfilePhoto creates a new ProfilePhoto 19 | // 20 | // @param id Photo identifier; 0 for an empty photo. Can be used to find a photo in a list of user profile photos 21 | // @param small A small (160x160) user profile photo. The file can be downloaded only before the photo is changed 22 | // @param big A big (640x640) user profile photo. The file can be downloaded only before the photo is changed 23 | // @param minithumbnail User profile photo minithumbnail; may be null 24 | // @param hasAnimation True, if the photo has animated variant 25 | func NewProfilePhoto(id JSONInt64, small *File, big *File, minithumbnail *Minithumbnail, hasAnimation bool) *ProfilePhoto { 26 | profilePhotoTemp := ProfilePhoto{ 27 | tdCommon: tdCommon{Type: "profilePhoto"}, 28 | Id: id, 29 | Small: small, 30 | Big: big, 31 | Minithumbnail: minithumbnail, 32 | HasAnimation: hasAnimation, 33 | } 34 | 35 | return &profilePhotoTemp 36 | } 37 | -------------------------------------------------------------------------------- /languagePackStrings.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // LanguagePackStrings Contains a list of language pack strings 9 | type LanguagePackStrings struct { 10 | tdCommon 11 | Strings []LanguagePackString `json:"strings"` // A list of language pack strings 12 | } 13 | 14 | // MessageType return the string telegram-type of LanguagePackStrings 15 | func (languagePackStrings *LanguagePackStrings) MessageType() string { 16 | return "languagePackStrings" 17 | } 18 | 19 | // NewLanguagePackStrings creates a new LanguagePackStrings 20 | // 21 | // @param strings A list of language pack strings 22 | func NewLanguagePackStrings(strings []LanguagePackString) *LanguagePackStrings { 23 | languagePackStringsTemp := LanguagePackStrings{ 24 | tdCommon: tdCommon{Type: "languagePackStrings"}, 25 | Strings: strings, 26 | } 27 | 28 | return &languagePackStringsTemp 29 | } 30 | 31 | // GetLanguagePackStrings Returns strings from a language pack in the current localization target by their keys. Can be called before authorization 32 | // @param languagePackId Language pack identifier of the strings to be returned 33 | // @param keys Language pack keys of the strings to be returned; leave empty to request all available strings 34 | func (client *Client) GetLanguagePackStrings(languagePackId string, keys []string) (*LanguagePackStrings, error) { 35 | result, err := client.SendAndCatch(UpdateData{ 36 | "@type": "getLanguagePackStrings", 37 | "language_pack_id": languagePackId, 38 | "keys": keys, 39 | }) 40 | 41 | if err != nil { 42 | return nil, err 43 | } 44 | 45 | if result.Data["@type"].(string) == "error" { 46 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 47 | } 48 | 49 | var languagePackStrings LanguagePackStrings 50 | err = json.Unmarshal(result.Raw, &languagePackStrings) 51 | return &languagePackStrings, err 52 | } 53 | -------------------------------------------------------------------------------- /deepLinkInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // DeepLinkInfo Contains information about a tg: deep link 9 | type DeepLinkInfo struct { 10 | tdCommon 11 | Text *FormattedText `json:"text"` // Text to be shown to the user 12 | NeedUpdateApplication bool `json:"need_update_application"` // True, if the user must be asked to update the application 13 | } 14 | 15 | // MessageType return the string telegram-type of DeepLinkInfo 16 | func (deepLinkInfo *DeepLinkInfo) MessageType() string { 17 | return "deepLinkInfo" 18 | } 19 | 20 | // NewDeepLinkInfo creates a new DeepLinkInfo 21 | // 22 | // @param text Text to be shown to the user 23 | // @param needUpdateApplication True, if the user must be asked to update the application 24 | func NewDeepLinkInfo(text *FormattedText, needUpdateApplication bool) *DeepLinkInfo { 25 | deepLinkInfoTemp := DeepLinkInfo{ 26 | tdCommon: tdCommon{Type: "deepLinkInfo"}, 27 | Text: text, 28 | NeedUpdateApplication: needUpdateApplication, 29 | } 30 | 31 | return &deepLinkInfoTemp 32 | } 33 | 34 | // 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 35 | // @param link The link 36 | func (client *Client) GetDeepLinkInfo(link string) (*DeepLinkInfo, error) { 37 | result, err := client.SendAndCatch(UpdateData{ 38 | "@type": "getDeepLinkInfo", 39 | "link": link, 40 | }) 41 | 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | if result.Data["@type"].(string) == "error" { 47 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 48 | } 49 | 50 | var deepLinkInfo DeepLinkInfo 51 | err = json.Unmarshal(result.Raw, &deepLinkInfo) 52 | return &deepLinkInfo, err 53 | } 54 | -------------------------------------------------------------------------------- /textEntity.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // TextEntity Represents a part of the text that needs to be formatted in some unusual way 8 | type TextEntity struct { 9 | tdCommon 10 | Offset int32 `json:"offset"` // Offset of the entity, in UTF-16 code units 11 | Length int32 `json:"length"` // Length of the entity, in UTF-16 code units 12 | Type TextEntityType `json:"type"` // Type of the entity 13 | } 14 | 15 | // MessageType return the string telegram-type of TextEntity 16 | func (textEntity *TextEntity) MessageType() string { 17 | return "textEntity" 18 | } 19 | 20 | // NewTextEntity creates a new TextEntity 21 | // 22 | // @param offset Offset of the entity, in UTF-16 code units 23 | // @param length Length of the entity, in UTF-16 code units 24 | // @param typeParam Type of the entity 25 | func NewTextEntity(offset int32, length int32, typeParam TextEntityType) *TextEntity { 26 | textEntityTemp := TextEntity{ 27 | tdCommon: tdCommon{Type: "textEntity"}, 28 | Offset: offset, 29 | Length: length, 30 | Type: typeParam, 31 | } 32 | 33 | return &textEntityTemp 34 | } 35 | 36 | // UnmarshalJSON unmarshal to json 37 | func (textEntity *TextEntity) UnmarshalJSON(b []byte) error { 38 | var objMap map[string]*json.RawMessage 39 | err := json.Unmarshal(b, &objMap) 40 | if err != nil { 41 | return err 42 | } 43 | tempObj := struct { 44 | tdCommon 45 | Offset int32 `json:"offset"` // Offset of the entity, in UTF-16 code units 46 | Length int32 `json:"length"` // Length of the entity, in UTF-16 code units 47 | 48 | }{} 49 | err = json.Unmarshal(b, &tempObj) 50 | if err != nil { 51 | return err 52 | } 53 | 54 | textEntity.tdCommon = tempObj.tdCommon 55 | textEntity.Offset = tempObj.Offset 56 | textEntity.Length = tempObj.Length 57 | 58 | fieldType, _ := unmarshalTextEntityType(objMap["type"]) 59 | textEntity.Type = fieldType 60 | 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /paymentFormTheme.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // PaymentFormTheme Theme colors for a payment form 4 | type PaymentFormTheme struct { 5 | tdCommon 6 | BackgroundColor int32 `json:"background_color"` // A color of the payment form background in the RGB24 format 7 | TextColor int32 `json:"text_color"` // A color of text in the RGB24 format 8 | HintColor int32 `json:"hint_color"` // A color of hints in the RGB24 format 9 | LinkColor int32 `json:"link_color"` // A color of links in the RGB24 format 10 | ButtonColor int32 `json:"button_color"` // A color of the buttons in the RGB24 format 11 | ButtonTextColor int32 `json:"button_text_color"` // A color of text on the buttons in the RGB24 format 12 | } 13 | 14 | // MessageType return the string telegram-type of PaymentFormTheme 15 | func (paymentFormTheme *PaymentFormTheme) MessageType() string { 16 | return "paymentFormTheme" 17 | } 18 | 19 | // NewPaymentFormTheme creates a new PaymentFormTheme 20 | // 21 | // @param backgroundColor A color of the payment form background in the RGB24 format 22 | // @param textColor A color of text in the RGB24 format 23 | // @param hintColor A color of hints in the RGB24 format 24 | // @param linkColor A color of links in the RGB24 format 25 | // @param buttonColor A color of the buttons in the RGB24 format 26 | // @param buttonTextColor A color of text on the buttons in the RGB24 format 27 | func NewPaymentFormTheme(backgroundColor int32, textColor int32, hintColor int32, linkColor int32, buttonColor int32, buttonTextColor int32) *PaymentFormTheme { 28 | paymentFormThemeTemp := PaymentFormTheme{ 29 | tdCommon: tdCommon{Type: "paymentFormTheme"}, 30 | BackgroundColor: backgroundColor, 31 | TextColor: textColor, 32 | HintColor: hintColor, 33 | LinkColor: linkColor, 34 | ButtonColor: buttonColor, 35 | ButtonTextColor: buttonTextColor, 36 | } 37 | 38 | return &paymentFormThemeTemp 39 | } 40 | -------------------------------------------------------------------------------- /chatsNearby.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ChatsNearby Represents a list of chats located nearby 9 | type ChatsNearby struct { 10 | tdCommon 11 | UsersNearby []ChatNearby `json:"users_nearby"` // List of users nearby 12 | SupergroupsNearby []ChatNearby `json:"supergroups_nearby"` // List of location-based supergroups nearby 13 | } 14 | 15 | // MessageType return the string telegram-type of ChatsNearby 16 | func (chatsNearby *ChatsNearby) MessageType() string { 17 | return "chatsNearby" 18 | } 19 | 20 | // NewChatsNearby creates a new ChatsNearby 21 | // 22 | // @param usersNearby List of users nearby 23 | // @param supergroupsNearby List of location-based supergroups nearby 24 | func NewChatsNearby(usersNearby []ChatNearby, supergroupsNearby []ChatNearby) *ChatsNearby { 25 | chatsNearbyTemp := ChatsNearby{ 26 | tdCommon: tdCommon{Type: "chatsNearby"}, 27 | UsersNearby: usersNearby, 28 | SupergroupsNearby: supergroupsNearby, 29 | } 30 | 31 | return &chatsNearbyTemp 32 | } 33 | 34 | // 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 must be sent again every 25 seconds with adjusted location to not miss new chats 35 | // @param location Current user location 36 | func (client *Client) SearchChatsNearby(location *Location) (*ChatsNearby, error) { 37 | result, err := client.SendAndCatch(UpdateData{ 38 | "@type": "searchChatsNearby", 39 | "location": location, 40 | }) 41 | 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | if result.Data["@type"].(string) == "error" { 47 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 48 | } 49 | 50 | var chatsNearby ChatsNearby 51 | err = json.Unmarshal(result.Raw, &chatsNearby) 52 | return &chatsNearby, err 53 | } 54 | -------------------------------------------------------------------------------- /iDentityDocument.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // IdentityDocument An identity document 4 | type IdentityDocument struct { 5 | tdCommon 6 | Number string `json:"number"` // Document number; 1-24 characters 7 | ExpiryDate *Date `json:"expiry_date"` // Document expiry date; may be null if not applicable 8 | FrontSide *DatedFile `json:"front_side"` // Front side of the document 9 | ReverseSide *DatedFile `json:"reverse_side"` // Reverse side of the document; only for driver license and identity card; may be null 10 | Selfie *DatedFile `json:"selfie"` // Selfie with the document; may be null 11 | Translation []DatedFile `json:"translation"` // List of files containing a certified English translation of the document 12 | } 13 | 14 | // MessageType return the string telegram-type of IdentityDocument 15 | func (identityDocument *IdentityDocument) MessageType() string { 16 | return "identityDocument" 17 | } 18 | 19 | // NewIdentityDocument creates a new IdentityDocument 20 | // 21 | // @param number Document number; 1-24 characters 22 | // @param expiryDate Document expiry date; may be null if not applicable 23 | // @param frontSide Front side of the document 24 | // @param reverseSide Reverse side of the document; only for driver license and identity card; may be null 25 | // @param selfie Selfie with the document; may be null 26 | // @param translation List of files containing a certified English translation of the document 27 | func NewIdentityDocument(number string, expiryDate *Date, frontSide *DatedFile, reverseSide *DatedFile, selfie *DatedFile, translation []DatedFile) *IdentityDocument { 28 | identityDocumentTemp := IdentityDocument{ 29 | tdCommon: tdCommon{Type: "identityDocument"}, 30 | Number: number, 31 | ExpiryDate: expiryDate, 32 | FrontSide: frontSide, 33 | ReverseSide: reverseSide, 34 | Selfie: selfie, 35 | Translation: translation, 36 | } 37 | 38 | return &identityDocumentTemp 39 | } 40 | -------------------------------------------------------------------------------- /networkStatistics.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // NetworkStatistics A full list of available network statistic entries 9 | type NetworkStatistics struct { 10 | tdCommon 11 | SinceDate int32 `json:"since_date"` // Point in time (Unix timestamp) from which the statistics are collected 12 | Entries []NetworkStatisticsEntry `json:"entries"` // Network statistics entries 13 | } 14 | 15 | // MessageType return the string telegram-type of NetworkStatistics 16 | func (networkStatistics *NetworkStatistics) MessageType() string { 17 | return "networkStatistics" 18 | } 19 | 20 | // NewNetworkStatistics creates a new NetworkStatistics 21 | // 22 | // @param sinceDate Point in time (Unix timestamp) from which the statistics are collected 23 | // @param entries Network statistics entries 24 | func NewNetworkStatistics(sinceDate int32, entries []NetworkStatisticsEntry) *NetworkStatistics { 25 | networkStatisticsTemp := NetworkStatistics{ 26 | tdCommon: tdCommon{Type: "networkStatistics"}, 27 | SinceDate: sinceDate, 28 | Entries: entries, 29 | } 30 | 31 | return &networkStatisticsTemp 32 | } 33 | 34 | // GetNetworkStatistics Returns network data usage statistics. Can be called before authorization 35 | // @param onlyCurrent If true, returns only data for the current library launch 36 | func (client *Client) GetNetworkStatistics(onlyCurrent bool) (*NetworkStatistics, error) { 37 | result, err := client.SendAndCatch(UpdateData{ 38 | "@type": "getNetworkStatistics", 39 | "only_current": onlyCurrent, 40 | }) 41 | 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | if result.Data["@type"].(string) == "error" { 47 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 48 | } 49 | 50 | var networkStatistics NetworkStatistics 51 | err = json.Unmarshal(result.Raw, &networkStatistics) 52 | return &networkStatistics, err 53 | } 54 | -------------------------------------------------------------------------------- /localizationTargetInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // LocalizationTargetInfo Contains information about the current localization target 9 | type LocalizationTargetInfo struct { 10 | tdCommon 11 | LanguagePacks []LanguagePackInfo `json:"language_packs"` // List of available language packs for this application 12 | } 13 | 14 | // MessageType return the string telegram-type of LocalizationTargetInfo 15 | func (localizationTargetInfo *LocalizationTargetInfo) MessageType() string { 16 | return "localizationTargetInfo" 17 | } 18 | 19 | // NewLocalizationTargetInfo creates a new LocalizationTargetInfo 20 | // 21 | // @param languagePacks List of available language packs for this application 22 | func NewLocalizationTargetInfo(languagePacks []LanguagePackInfo) *LocalizationTargetInfo { 23 | localizationTargetInfoTemp := LocalizationTargetInfo{ 24 | tdCommon: tdCommon{Type: "localizationTargetInfo"}, 25 | LanguagePacks: languagePacks, 26 | } 27 | 28 | return &localizationTargetInfoTemp 29 | } 30 | 31 | // GetLocalizationTargetInfo Returns information about the current localization target. This is an offline request if only_local is true. Can be called before authorization 32 | // @param onlyLocal If true, returns only locally available information without sending network requests 33 | func (client *Client) GetLocalizationTargetInfo(onlyLocal bool) (*LocalizationTargetInfo, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getLocalizationTargetInfo", 36 | "only_local": onlyLocal, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var localizationTargetInfo LocalizationTargetInfo 48 | err = json.Unmarshal(result.Raw, &localizationTargetInfo) 49 | return &localizationTargetInfo, err 50 | } 51 | -------------------------------------------------------------------------------- /groupCallRecentSpeaker.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // GroupCallRecentSpeaker Describes a recently speaking participant in a group call 8 | type GroupCallRecentSpeaker struct { 9 | tdCommon 10 | ParticipantId MessageSender `json:"participant_id"` // Group call participant identifier 11 | IsSpeaking bool `json:"is_speaking"` // True, is the user has spoken recently 12 | } 13 | 14 | // MessageType return the string telegram-type of GroupCallRecentSpeaker 15 | func (groupCallRecentSpeaker *GroupCallRecentSpeaker) MessageType() string { 16 | return "groupCallRecentSpeaker" 17 | } 18 | 19 | // NewGroupCallRecentSpeaker creates a new GroupCallRecentSpeaker 20 | // 21 | // @param participantId Group call participant identifier 22 | // @param isSpeaking True, is the user has spoken recently 23 | func NewGroupCallRecentSpeaker(participantId MessageSender, isSpeaking bool) *GroupCallRecentSpeaker { 24 | groupCallRecentSpeakerTemp := GroupCallRecentSpeaker{ 25 | tdCommon: tdCommon{Type: "groupCallRecentSpeaker"}, 26 | ParticipantId: participantId, 27 | IsSpeaking: isSpeaking, 28 | } 29 | 30 | return &groupCallRecentSpeakerTemp 31 | } 32 | 33 | // UnmarshalJSON unmarshal to json 34 | func (groupCallRecentSpeaker *GroupCallRecentSpeaker) UnmarshalJSON(b []byte) error { 35 | var objMap map[string]*json.RawMessage 36 | err := json.Unmarshal(b, &objMap) 37 | if err != nil { 38 | return err 39 | } 40 | tempObj := struct { 41 | tdCommon 42 | IsSpeaking bool `json:"is_speaking"` // True, is the user has spoken recently 43 | }{} 44 | err = json.Unmarshal(b, &tempObj) 45 | if err != nil { 46 | return err 47 | } 48 | 49 | groupCallRecentSpeaker.tdCommon = tempObj.tdCommon 50 | groupCallRecentSpeaker.IsSpeaking = tempObj.IsSpeaking 51 | 52 | fieldParticipantId, _ := unmarshalMessageSender(objMap["participant_id"]) 53 | groupCallRecentSpeaker.ParticipantId = fieldParticipantId 54 | 55 | return nil 56 | } 57 | -------------------------------------------------------------------------------- /examples/sendText/sendText.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "os/signal" 7 | "syscall" 8 | "time" 9 | 10 | "github.com/c0re100/go-tdlib" 11 | ) 12 | 13 | func main() { 14 | tdlib.SetLogVerbosityLevel(1) 15 | tdlib.SetFilePath("./errors.txt") 16 | 17 | // Create new instance of client 18 | client := tdlib.NewClient(tdlib.Config{ 19 | APIID: "187786", 20 | APIHash: "e782045df67ba48e441ccb105da8fc85", 21 | SystemLanguageCode: "en", 22 | DeviceModel: "Server", 23 | SystemVersion: "1.0.0", 24 | ApplicationVersion: "1.0.0", 25 | UseMessageDatabase: true, 26 | UseFileDatabase: true, 27 | UseChatInfoDatabase: true, 28 | UseTestDataCenter: false, 29 | DatabaseDirectory: "./tdlib-db", 30 | FileDirectory: "./tdlib-files", 31 | IgnoreFileNames: false, 32 | }) 33 | 34 | // Handle Ctrl+C 35 | ch := make(chan os.Signal, 2) 36 | signal.Notify(ch, os.Interrupt, syscall.SIGTERM) 37 | go func() { 38 | <-ch 39 | client.DestroyInstance() 40 | os.Exit(1) 41 | }() 42 | 43 | // Wait while we get AuthorizationReady! 44 | // Note: See authorization example for complete auhtorization sequence example 45 | currentState, _ := client.Authorize() 46 | for ; currentState.GetAuthorizationStateEnum() != tdlib.AuthorizationStateReadyType; currentState, _ = client.Authorize() { 47 | time.Sleep(300 * time.Millisecond) 48 | } 49 | 50 | // Send "/start" text every 5 seconds to Forsquare bot chat 51 | go func() { 52 | // Should get chatID somehow, check out "getChats" example 53 | chatID := int64(198529620) // Foursquare bot chat id 54 | 55 | inputMsgTxt := tdlib.NewInputMessageText(tdlib.NewFormattedText("/start", nil), true, true) 56 | client.SendMessage(chatID, 0, false, true, nil, inputMsgTxt) 57 | 58 | time.Sleep(5 * time.Second) 59 | }() 60 | 61 | // rawUpdates gets all updates comming from tdlib 62 | rawUpdates := client.GetRawUpdatesChannel(100) 63 | for update := range rawUpdates { 64 | // Show all updates 65 | fmt.Println(update.Data) 66 | fmt.Print("\n\n") 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /storageStatisticsByFileType.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // StorageStatisticsByFileType Contains the storage usage statistics for a specific file type 8 | type StorageStatisticsByFileType struct { 9 | tdCommon 10 | FileType FileType `json:"file_type"` // File type 11 | Size int64 `json:"size"` // Total size of the files, in bytes 12 | Count int32 `json:"count"` // Total number of files 13 | } 14 | 15 | // MessageType return the string telegram-type of StorageStatisticsByFileType 16 | func (storageStatisticsByFileType *StorageStatisticsByFileType) MessageType() string { 17 | return "storageStatisticsByFileType" 18 | } 19 | 20 | // NewStorageStatisticsByFileType creates a new StorageStatisticsByFileType 21 | // 22 | // @param fileType File type 23 | // @param size Total size of the files, in bytes 24 | // @param count Total number of files 25 | func NewStorageStatisticsByFileType(fileType FileType, size int64, count int32) *StorageStatisticsByFileType { 26 | storageStatisticsByFileTypeTemp := StorageStatisticsByFileType{ 27 | tdCommon: tdCommon{Type: "storageStatisticsByFileType"}, 28 | FileType: fileType, 29 | Size: size, 30 | Count: count, 31 | } 32 | 33 | return &storageStatisticsByFileTypeTemp 34 | } 35 | 36 | // UnmarshalJSON unmarshal to json 37 | func (storageStatisticsByFileType *StorageStatisticsByFileType) UnmarshalJSON(b []byte) error { 38 | var objMap map[string]*json.RawMessage 39 | err := json.Unmarshal(b, &objMap) 40 | if err != nil { 41 | return err 42 | } 43 | tempObj := struct { 44 | tdCommon 45 | Size int64 `json:"size"` // Total size of the files, in bytes 46 | Count int32 `json:"count"` // Total number of files 47 | }{} 48 | err = json.Unmarshal(b, &tempObj) 49 | if err != nil { 50 | return err 51 | } 52 | 53 | storageStatisticsByFileType.tdCommon = tempObj.tdCommon 54 | storageStatisticsByFileType.Size = tempObj.Size 55 | storageStatisticsByFileType.Count = tempObj.Count 56 | 57 | fieldFileType, _ := unmarshalFileType(objMap["file_type"]) 58 | storageStatisticsByFileType.FileType = fieldFileType 59 | 60 | return nil 61 | } 62 | -------------------------------------------------------------------------------- /passportElementError.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // PassportElementError Contains the description of an error in a Telegram Passport element 8 | type PassportElementError struct { 9 | tdCommon 10 | Type PassportElementType `json:"type"` // Type of the Telegram Passport element which has the error 11 | Message string `json:"message"` // Error message 12 | Source PassportElementErrorSource `json:"source"` // Error source 13 | } 14 | 15 | // MessageType return the string telegram-type of PassportElementError 16 | func (passportElementError *PassportElementError) MessageType() string { 17 | return "passportElementError" 18 | } 19 | 20 | // NewPassportElementError creates a new PassportElementError 21 | // 22 | // @param typeParam Type of the Telegram Passport element which has the error 23 | // @param message Error message 24 | // @param source Error source 25 | func NewPassportElementError(typeParam PassportElementType, message string, source PassportElementErrorSource) *PassportElementError { 26 | passportElementErrorTemp := PassportElementError{ 27 | tdCommon: tdCommon{Type: "passportElementError"}, 28 | Type: typeParam, 29 | Message: message, 30 | Source: source, 31 | } 32 | 33 | return &passportElementErrorTemp 34 | } 35 | 36 | // UnmarshalJSON unmarshal to json 37 | func (passportElementError *PassportElementError) UnmarshalJSON(b []byte) error { 38 | var objMap map[string]*json.RawMessage 39 | err := json.Unmarshal(b, &objMap) 40 | if err != nil { 41 | return err 42 | } 43 | tempObj := struct { 44 | tdCommon 45 | Message string `json:"message"` // Error message 46 | 47 | }{} 48 | err = json.Unmarshal(b, &tempObj) 49 | if err != nil { 50 | return err 51 | } 52 | 53 | passportElementError.tdCommon = tempObj.tdCommon 54 | passportElementError.Message = tempObj.Message 55 | 56 | fieldType, _ := unmarshalPassportElementType(objMap["type"]) 57 | passportElementError.Type = fieldType 58 | 59 | fieldSource, _ := unmarshalPassportElementErrorSource(objMap["source"]) 60 | passportElementError.Source = fieldSource 61 | 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /chatEvent.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // ChatEvent Represents a chat event 8 | type ChatEvent struct { 9 | tdCommon 10 | Id JSONInt64 `json:"id"` // Chat event identifier 11 | Date int32 `json:"date"` // Point in time (Unix timestamp) when the event happened 12 | MemberId MessageSender `json:"member_id"` // Identifier of the user or chat who performed the action 13 | Action ChatEventAction `json:"action"` // The action 14 | } 15 | 16 | // MessageType return the string telegram-type of ChatEvent 17 | func (chatEvent *ChatEvent) MessageType() string { 18 | return "chatEvent" 19 | } 20 | 21 | // NewChatEvent creates a new ChatEvent 22 | // 23 | // @param id Chat event identifier 24 | // @param date Point in time (Unix timestamp) when the event happened 25 | // @param memberId Identifier of the user or chat who performed the action 26 | // @param action The action 27 | func NewChatEvent(id JSONInt64, date int32, memberId MessageSender, action ChatEventAction) *ChatEvent { 28 | chatEventTemp := ChatEvent{ 29 | tdCommon: tdCommon{Type: "chatEvent"}, 30 | Id: id, 31 | Date: date, 32 | MemberId: memberId, 33 | Action: action, 34 | } 35 | 36 | return &chatEventTemp 37 | } 38 | 39 | // UnmarshalJSON unmarshal to json 40 | func (chatEvent *ChatEvent) UnmarshalJSON(b []byte) error { 41 | var objMap map[string]*json.RawMessage 42 | err := json.Unmarshal(b, &objMap) 43 | if err != nil { 44 | return err 45 | } 46 | tempObj := struct { 47 | tdCommon 48 | Id JSONInt64 `json:"id"` // Chat event identifier 49 | Date int32 `json:"date"` // Point in time (Unix timestamp) when the event happened 50 | 51 | }{} 52 | err = json.Unmarshal(b, &tempObj) 53 | if err != nil { 54 | return err 55 | } 56 | 57 | chatEvent.tdCommon = tempObj.tdCommon 58 | chatEvent.Id = tempObj.Id 59 | chatEvent.Date = tempObj.Date 60 | 61 | fieldMemberId, _ := unmarshalMessageSender(objMap["member_id"]) 62 | chatEvent.MemberId = fieldMemberId 63 | 64 | fieldAction, _ := unmarshalChatEventAction(objMap["action"]) 65 | chatEvent.Action = fieldAction 66 | 67 | return nil 68 | } 69 | -------------------------------------------------------------------------------- /call.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // Call Describes a call 8 | type Call struct { 9 | tdCommon 10 | Id int32 `json:"id"` // Call identifier, not persistent 11 | UserId int64 `json:"user_id"` // Peer user identifier 12 | IsOutgoing bool `json:"is_outgoing"` // True, if the call is outgoing 13 | IsVideo bool `json:"is_video"` // True, if the call is a video call 14 | State CallState `json:"state"` // Call state 15 | } 16 | 17 | // MessageType return the string telegram-type of Call 18 | func (call *Call) MessageType() string { 19 | return "call" 20 | } 21 | 22 | // NewCall creates a new Call 23 | // 24 | // @param id Call identifier, not persistent 25 | // @param userId Peer user identifier 26 | // @param isOutgoing True, if the call is outgoing 27 | // @param isVideo True, if the call is a video call 28 | // @param state Call state 29 | func NewCall(id int32, userId int64, isOutgoing bool, isVideo bool, state CallState) *Call { 30 | callTemp := Call{ 31 | tdCommon: tdCommon{Type: "call"}, 32 | Id: id, 33 | UserId: userId, 34 | IsOutgoing: isOutgoing, 35 | IsVideo: isVideo, 36 | State: state, 37 | } 38 | 39 | return &callTemp 40 | } 41 | 42 | // UnmarshalJSON unmarshal to json 43 | func (call *Call) UnmarshalJSON(b []byte) error { 44 | var objMap map[string]*json.RawMessage 45 | err := json.Unmarshal(b, &objMap) 46 | if err != nil { 47 | return err 48 | } 49 | tempObj := struct { 50 | tdCommon 51 | Id int32 `json:"id"` // Call identifier, not persistent 52 | UserId int64 `json:"user_id"` // Peer user identifier 53 | IsOutgoing bool `json:"is_outgoing"` // True, if the call is outgoing 54 | IsVideo bool `json:"is_video"` // True, if the call is a video call 55 | 56 | }{} 57 | err = json.Unmarshal(b, &tempObj) 58 | if err != nil { 59 | return err 60 | } 61 | 62 | call.tdCommon = tempObj.tdCommon 63 | call.Id = tempObj.Id 64 | call.UserId = tempObj.UserId 65 | call.IsOutgoing = tempObj.IsOutgoing 66 | call.IsVideo = tempObj.IsVideo 67 | 68 | fieldState, _ := unmarshalCallState(objMap["state"]) 69 | call.State = fieldState 70 | 71 | return nil 72 | } 73 | -------------------------------------------------------------------------------- /notification.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // Notification Contains information about a notification 8 | type Notification struct { 9 | tdCommon 10 | Id int32 `json:"id"` // Unique persistent identifier of this notification 11 | Date int32 `json:"date"` // Notification date 12 | IsSilent bool `json:"is_silent"` // True, if the notification was initially silent 13 | Type NotificationType `json:"type"` // Notification type 14 | } 15 | 16 | // MessageType return the string telegram-type of Notification 17 | func (notification *Notification) MessageType() string { 18 | return "notification" 19 | } 20 | 21 | // NewNotification creates a new Notification 22 | // 23 | // @param id Unique persistent identifier of this notification 24 | // @param date Notification date 25 | // @param isSilent True, if the notification was initially silent 26 | // @param typeParam Notification type 27 | func NewNotification(id int32, date int32, isSilent bool, typeParam NotificationType) *Notification { 28 | notificationTemp := Notification{ 29 | tdCommon: tdCommon{Type: "notification"}, 30 | Id: id, 31 | Date: date, 32 | IsSilent: isSilent, 33 | Type: typeParam, 34 | } 35 | 36 | return ¬ificationTemp 37 | } 38 | 39 | // UnmarshalJSON unmarshal to json 40 | func (notification *Notification) UnmarshalJSON(b []byte) error { 41 | var objMap map[string]*json.RawMessage 42 | err := json.Unmarshal(b, &objMap) 43 | if err != nil { 44 | return err 45 | } 46 | tempObj := struct { 47 | tdCommon 48 | Id int32 `json:"id"` // Unique persistent identifier of this notification 49 | Date int32 `json:"date"` // Notification date 50 | IsSilent bool `json:"is_silent"` // True, if the notification was initially silent 51 | 52 | }{} 53 | err = json.Unmarshal(b, &tempObj) 54 | if err != nil { 55 | return err 56 | } 57 | 58 | notification.tdCommon = tempObj.tdCommon 59 | notification.Id = tempObj.Id 60 | notification.Date = tempObj.Date 61 | notification.IsSilent = tempObj.IsSilent 62 | 63 | fieldType, _ := unmarshalNotificationType(objMap["type"]) 64 | notification.Type = fieldType 65 | 66 | return nil 67 | } 68 | -------------------------------------------------------------------------------- /animatedEmoji.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // AnimatedEmoji Describes an animated representation of an emoji 9 | type AnimatedEmoji struct { 10 | tdCommon 11 | Sticker *Sticker `json:"sticker"` // Animated sticker for the emoji 12 | FitzpatrickType int32 `json:"fitzpatrick_type"` // Emoji modifier fitzpatrick type; 0-6; 0 if none 13 | Sound *File `json:"sound"` // File containing the sound to be played when the animated emoji is clicked if any; may be null. The sound is encoded with the Opus codec, and stored inside an OGG container 14 | } 15 | 16 | // MessageType return the string telegram-type of AnimatedEmoji 17 | func (animatedEmoji *AnimatedEmoji) MessageType() string { 18 | return "animatedEmoji" 19 | } 20 | 21 | // NewAnimatedEmoji creates a new AnimatedEmoji 22 | // 23 | // @param sticker Animated sticker for the emoji 24 | // @param fitzpatrickType Emoji modifier fitzpatrick type; 0-6; 0 if none 25 | // @param sound File containing the sound to be played when the animated emoji is clicked if any; may be null. The sound is encoded with the Opus codec, and stored inside an OGG container 26 | func NewAnimatedEmoji(sticker *Sticker, fitzpatrickType int32, sound *File) *AnimatedEmoji { 27 | animatedEmojiTemp := AnimatedEmoji{ 28 | tdCommon: tdCommon{Type: "animatedEmoji"}, 29 | Sticker: sticker, 30 | FitzpatrickType: fitzpatrickType, 31 | Sound: sound, 32 | } 33 | 34 | return &animatedEmojiTemp 35 | } 36 | 37 | // GetAnimatedEmoji Returns an animated emoji corresponding to a given emoji. Returns a 404 error if the emoji has no animated emoji 38 | // @param emoji The emoji 39 | func (client *Client) GetAnimatedEmoji(emoji string) (*AnimatedEmoji, error) { 40 | result, err := client.SendAndCatch(UpdateData{ 41 | "@type": "getAnimatedEmoji", 42 | "emoji": emoji, 43 | }) 44 | 45 | if err != nil { 46 | return nil, err 47 | } 48 | 49 | if result.Data["@type"].(string) == "error" { 50 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 51 | } 52 | 53 | var animatedEmoji AnimatedEmoji 54 | err = json.Unmarshal(result.Raw, &animatedEmoji) 55 | return &animatedEmoji, err 56 | } 57 | -------------------------------------------------------------------------------- /examples/authorization/basicAuthorization.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/c0re100/go-tdlib" 7 | ) 8 | 9 | func main() { 10 | tdlib.SetLogVerbosityLevel(1) 11 | tdlib.SetFilePath("./errors.txt") 12 | 13 | // Create new instance of client 14 | client := tdlib.NewClient(tdlib.Config{ 15 | APIID: "187786", 16 | APIHash: "e782045df67ba48e441ccb105da8fc85", 17 | SystemLanguageCode: "en", 18 | DeviceModel: "Server", 19 | SystemVersion: "1.0.0", 20 | ApplicationVersion: "1.0.0", 21 | UseMessageDatabase: true, 22 | UseFileDatabase: true, 23 | UseChatInfoDatabase: true, 24 | UseTestDataCenter: false, 25 | DatabaseDirectory: "./tdlib-db", 26 | FileDirectory: "./tdlib-files", 27 | IgnoreFileNames: false, 28 | }) 29 | 30 | for { 31 | currentState, _ := client.Authorize() 32 | if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPhoneNumberType { 33 | fmt.Print("Enter phone: ") 34 | var number string 35 | fmt.Scanln(&number) 36 | _, err := client.SendPhoneNumber(number) 37 | if err != nil { 38 | fmt.Printf("Error sending phone number: %v", err) 39 | } 40 | } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitCodeType { 41 | fmt.Print("Enter code: ") 42 | var code string 43 | fmt.Scanln(&code) 44 | _, err := client.SendAuthCode(code) 45 | if err != nil { 46 | fmt.Printf("Error sending auth code : %v", err) 47 | } 48 | } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPasswordType { 49 | fmt.Print("Enter Password: ") 50 | var password string 51 | fmt.Scanln(&password) 52 | _, err := client.SendAuthPassword(password) 53 | if err != nil { 54 | fmt.Printf("Error sending auth password: %v", err) 55 | } 56 | } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateReadyType { 57 | fmt.Println("Authorization Ready! Let's rock") 58 | break 59 | } 60 | } 61 | 62 | // rawUpdates gets all updates comming from tdlib 63 | rawUpdates := client.GetRawUpdatesChannel(100) 64 | for update := range rawUpdates { 65 | // Show all updates 66 | fmt.Println(update.Data) 67 | fmt.Print("\n\n") 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /inputPassportElementError.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // InputPassportElementError Contains the description of an error in a Telegram Passport element; for bots only 8 | type InputPassportElementError struct { 9 | tdCommon 10 | Type PassportElementType `json:"type"` // Type of Telegram Passport element that has the error 11 | Message string `json:"message"` // Error message 12 | Source InputPassportElementErrorSource `json:"source"` // Error source 13 | } 14 | 15 | // MessageType return the string telegram-type of InputPassportElementError 16 | func (inputPassportElementError *InputPassportElementError) MessageType() string { 17 | return "inputPassportElementError" 18 | } 19 | 20 | // NewInputPassportElementError creates a new InputPassportElementError 21 | // 22 | // @param typeParam Type of Telegram Passport element that has the error 23 | // @param message Error message 24 | // @param source Error source 25 | func NewInputPassportElementError(typeParam PassportElementType, message string, source InputPassportElementErrorSource) *InputPassportElementError { 26 | inputPassportElementErrorTemp := InputPassportElementError{ 27 | tdCommon: tdCommon{Type: "inputPassportElementError"}, 28 | Type: typeParam, 29 | Message: message, 30 | Source: source, 31 | } 32 | 33 | return &inputPassportElementErrorTemp 34 | } 35 | 36 | // UnmarshalJSON unmarshal to json 37 | func (inputPassportElementError *InputPassportElementError) UnmarshalJSON(b []byte) error { 38 | var objMap map[string]*json.RawMessage 39 | err := json.Unmarshal(b, &objMap) 40 | if err != nil { 41 | return err 42 | } 43 | tempObj := struct { 44 | tdCommon 45 | Message string `json:"message"` // Error message 46 | 47 | }{} 48 | err = json.Unmarshal(b, &tempObj) 49 | if err != nil { 50 | return err 51 | } 52 | 53 | inputPassportElementError.tdCommon = tempObj.tdCommon 54 | inputPassportElementError.Message = tempObj.Message 55 | 56 | fieldType, _ := unmarshalPassportElementType(objMap["type"]) 57 | inputPassportElementError.Type = fieldType 58 | 59 | fieldSource, _ := unmarshalInputPassportElementErrorSource(objMap["source"]) 60 | inputPassportElementError.Source = fieldSource 61 | 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /chatEvents.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ChatEvents Contains a list of chat events 9 | type ChatEvents struct { 10 | tdCommon 11 | Events []ChatEvent `json:"events"` // List of events 12 | } 13 | 14 | // MessageType return the string telegram-type of ChatEvents 15 | func (chatEvents *ChatEvents) MessageType() string { 16 | return "chatEvents" 17 | } 18 | 19 | // NewChatEvents creates a new ChatEvents 20 | // 21 | // @param events List of events 22 | func NewChatEvents(events []ChatEvent) *ChatEvents { 23 | chatEventsTemp := ChatEvents{ 24 | tdCommon: tdCommon{Type: "chatEvents"}, 25 | Events: events, 26 | } 27 | 28 | return &chatEventsTemp 29 | } 30 | 31 | // 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) 32 | // @param chatId Chat identifier 33 | // @param query Search query by which to filter events 34 | // @param fromEventId Identifier of an event from which to return results. Use 0 to get results from the latest events 35 | // @param limit The maximum number of events to return; up to 100 36 | // @param filters The types of events to return; pass null to get chat events of all types 37 | // @param userIds User identifiers by which to filter events. By default, events relating to all users will be returned 38 | func (client *Client) GetChatEventLog(chatId int64, query string, fromEventId JSONInt64, limit int32, filters *ChatEventLogFilters, userIds []int64) (*ChatEvents, error) { 39 | result, err := client.SendAndCatch(UpdateData{ 40 | "@type": "getChatEventLog", 41 | "chat_id": chatId, 42 | "query": query, 43 | "from_event_id": fromEventId, 44 | "limit": limit, 45 | "filters": filters, 46 | "user_ids": userIds, 47 | }) 48 | 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | if result.Data["@type"].(string) == "error" { 54 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 55 | } 56 | 57 | var chatEvents ChatEvents 58 | err = json.Unmarshal(result.Raw, &chatEvents) 59 | return &chatEvents, err 60 | } 61 | -------------------------------------------------------------------------------- /inputThumbnail.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // 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 8 | type InputThumbnail struct { 9 | tdCommon 10 | Thumbnail InputFile `json:"thumbnail"` // Thumbnail file to send. Sending thumbnails by file_id is currently not supported 11 | Width int32 `json:"width"` // Thumbnail width, usually shouldn't exceed 320. Use 0 if unknown 12 | Height int32 `json:"height"` // Thumbnail height, usually shouldn't exceed 320. Use 0 if unknown 13 | } 14 | 15 | // MessageType return the string telegram-type of InputThumbnail 16 | func (inputThumbnail *InputThumbnail) MessageType() string { 17 | return "inputThumbnail" 18 | } 19 | 20 | // NewInputThumbnail creates a new InputThumbnail 21 | // 22 | // @param thumbnail Thumbnail file to send. Sending thumbnails by file_id is currently not supported 23 | // @param width Thumbnail width, usually shouldn't exceed 320. Use 0 if unknown 24 | // @param height Thumbnail height, usually shouldn't exceed 320. Use 0 if unknown 25 | func NewInputThumbnail(thumbnail InputFile, width int32, height int32) *InputThumbnail { 26 | inputThumbnailTemp := InputThumbnail{ 27 | tdCommon: tdCommon{Type: "inputThumbnail"}, 28 | Thumbnail: thumbnail, 29 | Width: width, 30 | Height: height, 31 | } 32 | 33 | return &inputThumbnailTemp 34 | } 35 | 36 | // UnmarshalJSON unmarshal to json 37 | func (inputThumbnail *InputThumbnail) UnmarshalJSON(b []byte) error { 38 | var objMap map[string]*json.RawMessage 39 | err := json.Unmarshal(b, &objMap) 40 | if err != nil { 41 | return err 42 | } 43 | tempObj := struct { 44 | tdCommon 45 | Width int32 `json:"width"` // Thumbnail width, usually shouldn't exceed 320. Use 0 if unknown 46 | Height int32 `json:"height"` // Thumbnail height, usually shouldn't exceed 320. Use 0 if unknown 47 | }{} 48 | err = json.Unmarshal(b, &tempObj) 49 | if err != nil { 50 | return err 51 | } 52 | 53 | inputThumbnail.tdCommon = tempObj.tdCommon 54 | inputThumbnail.Width = tempObj.Width 55 | inputThumbnail.Height = tempObj.Height 56 | 57 | fieldThumbnail, _ := unmarshalInputFile(objMap["thumbnail"]) 58 | inputThumbnail.Thumbnail = fieldThumbnail 59 | 60 | return nil 61 | } 62 | -------------------------------------------------------------------------------- /callbackQueryAnswer.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // CallbackQueryAnswer Contains a bot's answer to a callback query 9 | type CallbackQueryAnswer struct { 10 | tdCommon 11 | Text string `json:"text"` // Text of the answer 12 | ShowAlert bool `json:"show_alert"` // True, if an alert must be shown to the user instead of a toast notification 13 | Url string `json:"url"` // URL to be opened 14 | } 15 | 16 | // MessageType return the string telegram-type of CallbackQueryAnswer 17 | func (callbackQueryAnswer *CallbackQueryAnswer) MessageType() string { 18 | return "callbackQueryAnswer" 19 | } 20 | 21 | // NewCallbackQueryAnswer creates a new CallbackQueryAnswer 22 | // 23 | // @param text Text of the answer 24 | // @param showAlert True, if an alert must be shown to the user instead of a toast notification 25 | // @param url URL to be opened 26 | func NewCallbackQueryAnswer(text string, showAlert bool, url string) *CallbackQueryAnswer { 27 | callbackQueryAnswerTemp := CallbackQueryAnswer{ 28 | tdCommon: tdCommon{Type: "callbackQueryAnswer"}, 29 | Text: text, 30 | ShowAlert: showAlert, 31 | Url: url, 32 | } 33 | 34 | return &callbackQueryAnswerTemp 35 | } 36 | 37 | // 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 38 | // @param chatId Identifier of the chat with the message 39 | // @param messageId Identifier of the message from which the query originated 40 | // @param payload Query payload 41 | func (client *Client) GetCallbackQueryAnswer(chatId int64, messageId int64, payload CallbackQueryPayload) (*CallbackQueryAnswer, error) { 42 | result, err := client.SendAndCatch(UpdateData{ 43 | "@type": "getCallbackQueryAnswer", 44 | "chat_id": chatId, 45 | "message_id": messageId, 46 | "payload": payload, 47 | }) 48 | 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | if result.Data["@type"].(string) == "error" { 54 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 55 | } 56 | 57 | var callbackQueryAnswer CallbackQueryAnswer 58 | err = json.Unmarshal(result.Raw, &callbackQueryAnswer) 59 | return &callbackQueryAnswer, err 60 | } 61 | -------------------------------------------------------------------------------- /logVerbosityLevel.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // LogVerbosityLevel Contains a TDLib internal log verbosity level 9 | type LogVerbosityLevel struct { 10 | tdCommon 11 | VerbosityLevel int32 `json:"verbosity_level"` // Log verbosity level 12 | } 13 | 14 | // MessageType return the string telegram-type of LogVerbosityLevel 15 | func (logVerbosityLevel *LogVerbosityLevel) MessageType() string { 16 | return "logVerbosityLevel" 17 | } 18 | 19 | // NewLogVerbosityLevel creates a new LogVerbosityLevel 20 | // 21 | // @param verbosityLevel Log verbosity level 22 | func NewLogVerbosityLevel(verbosityLevel int32) *LogVerbosityLevel { 23 | logVerbosityLevelTemp := LogVerbosityLevel{ 24 | tdCommon: tdCommon{Type: "logVerbosityLevel"}, 25 | VerbosityLevel: verbosityLevel, 26 | } 27 | 28 | return &logVerbosityLevelTemp 29 | } 30 | 31 | // GetLogVerbosityLevel Returns current verbosity level of the internal logging of TDLib. Can be called synchronously 32 | func (client *Client) GetLogVerbosityLevel() (*LogVerbosityLevel, error) { 33 | result, err := client.SendAndCatch(UpdateData{ 34 | "@type": "getLogVerbosityLevel", 35 | }) 36 | 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if result.Data["@type"].(string) == "error" { 42 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 43 | } 44 | 45 | var logVerbosityLevel LogVerbosityLevel 46 | err = json.Unmarshal(result.Raw, &logVerbosityLevel) 47 | return &logVerbosityLevel, err 48 | } 49 | 50 | // GetLogTagVerbosityLevel Returns current verbosity level for a specified TDLib internal log tag. Can be called synchronously 51 | // @param tag Logging tag to change verbosity level 52 | func (client *Client) GetLogTagVerbosityLevel(tag string) (*LogVerbosityLevel, error) { 53 | result, err := client.SendAndCatch(UpdateData{ 54 | "@type": "getLogTagVerbosityLevel", 55 | "tag": tag, 56 | }) 57 | 58 | if err != nil { 59 | return nil, err 60 | } 61 | 62 | if result.Data["@type"].(string) == "error" { 63 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 64 | } 65 | 66 | var logVerbosityLevel LogVerbosityLevel 67 | err = json.Unmarshal(result.Raw, &logVerbosityLevel) 68 | return &logVerbosityLevel, err 69 | } 70 | -------------------------------------------------------------------------------- /callServer.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // CallServer Describes a server for relaying call data 8 | type CallServer struct { 9 | tdCommon 10 | Id JSONInt64 `json:"id"` // Server identifier 11 | IpAddress string `json:"ip_address"` // Server IPv4 address 12 | Ipv6Address string `json:"ipv6_address"` // Server IPv6 address 13 | Port int32 `json:"port"` // Server port number 14 | Type CallServerType `json:"type"` // Server type 15 | } 16 | 17 | // MessageType return the string telegram-type of CallServer 18 | func (callServer *CallServer) MessageType() string { 19 | return "callServer" 20 | } 21 | 22 | // NewCallServer creates a new CallServer 23 | // 24 | // @param id Server identifier 25 | // @param ipAddress Server IPv4 address 26 | // @param ipv6Address Server IPv6 address 27 | // @param port Server port number 28 | // @param typeParam Server type 29 | func NewCallServer(id JSONInt64, ipAddress string, ipv6Address string, port int32, typeParam CallServerType) *CallServer { 30 | callServerTemp := CallServer{ 31 | tdCommon: tdCommon{Type: "callServer"}, 32 | Id: id, 33 | IpAddress: ipAddress, 34 | Ipv6Address: ipv6Address, 35 | Port: port, 36 | Type: typeParam, 37 | } 38 | 39 | return &callServerTemp 40 | } 41 | 42 | // UnmarshalJSON unmarshal to json 43 | func (callServer *CallServer) UnmarshalJSON(b []byte) error { 44 | var objMap map[string]*json.RawMessage 45 | err := json.Unmarshal(b, &objMap) 46 | if err != nil { 47 | return err 48 | } 49 | tempObj := struct { 50 | tdCommon 51 | Id JSONInt64 `json:"id"` // Server identifier 52 | IpAddress string `json:"ip_address"` // Server IPv4 address 53 | Ipv6Address string `json:"ipv6_address"` // Server IPv6 address 54 | Port int32 `json:"port"` // Server port number 55 | 56 | }{} 57 | err = json.Unmarshal(b, &tempObj) 58 | if err != nil { 59 | return err 60 | } 61 | 62 | callServer.tdCommon = tempObj.tdCommon 63 | callServer.Id = tempObj.Id 64 | callServer.IpAddress = tempObj.IpAddress 65 | callServer.Ipv6Address = tempObj.Ipv6Address 66 | callServer.Port = tempObj.Port 67 | 68 | fieldType, _ := unmarshalCallServerType(objMap["type"]) 69 | callServer.Type = fieldType 70 | 71 | return nil 72 | } 73 | -------------------------------------------------------------------------------- /draftMessage.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // DraftMessage Contains information about a message draft 8 | type DraftMessage struct { 9 | tdCommon 10 | ReplyToMessageId int64 `json:"reply_to_message_id"` // Identifier of the message to reply to; 0 if none 11 | Date int32 `json:"date"` // Point in time (Unix timestamp) when the draft was created 12 | InputMessageText InputMessageContent `json:"input_message_text"` // Content of the message draft; must be of the type inputMessageText 13 | } 14 | 15 | // MessageType return the string telegram-type of DraftMessage 16 | func (draftMessage *DraftMessage) MessageType() string { 17 | return "draftMessage" 18 | } 19 | 20 | // NewDraftMessage creates a new DraftMessage 21 | // 22 | // @param replyToMessageId Identifier of the message to reply to; 0 if none 23 | // @param date Point in time (Unix timestamp) when the draft was created 24 | // @param inputMessageText Content of the message draft; must be of the type inputMessageText 25 | func NewDraftMessage(replyToMessageId int64, date int32, inputMessageText InputMessageContent) *DraftMessage { 26 | draftMessageTemp := DraftMessage{ 27 | tdCommon: tdCommon{Type: "draftMessage"}, 28 | ReplyToMessageId: replyToMessageId, 29 | Date: date, 30 | InputMessageText: inputMessageText, 31 | } 32 | 33 | return &draftMessageTemp 34 | } 35 | 36 | // UnmarshalJSON unmarshal to json 37 | func (draftMessage *DraftMessage) UnmarshalJSON(b []byte) error { 38 | var objMap map[string]*json.RawMessage 39 | err := json.Unmarshal(b, &objMap) 40 | if err != nil { 41 | return err 42 | } 43 | tempObj := struct { 44 | tdCommon 45 | ReplyToMessageId int64 `json:"reply_to_message_id"` // Identifier of the message to reply to; 0 if none 46 | Date int32 `json:"date"` // Point in time (Unix timestamp) when the draft was created 47 | 48 | }{} 49 | err = json.Unmarshal(b, &tempObj) 50 | if err != nil { 51 | return err 52 | } 53 | 54 | draftMessage.tdCommon = tempObj.tdCommon 55 | draftMessage.ReplyToMessageId = tempObj.ReplyToMessageId 56 | draftMessage.Date = tempObj.Date 57 | 58 | fieldInputMessageText, _ := unmarshalInputMessageContent(objMap["input_message_text"]) 59 | draftMessage.InputMessageText = fieldInputMessageText 60 | 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /passportElementsWithErrors.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // PassportElementsWithErrors Contains information about a Telegram Passport elements and corresponding errors 9 | type PassportElementsWithErrors struct { 10 | tdCommon 11 | Elements []PassportElement `json:"elements"` // Telegram Passport elements 12 | Errors []PassportElementError `json:"errors"` // Errors in the elements that are already available 13 | } 14 | 15 | // MessageType return the string telegram-type of PassportElementsWithErrors 16 | func (passportElementsWithErrors *PassportElementsWithErrors) MessageType() string { 17 | return "passportElementsWithErrors" 18 | } 19 | 20 | // NewPassportElementsWithErrors creates a new PassportElementsWithErrors 21 | // 22 | // @param elements Telegram Passport elements 23 | // @param errors Errors in the elements that are already available 24 | func NewPassportElementsWithErrors(elements []PassportElement, errors []PassportElementError) *PassportElementsWithErrors { 25 | passportElementsWithErrorsTemp := PassportElementsWithErrors{ 26 | tdCommon: tdCommon{Type: "passportElementsWithErrors"}, 27 | Elements: elements, 28 | Errors: errors, 29 | } 30 | 31 | return &passportElementsWithErrorsTemp 32 | } 33 | 34 | // 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 35 | // @param autorizationFormId Authorization form identifier 36 | // @param password Password of the current user 37 | func (client *Client) GetPassportAuthorizationFormAvailableElements(autorizationFormId int32, password string) (*PassportElementsWithErrors, error) { 38 | result, err := client.SendAndCatch(UpdateData{ 39 | "@type": "getPassportAuthorizationFormAvailableElements", 40 | "autorization_form_id": autorizationFormId, 41 | "password": password, 42 | }) 43 | 44 | if err != nil { 45 | return nil, err 46 | } 47 | 48 | if result.Data["@type"].(string) == "error" { 49 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 50 | } 51 | 52 | var passportElementsWithErrors PassportElementsWithErrors 53 | err = json.Unmarshal(result.Raw, &passportElementsWithErrors) 54 | return &passportElementsWithErrors, err 55 | } 56 | -------------------------------------------------------------------------------- /validatedOrderInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // ValidatedOrderInfo Contains a temporary identifier of validated order information, which is stored for one hour. Also contains the available shipping options 9 | type ValidatedOrderInfo struct { 10 | tdCommon 11 | OrderInfoId string `json:"order_info_id"` // Temporary identifier of the order information 12 | ShippingOptions []ShippingOption `json:"shipping_options"` // Available shipping options 13 | } 14 | 15 | // MessageType return the string telegram-type of ValidatedOrderInfo 16 | func (validatedOrderInfo *ValidatedOrderInfo) MessageType() string { 17 | return "validatedOrderInfo" 18 | } 19 | 20 | // NewValidatedOrderInfo creates a new ValidatedOrderInfo 21 | // 22 | // @param orderInfoId Temporary identifier of the order information 23 | // @param shippingOptions Available shipping options 24 | func NewValidatedOrderInfo(orderInfoId string, shippingOptions []ShippingOption) *ValidatedOrderInfo { 25 | validatedOrderInfoTemp := ValidatedOrderInfo{ 26 | tdCommon: tdCommon{Type: "validatedOrderInfo"}, 27 | OrderInfoId: orderInfoId, 28 | ShippingOptions: shippingOptions, 29 | } 30 | 31 | return &validatedOrderInfoTemp 32 | } 33 | 34 | // ValidateOrderInfo Validates the order information provided by a user and returns the available shipping options for a flexible invoice 35 | // @param chatId Chat identifier of the Invoice message 36 | // @param messageId Message identifier 37 | // @param orderInfo The order information, provided by the user; pass null if empty 38 | // @param allowSave True, if the order information can be saved 39 | func (client *Client) ValidateOrderInfo(chatId int64, messageId int64, orderInfo *OrderInfo, allowSave bool) (*ValidatedOrderInfo, error) { 40 | result, err := client.SendAndCatch(UpdateData{ 41 | "@type": "validateOrderInfo", 42 | "chat_id": chatId, 43 | "message_id": messageId, 44 | "order_info": orderInfo, 45 | "allow_save": allowSave, 46 | }) 47 | 48 | if err != nil { 49 | return nil, err 50 | } 51 | 52 | if result.Data["@type"].(string) == "error" { 53 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 54 | } 55 | 56 | var validatedOrderInfo ValidatedOrderInfo 57 | err = json.Unmarshal(result.Raw, &validatedOrderInfo) 58 | return &validatedOrderInfo, err 59 | } 60 | -------------------------------------------------------------------------------- /autoDownloadSettingsPresets.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // AutoDownloadSettingsPresets Contains auto-download settings presets for the current user 9 | type AutoDownloadSettingsPresets struct { 10 | tdCommon 11 | Low *AutoDownloadSettings `json:"low"` // Preset with lowest settings; supposed to be used by default when roaming 12 | Medium *AutoDownloadSettings `json:"medium"` // Preset with medium settings; supposed to be used by default when using mobile data 13 | High *AutoDownloadSettings `json:"high"` // Preset with highest settings; supposed to be used by default when connected on Wi-Fi 14 | } 15 | 16 | // MessageType return the string telegram-type of AutoDownloadSettingsPresets 17 | func (autoDownloadSettingsPresets *AutoDownloadSettingsPresets) MessageType() string { 18 | return "autoDownloadSettingsPresets" 19 | } 20 | 21 | // NewAutoDownloadSettingsPresets creates a new AutoDownloadSettingsPresets 22 | // 23 | // @param low Preset with lowest settings; supposed to be used by default when roaming 24 | // @param medium Preset with medium settings; supposed to be used by default when using mobile data 25 | // @param high Preset with highest settings; supposed to be used by default when connected on Wi-Fi 26 | func NewAutoDownloadSettingsPresets(low *AutoDownloadSettings, medium *AutoDownloadSettings, high *AutoDownloadSettings) *AutoDownloadSettingsPresets { 27 | autoDownloadSettingsPresetsTemp := AutoDownloadSettingsPresets{ 28 | tdCommon: tdCommon{Type: "autoDownloadSettingsPresets"}, 29 | Low: low, 30 | Medium: medium, 31 | High: high, 32 | } 33 | 34 | return &autoDownloadSettingsPresetsTemp 35 | } 36 | 37 | // GetAutoDownloadSettingsPresets Returns auto-download settings presets for the current user 38 | func (client *Client) GetAutoDownloadSettingsPresets() (*AutoDownloadSettingsPresets, error) { 39 | result, err := client.SendAndCatch(UpdateData{ 40 | "@type": "getAutoDownloadSettingsPresets", 41 | }) 42 | 43 | if err != nil { 44 | return nil, err 45 | } 46 | 47 | if result.Data["@type"].(string) == "error" { 48 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 49 | } 50 | 51 | var autoDownloadSettingsPresets AutoDownloadSettingsPresets 52 | err = json.Unmarshal(result.Raw, &autoDownloadSettingsPresets) 53 | return &autoDownloadSettingsPresets, err 54 | } 55 | -------------------------------------------------------------------------------- /messageReplyInfo.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | // MessageReplyInfo Contains information about replies to a message 4 | type MessageReplyInfo struct { 5 | tdCommon 6 | ReplyCount int32 `json:"reply_count"` // Number of times the message was directly or indirectly replied 7 | RecentReplierIds []MessageSender `json:"recent_replier_ids"` // Identifiers of at most 3 recent repliers to the message; available in channels with a discussion supergroup. The users and chats are expected to be inaccessible: only their photo and name will be available 8 | LastReadInboxMessageId int64 `json:"last_read_inbox_message_id"` // Identifier of the last read incoming reply to the message 9 | LastReadOutboxMessageId int64 `json:"last_read_outbox_message_id"` // Identifier of the last read outgoing reply to the message 10 | LastMessageId int64 `json:"last_message_id"` // Identifier of the last reply to the message 11 | } 12 | 13 | // MessageType return the string telegram-type of MessageReplyInfo 14 | func (messageReplyInfo *MessageReplyInfo) MessageType() string { 15 | return "messageReplyInfo" 16 | } 17 | 18 | // NewMessageReplyInfo creates a new MessageReplyInfo 19 | // 20 | // @param replyCount Number of times the message was directly or indirectly replied 21 | // @param recentReplierIds Identifiers of at most 3 recent repliers to the message; available in channels with a discussion supergroup. The users and chats are expected to be inaccessible: only their photo and name will be available 22 | // @param lastReadInboxMessageId Identifier of the last read incoming reply to the message 23 | // @param lastReadOutboxMessageId Identifier of the last read outgoing reply to the message 24 | // @param lastMessageId Identifier of the last reply to the message 25 | func NewMessageReplyInfo(replyCount int32, recentReplierIds []MessageSender, lastReadInboxMessageId int64, lastReadOutboxMessageId int64, lastMessageId int64) *MessageReplyInfo { 26 | messageReplyInfoTemp := MessageReplyInfo{ 27 | tdCommon: tdCommon{Type: "messageReplyInfo"}, 28 | ReplyCount: replyCount, 29 | RecentReplierIds: recentReplierIds, 30 | LastReadInboxMessageId: lastReadInboxMessageId, 31 | LastReadOutboxMessageId: lastReadOutboxMessageId, 32 | LastMessageId: lastMessageId, 33 | } 34 | 35 | return &messageReplyInfoTemp 36 | } 37 | -------------------------------------------------------------------------------- /emojis.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // Emojis Represents a list of emoji 9 | type Emojis struct { 10 | tdCommon 11 | Emojis []string `json:"emojis"` // List of emojis 12 | } 13 | 14 | // MessageType return the string telegram-type of Emojis 15 | func (emojis *Emojis) MessageType() string { 16 | return "emojis" 17 | } 18 | 19 | // NewEmojis creates a new Emojis 20 | // 21 | // @param emojis List of emojis 22 | func NewEmojis(emojis []string) *Emojis { 23 | emojisTemp := Emojis{ 24 | tdCommon: tdCommon{Type: "emojis"}, 25 | Emojis: emojis, 26 | } 27 | 28 | return &emojisTemp 29 | } 30 | 31 | // 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 32 | // @param sticker Sticker file identifier 33 | func (client *Client) GetStickerEmojis(sticker InputFile) (*Emojis, error) { 34 | result, err := client.SendAndCatch(UpdateData{ 35 | "@type": "getStickerEmojis", 36 | "sticker": sticker, 37 | }) 38 | 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | if result.Data["@type"].(string) == "error" { 44 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 45 | } 46 | 47 | var emojis Emojis 48 | err = json.Unmarshal(result.Raw, &emojis) 49 | return &emojis, err 50 | } 51 | 52 | // SearchEmojis Searches for emojis by keywords. Supported only if the file database is enabled 53 | // @param text Text to search for 54 | // @param exactMatch True, if only emojis, which exactly match text needs to be returned 55 | // @param inputLanguageCodes List of possible IETF language tags of the user's input language; may be empty if unknown 56 | func (client *Client) SearchEmojis(text string, exactMatch bool, inputLanguageCodes []string) (*Emojis, error) { 57 | result, err := client.SendAndCatch(UpdateData{ 58 | "@type": "searchEmojis", 59 | "text": text, 60 | "exact_match": exactMatch, 61 | "input_language_codes": inputLanguageCodes, 62 | }) 63 | 64 | if err != nil { 65 | return nil, err 66 | } 67 | 68 | if result.Data["@type"].(string) == "error" { 69 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 70 | } 71 | 72 | var emojis Emojis 73 | err = json.Unmarshal(result.Raw, &emojis) 74 | return &emojis, err 75 | } 76 | -------------------------------------------------------------------------------- /messageLink.go: -------------------------------------------------------------------------------- 1 | package tdlib 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // MessageLink Contains an HTTPS link to a message in a supergroup or channel 9 | type MessageLink struct { 10 | tdCommon 11 | Link string `json:"link"` // Message link 12 | IsPublic bool `json:"is_public"` // True, if the link will work for non-members of the chat 13 | } 14 | 15 | // MessageType return the string telegram-type of MessageLink 16 | func (messageLink *MessageLink) MessageType() string { 17 | return "messageLink" 18 | } 19 | 20 | // NewMessageLink creates a new MessageLink 21 | // 22 | // @param link Message link 23 | // @param isPublic True, if the link will work for non-members of the chat 24 | func NewMessageLink(link string, isPublic bool) *MessageLink { 25 | messageLinkTemp := MessageLink{ 26 | tdCommon: tdCommon{Type: "messageLink"}, 27 | Link: link, 28 | IsPublic: isPublic, 29 | } 30 | 31 | return &messageLinkTemp 32 | } 33 | 34 | // 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 35 | // @param chatId Identifier of the chat to which the message belongs 36 | // @param messageId Identifier of the message 37 | // @param mediaTimestamp If not 0, timestamp from which the video/audio/video note/voice note playing must start, in seconds. The media can be in the message content or in its web page preview 38 | // @param forAlbum Pass true to create a link for the whole media album 39 | // @param forComment Pass true to create a link to the message as a channel post comment, or from a message thread 40 | func (client *Client) GetMessageLink(chatId int64, messageId int64, mediaTimestamp int32, forAlbum bool, forComment bool) (*MessageLink, error) { 41 | result, err := client.SendAndCatch(UpdateData{ 42 | "@type": "getMessageLink", 43 | "chat_id": chatId, 44 | "message_id": messageId, 45 | "media_timestamp": mediaTimestamp, 46 | "for_album": forAlbum, 47 | "for_comment": forComment, 48 | }) 49 | 50 | if err != nil { 51 | return nil, err 52 | } 53 | 54 | if result.Data["@type"].(string) == "error" { 55 | return nil, fmt.Errorf("error! code: %v msg: %s", result.Data["code"], result.Data["message"]) 56 | } 57 | 58 | var messageLink MessageLink 59 | err = json.Unmarshal(result.Raw, &messageLink) 60 | return &messageLink, err 61 | } 62 | --------------------------------------------------------------------------------