diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 48b2859b..407f7940 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,14 +12,14 @@ jobs: name: Test runs-on: ubuntu-latest steps: - - name: Set up Go 1.x - uses: actions/setup-go@v2 + - name: Set up Go 1.23 + uses: actions/setup-go@v5 with: - go-version: ^1.15 + go-version: "1.23" id: go - name: Check out code into the Go module directory - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Build run: go build -v . diff --git a/.gitignore b/.gitignore index eb7a23b2..d3083e5f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ coverage.out tmp/ book/ +.vscode/ diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 00000000..eda9b16e --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +* @iamwavecut @zhuk-kk diff --git a/README.md b/README.md index b18d15dd..69d8ea8a 100644 --- a/README.md +++ b/README.md @@ -1,121 +1,117 @@ -# Golang bindings for the Telegram Bot API +# Golang Bindings for the Telegram Bot API +[![Go Reference](https://pkg.go.dev/badge/github.com/OvyFlash/telegram-bot-api.svg)](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api) +[![Test](https://github.com/OvyFlash/telegram-bot-api/actions/workflows/test.yml/badge.svg)](https://github.com/OvyFlash/telegram-bot-api/actions/workflows/test.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-telegram-bot-api/telegram-bot-api/v5.svg)](https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5) -[![Test](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml/badge.svg)](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml) +# Headline -All methods are fairly self-explanatory, and reading the [godoc](https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5) page should -explain everything. If something isn't clear, open an issue or submit -a pull request. +This is a maintained fork of go-telegram-bot-api that preserves the original design while staying current with the latest Telegram Bot API specifications. It continues the development of the original [github.com/go-telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api) package. -There are more tutorials and high-level information on the website, [go-telegram-bot-api.dev](https://go-telegram-bot-api.dev). +## Features -The scope of this project is just to provide a wrapper around the API -without any additional features. There are other projects for creating -something with plugins and command handlers without having to design -all that yourself. +- Complete coverage of the Telegram Bot API +- Simple and intuitive interface +- Minimal dependencies +- Production-ready and actively maintained +- Preserves original API structure for easy migration -Join [the development group](https://telegram.me/go_telegram_bot_api) if -you want to ask questions or discuss development. +## Installation -## Example - -First, ensure the library is installed and up to date by running -`go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5`. - -This is a very simple bot that just displays any gotten updates, -then replies it to that chat. - -```go -package main - -import ( - "log" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := tgbotapi.NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) +Install the latest version: +```bash +go get -u github.com/OvyFlash/telegram-bot-api +``` - for update := range updates { - if update.Message != nil { // If we got a message - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyToMessageID = update.Message.MessageID +> ❗ Tag versioning is discouraged due to the unstable nature of the Telegram Bot API, and it might break at any time after the API changes. +> ~~`go get -u github.com/OvyFlash/telegram-bot-api/v7`~~ - bot.Send(msg) - } - } -} -``` +## Quick Start -If you need to use webhooks (if you wish to run on Google App Engine), -you may use a slightly different method. +Here's a simple echo bot using polling: ```go package main import ( - "log" - "net/http" - - "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "log" + "time" + api "github.com/OvyFlash/telegram-bot-api" ) func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Fatal(err) - } + bot, err := api.NewBotAPI("BOT_TOKEN") + if err != nil { + panic(err) + } - bot.Debug = true + log.Printf("Authorized on account %s", bot.Self.UserName) - log.Printf("Authorized on account %s", bot.Self.UserName) + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + updatesChannel := bot.GetUpdatesChan(updateConfig) - wh, _ := tgbotapi.NewWebhookWithCert("https://www.example.com:8443/"+bot.Token, "cert.pem") + // Optional: Clear initial updates + time.Sleep(time.Millisecond * 500) + updatesChannel.Clear() - _, err = bot.Request(wh) - if err != nil { - log.Fatal(err) - } + for update := range updatesChannel { + if update.Message == nil { + continue + } - info, err := bot.GetWebhookInfo() - if err != nil { - log.Fatal(err) - } + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - if info.LastErrorDate != 0 { - log.Printf("Telegram callback failed: %s", info.LastErrorMessage) - } + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID - updates := bot.ListenForWebhook("/" + bot.Token) - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) - - for update := range updates { - log.Printf("%+v\n", update) - } + bot.Send(msg) + } } ``` -If you need, you may generate a self-signed certificate, as this requires -HTTPS / TLS. The above example tells Telegram that this is your -certificate and that it should be trusted, even though it is not -properly signed. +## Webhook Setup +For webhook implementation: +1. Check the [examples](./examples) folder for examples of webhook implementations +2. Use HTTPS (required by Telegram) + - Generate SSL certificate: + ```bash openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes - -Now that [Let's Encrypt](https://letsencrypt.org) is available, -you may wish to generate your free TLS certificate there. + ``` + - Bring your own SSL certificate. [Let's Encrypt](https://letsencrypt.org) is recommended for free TLS certificates in production. + +## Documentation + +- [GoDoc](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api) +- Check the [examples](./examples) directory for more use cases + + +## Contributing + +- Issues and feature requests are welcome +- Pull requests should maintain the existing design philosophy +- The focus is on providing a clean API wrapper without additional features + +## License + +>The [MIT License](./LICENSE.txt) +> +>Copyright (c) 2015 Syfaro +> +>Permission is hereby granted, free of charge, to any person obtaining a copy +>of this software and associated documentation files (the "Software"), to deal +>in the Software without restriction, including without limitation the rights +>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +>copies of the Software, and to permit persons to whom the Software is +>furnished to do so, subject to the following conditions: +> +>The above copyright notice and this permission notice shall be included in all +>copies or substantial portions of the Software. +> +>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +>SOFTWARE. diff --git a/bot.go b/bot.go index 39037b8d..25e5328d 100644 --- a/bot.go +++ b/bot.go @@ -3,6 +3,7 @@ package tgbotapi import ( + "context" "encoding/json" "errors" "fmt" @@ -11,6 +12,7 @@ import ( "net/http" "net/url" "strings" + "sync" "time" ) @@ -25,11 +27,13 @@ type BotAPI struct { Debug bool `json:"debug"` Buffer int `json:"buffer"` - Self User `json:"-"` - Client HTTPClient `json:"-"` - shutdownChannel chan interface{} + Self User `json:"-"` + Client HTTPClient `json:"-"` apiEndpoint string + + stoppers []context.CancelFunc + mu sync.RWMutex } // NewBotAPI creates a new BotAPI instance. @@ -53,10 +57,9 @@ func NewBotAPIWithAPIEndpoint(token, apiEndpoint string) (*BotAPI, error) { // It requires a token, provided by @BotFather on Telegram and API endpoint. func NewBotAPIWithClient(token, apiEndpoint string, client HTTPClient) (*BotAPI, error) { bot := &BotAPI{ - Token: token, - Client: client, - Buffer: 100, - shutdownChannel: make(chan interface{}), + Token: token, + Client: client, + Buffer: 100, apiEndpoint: apiEndpoint, } @@ -92,6 +95,10 @@ func buildParams(in Params) url.Values { // MakeRequest makes a request to a specific endpoint with our token. func (bot *BotAPI) MakeRequest(endpoint string, params Params) (*APIResponse, error) { + return bot.MakeRequestWithContext(context.Background(), endpoint, params) +} + +func (bot *BotAPI) MakeRequestWithContext(ctx context.Context, endpoint string, params Params) (*APIResponse, error) { if bot.Debug { log.Printf("Endpoint: %s, params: %v\n", endpoint, params) } @@ -100,7 +107,7 @@ func (bot *BotAPI) MakeRequest(endpoint string, params Params) (*APIResponse, er values := buildParams(params) - req, err := http.NewRequest("POST", method, strings.NewReader(values.Encode())) + req, err := http.NewRequestWithContext(ctx, "POST", method, strings.NewReader(values.Encode())) if err != nil { return &APIResponse{}, err } @@ -165,6 +172,10 @@ func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) // UploadFiles makes a request to the API with files. func (bot *BotAPI) UploadFiles(endpoint string, params Params, files []RequestFile) (*APIResponse, error) { + return bot.UploadFilesWithContext(context.Background(), endpoint, params, files) +} + +func (bot *BotAPI) UploadFilesWithContext(ctx context.Context, endpoint string, params Params, files []RequestFile) (*APIResponse, error) { r, w := io.Pipe() m := multipart.NewWriter(w) @@ -223,7 +234,7 @@ func (bot *BotAPI) UploadFiles(endpoint string, params Params, files []RequestFi method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint) - req, err := http.NewRequest("POST", method, r) + req, err := http.NewRequestWithContext(ctx, "POST", method, r) if err != nil { return nil, err } @@ -281,7 +292,11 @@ func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) { // and so you may get this data from BotAPI.Self without the need for // another request. func (bot *BotAPI) GetMe() (User, error) { - resp, err := bot.MakeRequest("getMe", nil) + return bot.GetMeWithContext(context.Background()) +} + +func (bot *BotAPI) GetMeWithContext(ctx context.Context) (User, error) { + resp, err := bot.MakeRequestWithContext(ctx, "getMe", nil) if err != nil { return User{}, err } @@ -311,6 +326,10 @@ func hasFilesNeedingUpload(files []RequestFile) bool { // Request sends a Chattable to Telegram, and returns the APIResponse. func (bot *BotAPI) Request(c Chattable) (*APIResponse, error) { + return bot.RequestWithContext(context.Background(), c) +} + +func (bot *BotAPI) RequestWithContext(ctx context.Context, c Chattable) (*APIResponse, error) { params, err := c.params() if err != nil { return nil, err @@ -332,7 +351,7 @@ func (bot *BotAPI) Request(c Chattable) (*APIResponse, error) { } } - return bot.MakeRequest(c.method(), params) + return bot.MakeRequestWithContext(ctx, c.method(), params) } // Send will send a Chattable item to Telegram and provides the @@ -401,7 +420,11 @@ func (bot *BotAPI) GetFile(config FileConfig) (File, error) { // Set Timeout to a large number to reduce requests, so you can get updates // instantly instead of having to wait between requests. func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { - resp, err := bot.Request(config) + return bot.GetUpdatesWithContext(context.Background(), config) +} + +func (bot *BotAPI) GetUpdatesWithContext(ctx context.Context, config UpdateConfig) ([]Update, error) { + resp, err := bot.RequestWithContext(ctx, config) if err != nil { return []Update{}, err } @@ -415,7 +438,11 @@ func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { // GetWebhookInfo allows you to fetch information about a webhook and if // one currently is set, along with pending update count and error messages. func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { - resp, err := bot.MakeRequest("getWebhookInfo", nil) + return bot.GetWebhookInfoWithContext(context.Background()) +} + +func (bot *BotAPI) GetWebhookInfoWithContext(ctx context.Context) (WebhookInfo, error) { + resp, err := bot.MakeRequestWithContext(ctx, "getWebhookInfo", nil) if err != nil { return WebhookInfo{}, err } @@ -430,21 +457,27 @@ func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) UpdatesChannel { ch := make(chan Update, bot.Buffer) + ctx, cancel := context.WithCancel(context.Background()) + bot.mu.Lock() + bot.stoppers = append(bot.stoppers, cancel) + bot.mu.Unlock() + go func() { for { select { - case <-bot.shutdownChannel: + case <-ctx.Done(): close(ch) return default: } - updates, err := bot.GetUpdates(config) + updates, err := bot.GetUpdatesWithContext(ctx, config) if err != nil { - log.Println(err) - log.Println("Failed to get updates, retrying in 3 seconds...") - time.Sleep(time.Second * 3) - + if ctx.Err() == nil { + log.Println(err) + log.Println("Failed to get updates, retrying in 3 seconds...") + time.Sleep(time.Second * 3) + } continue } @@ -462,10 +495,15 @@ func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) UpdatesChannel { // StopReceivingUpdates stops the go routine which receives updates func (bot *BotAPI) StopReceivingUpdates() { + bot.mu.Lock() + defer bot.mu.Unlock() + if bot.Debug { log.Println("Stopping the update receiver routine...") } - close(bot.shutdownChannel) + for _, stopper := range bot.stoppers { + stopper() + } } // ListenForWebhook registers a http handler for a webhook. @@ -553,13 +591,13 @@ func WriteToHTTPResponse(w http.ResponseWriter, c Chattable) error { } // GetChat gets information about a chat. -func (bot *BotAPI) GetChat(config ChatInfoConfig) (Chat, error) { +func (bot *BotAPI) GetChat(config ChatInfoConfig) (ChatFullInfo, error) { resp, err := bot.Request(config) if err != nil { - return Chat{}, err + return ChatFullInfo{}, err } - var chat Chat + var chat ChatFullInfo err = json.Unmarshal(resp.Result, &chat) return chat, err @@ -633,6 +671,23 @@ func (bot *BotAPI) GetInviteLink(config ChatInviteLinkConfig) (string, error) { return inviteLink, err } +// CreateInvoiceLink Use this method to create a link for an invoice. Returns the created invoice link as +// String on success. +func (bot *BotAPI) CreateInvoiceLink(config InvoiceLinkConfig) (inviteLink string, err error) { + var resp *APIResponse + + if resp, err = bot.Request(config); err != nil { + return + } + if !resp.Ok { + err = fmt.Errorf("returns error code: %d", resp.ErrorCode) + return + } + err = json.Unmarshal(resp.Result, &inviteLink) + + return +} + // GetStickerSet returns a StickerSet. func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) { resp, err := bot.Request(config) @@ -640,7 +695,20 @@ func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) return StickerSet{}, err } - var stickers StickerSet + var stickerSet StickerSet + err = json.Unmarshal(resp.Result, &stickerSet) + + return stickerSet, err +} + +// GetCustomEmojiStickers returns a slice of Sticker objects. +func (bot *BotAPI) GetCustomEmojiStickers(config GetCustomEmojiStickersConfig) ([]Sticker, error) { + resp, err := bot.Request(config) + if err != nil { + return []Sticker{}, err + } + + var stickers []Sticker err = json.Unmarshal(resp.Result, &stickers) return stickers, err diff --git a/bot_test.go b/bot_test.go index 7abd790a..0e98e38a 100644 --- a/bot_test.go +++ b/bot_test.go @@ -1,14 +1,12 @@ package tgbotapi import ( - "net/http" "os" "testing" "time" ) const ( - TestToken = "153667468:AAHlSHlMqSt1f_uFmVRJbm5gntu2HI4WW8I" ChatID = 76918703 Channel = "@tgbotapitest" SupergroupChatID = -1001120141283 @@ -35,7 +33,7 @@ func (t testLogger) Printf(format string, v ...interface{}) { } func getBot(t *testing.T) (*BotAPI, error) { - bot, err := NewBotAPI(TestToken) + bot, err := NewBotAPI(os.Getenv("TEST_TOKEN")) bot.Debug = true logger := testLogger{t} @@ -84,7 +82,7 @@ func TestSendWithMessageReply(t *testing.T) { bot, _ := getBot(t) msg := NewMessage(ChatID, "A test message from the test library in telegram-bot-api") - msg.ReplyToMessageID = ReplyToMessageID + msg.ReplyParameters.MessageID = ReplyToMessageID _, err := bot.Send(msg) if err != nil { @@ -169,7 +167,7 @@ func TestSendWithNewPhotoReply(t *testing.T) { bot, _ := getBot(t) msg := NewPhoto(ChatID, FilePath("tests/image.jpg")) - msg.ReplyToMessageID = ReplyToMessageID + msg.ReplyParameters.MessageID = ReplyToMessageID _, err := bot.Send(msg) @@ -671,154 +669,6 @@ func TestSendWithMediaGroupAudio(t *testing.T) { } } -func ExampleNewBotAPI() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - // Optional: wait for updates and clear them if you don't want to handle - // a large backlog of old messages - time.Sleep(time.Millisecond * 500) - updates.Clear() - - for update := range updates { - if update.Message == nil { - continue - } - - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - - msg := NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyToMessageID = update.Message.MessageID - - bot.Send(msg) - } -} - -func ExampleNewWebhook() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, FilePath("cert.pem")) - - if err != nil { - panic(err) - } - - _, err = bot.Request(wh) - - if err != nil { - panic(err) - } - - info, err := bot.GetWebhookInfo() - - if err != nil { - panic(err) - } - - if info.LastErrorDate != 0 { - log.Printf("failed to set webhook: %s", info.LastErrorMessage) - } - - updates := bot.ListenForWebhook("/" + bot.Token) - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) - - for update := range updates { - log.Printf("%+v\n", update) - } -} - -func ExampleWebhookHandler() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, FilePath("cert.pem")) - - if err != nil { - panic(err) - } - - _, err = bot.Request(wh) - if err != nil { - panic(err) - } - info, err := bot.GetWebhookInfo() - if err != nil { - panic(err) - } - if info.LastErrorDate != 0 { - log.Printf("[Telegram callback failed]%s", info.LastErrorMessage) - } - - http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) { - update, err := bot.HandleUpdate(r) - if err != nil { - log.Printf("%+v\n", err.Error()) - } else { - log.Printf("%+v\n", *update) - } - }) - - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) -} - -func ExampleInlineConfig() { - bot, err := NewBotAPI("MyAwesomeBotToken") // create new bot - if err != nil { - panic(err) - } - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - for update := range updates { - if update.InlineQuery == nil { // if no inline query, ignore it - continue - } - - article := NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query) - article.Description = update.InlineQuery.Query - - inlineConf := InlineConfig{ - InlineQueryID: update.InlineQuery.ID, - IsPersonal: true, - CacheTime: 0, - Results: []interface{}{article}, - } - - if _, err := bot.Request(inlineConf); err != nil { - log.Println(err) - } - } -} - func TestDeleteMessage(t *testing.T) { bot, _ := getBot(t) @@ -827,8 +677,12 @@ func TestDeleteMessage(t *testing.T) { message, _ := bot.Send(msg) deleteMessageConfig := DeleteMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, } _, err := bot.Request(deleteMessageConfig) @@ -845,8 +699,12 @@ func TestPinChatMessage(t *testing.T) { message, _ := bot.Send(msg) pinChatMessageConfig := PinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: ChatID, + }, + MessageID: message.MessageID, + }, DisableNotification: false, } _, err := bot.Request(pinChatMessageConfig) @@ -865,8 +723,12 @@ func TestUnpinChatMessage(t *testing.T) { // We need pin message to unpin something pinChatMessageConfig := PinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, DisableNotification: false, } @@ -875,8 +737,12 @@ func TestUnpinChatMessage(t *testing.T) { } unpinChatMessageConfig := UnpinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, } if _, err := bot.Request(unpinChatMessageConfig); err != nil { @@ -892,8 +758,12 @@ func TestUnpinAllChatMessages(t *testing.T) { message, _ := bot.Send(msg) pinChatMessageConfig := PinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, DisableNotification: true, } @@ -902,7 +772,7 @@ func TestUnpinAllChatMessages(t *testing.T) { } unpinAllChatMessagesConfig := UnpinAllChatMessagesConfig{ - ChatID: message.Chat.ID, + ChatConfig: ChatConfig{ChatID: message.Chat.ID}, } if _, err := bot.Request(unpinAllChatMessagesConfig); err != nil { @@ -913,7 +783,7 @@ func TestUnpinAllChatMessages(t *testing.T) { func TestPolls(t *testing.T) { bot, _ := getBot(t) - poll := NewPoll(SupergroupChatID, "Are polls working?", "Yes", "No") + poll := NewPoll(SupergroupChatID, "Are polls working?", NewPollOption("Yes"), NewPollOption("No")) msg, err := bot.Send(poll) if err != nil { @@ -1001,33 +871,6 @@ func TestCommands(t *testing.T) { } } -// TODO: figure out why test is failing -// -// func TestEditMessageMedia(t *testing.T) { -// bot, _ := getBot(t) - -// msg := NewPhoto(ChatID, "tests/image.jpg") -// msg.Caption = "Test" -// m, err := bot.Send(msg) - -// if err != nil { -// t.Error(err) -// } - -// edit := EditMessageMediaConfig{ -// BaseEdit: BaseEdit{ -// ChatID: ChatID, -// MessageID: m.MessageID, -// }, -// Media: NewInputMediaVideo(FilePath("tests/video.mp4")), -// } - -// _, err = bot.Request(edit) -// if err != nil { -// t.Error(err) -// } -// } - func TestPrepareInputMediaForParams(t *testing.T) { media := []interface{}{ NewInputMediaPhoto(FilePath("tests/image.jpg")), diff --git a/configs.go b/configs.go index 1831337b..8fd3dc7e 100644 --- a/configs.go +++ b/configs.go @@ -60,6 +60,25 @@ const ( // UpdateTypeEditedChannelPost is new version of a channel post that is known to the bot and was edited UpdateTypeEditedChannelPost = "edited_channel_post" + // UpdateTypeBusinessConnection is the bot was connected to or disconnected from a business account, + // or a user edited an existing connection with the bot + UpdateTypeBusinessConnection = "business_connection" + + // UpdateTypeBusinessMessage is a new non-service message from a connected business account + UpdateTypeBusinessMessage = "business_message" + + // UpdateTypeEditedBusinessMessage is a new version of a message from a connected business account + UpdateTypeEditedBusinessMessage = "edited_business_message" + + // UpdateTypeDeletedBusinessMessages are the messages were deleted from a connected business account + UpdateTypeDeletedBusinessMessages = "deleted_business_messages" + + // UpdateTypeMessageReactionis is a reaction to a message was changed by a user + UpdateTypeMessageReaction = "message_reaction" + + // UpdateTypeMessageReactionCount are reactions to a message with anonymous reactions were changed + UpdateTypeMessageReactionCount = "message_reaction_count" + // UpdateTypeInlineQuery is new incoming inline query UpdateTypeInlineQuery = "inline_query" @@ -77,6 +96,10 @@ const ( // UpdateTypePreCheckoutQuery is new incoming pre-checkout query. Contains full information about checkout UpdateTypePreCheckoutQuery = "pre_checkout_query" + // UpdateTypePurchasedPaidMedia is a user purchased paid media with a non-empty payload + // sent by the bot in a non-channel chat + UpdateTypePurchasedPaidMedia = "purchased_paid_media" + // UpdateTypePoll is new poll state. Bots receive only updates about stopped polls and polls // which are sent by the bot UpdateTypePoll = "poll" @@ -92,6 +115,18 @@ const ( // UpdateTypeChatMember is when the bot must be an administrator in the chat and must explicitly specify // this update in the list of allowed_updates to receive these updates. UpdateTypeChatMember = "chat_member" + + // UpdateTypeChatJoinRequest is request to join the chat has been sent. + // The bot must have the can_invite_users administrator right in the chat to receive these updates. + UpdateTypeChatJoinRequest = "chat_join_request" + + // UpdateTypeChatBoost is chat boost was added or changed. + // The bot must be an administrator in the chat to receive these updates. + UpdateTypeChatBoost = "chat_boost" + + // UpdateTypeRemovedChatBoost is boost was removed from a chat. + // The bot must be an administrator in the chat to receive these updates. + UpdateTypeRemovedChatBoost = "removed_chat_boost" ) // Library errors @@ -262,72 +297,13 @@ func (CloseConfig) params() (Params, error) { return nil, nil } -// BaseChat is base type for all chat config types. -type BaseChat struct { - ChatID int64 // required - ChannelUsername string - ProtectContent bool - ReplyToMessageID int - ReplyMarkup interface{} - DisableNotification bool - AllowSendingWithoutReply bool -} - -func (chat *BaseChat) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", chat.ChatID, chat.ChannelUsername) - params.AddNonZero("reply_to_message_id", chat.ReplyToMessageID) - params.AddBool("disable_notification", chat.DisableNotification) - params.AddBool("allow_sending_without_reply", chat.AllowSendingWithoutReply) - params.AddBool("protect_content", chat.ProtectContent) - - err := params.AddInterface("reply_markup", chat.ReplyMarkup) - - return params, err -} - -// BaseFile is a base type for all file config types. -type BaseFile struct { - BaseChat - File RequestFileData -} - -func (file BaseFile) params() (Params, error) { - return file.BaseChat.params() -} - -// BaseEdit is base type of all chat edits. -type BaseEdit struct { - ChatID int64 - ChannelUsername string - MessageID int - InlineMessageID string - ReplyMarkup *InlineKeyboardMarkup -} - -func (edit BaseEdit) params() (Params, error) { - params := make(Params) - - if edit.InlineMessageID != "" { - params["inline_message_id"] = edit.InlineMessageID - } else { - params.AddFirstValid("chat_id", edit.ChatID, edit.ChannelUsername) - params.AddNonZero("message_id", edit.MessageID) - } - - err := params.AddInterface("reply_markup", edit.ReplyMarkup) - - return params, err -} - // MessageConfig contains information about a SendMessage request. type MessageConfig struct { BaseChat - Text string - ParseMode string - Entities []MessageEntity - DisableWebPagePreview bool + Text string + ParseMode string + Entities []MessageEntity + LinkPreviewOptions LinkPreviewOptions } func (config MessageConfig) params() (Params, error) { @@ -337,9 +313,12 @@ func (config MessageConfig) params() (Params, error) { } params.AddNonEmpty("text", config.Text) - params.AddBool("disable_web_page_preview", config.DisableWebPagePreview) params.AddNonEmpty("parse_mode", config.ParseMode) err = params.AddInterface("entities", config.Entities) + if err != nil { + return params, err + } + err = params.AddInterface("link_preview_options", config.LinkPreviewOptions) return params, err } @@ -351,9 +330,8 @@ func (config MessageConfig) method() string { // ForwardConfig contains information about a ForwardMessage request. type ForwardConfig struct { BaseChat - FromChatID int64 // required - FromChannelUsername string - MessageID int // required + FromChat ChatConfig + MessageID int // required } func (config ForwardConfig) params() (Params, error) { @@ -361,8 +339,11 @@ func (config ForwardConfig) params() (Params, error) { if err != nil { return params, err } - - params.AddNonZero64("from_chat_id", config.FromChatID) + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) params.AddNonZero("message_id", config.MessageID) return params, nil @@ -372,15 +353,43 @@ func (config ForwardConfig) method() string { return "forwardMessage" } +// ForwardMessagesConfig contains information about a ForwardMessages request. +type ForwardMessagesConfig struct { + BaseChat + FromChat ChatConfig + MessageIDs []int // required +} + +func (config ForwardMessagesConfig) params() (Params, error) { + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) + err = params.AddInterface("message_ids", config.MessageIDs) + + return params, err +} + +func (config ForwardMessagesConfig) method() string { + return "forwardMessages" +} + // CopyMessageConfig contains information about a copyMessage request. +// Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. type CopyMessageConfig struct { BaseChat - FromChatID int64 - FromChannelUsername string - MessageID int - Caption string - ParseMode string - CaptionEntities []MessageEntity + FromChat ChatConfig + MessageID int + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config CopyMessageConfig) params() (Params, error) { @@ -389,10 +398,15 @@ func (config CopyMessageConfig) params() (Params, error) { return params, err } - params.AddFirstValid("from_chat_id", config.FromChatID, config.FromChannelUsername) + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) params.AddNonZero("message_id", config.MessageID) params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) return params, err @@ -402,13 +416,45 @@ func (config CopyMessageConfig) method() string { return "copyMessage" } +// CopyMessagesConfig contains information about a copyMessages request. +// Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. +type CopyMessagesConfig struct { + BaseChat + FromChat ChatConfig + MessageIDs []int + RemoveCaption bool +} + +func (config CopyMessagesConfig) params() (Params, error) { + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) + params.AddBool("remove_caption", config.RemoveCaption) + err = params.AddInterface("message_ids", config.MessageIDs) + + return params, err +} + +func (config CopyMessagesConfig) method() string { + return "copyMessages" +} + // PhotoConfig contains information about a SendPhoto request. type PhotoConfig struct { BaseFile - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity + BaseSpoiler + Thumb RequestFileData + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config PhotoConfig) params() (Params, error) { @@ -419,7 +465,17 @@ func (config PhotoConfig) params() (Params, error) { params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } + + p1, err := config.BaseSpoiler.params() + if err != nil { + return params, err + } + params.Merge(p1) return params, err } @@ -436,7 +492,7 @@ func (config PhotoConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -484,7 +540,7 @@ func (config AudioConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -504,10 +560,17 @@ type DocumentConfig struct { func (config DocumentConfig) params() (Params, error) { params, err := config.BaseFile.params() + if err != nil { + return params, err + } params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("disable_content_type_detection", config.DisableContentTypeDetection) + err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } return params, err } @@ -524,7 +587,7 @@ func (config DocumentConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -534,11 +597,18 @@ func (config DocumentConfig) files() []RequestFile { // StickerConfig contains information about a SendSticker request. type StickerConfig struct { + // Emoji associated with the sticker; only for just uploaded stickers + Emoji string BaseFile } func (config StickerConfig) params() (Params, error) { - return config.BaseChat.params() + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + params.AddNonEmpty("emoji", config.Emoji) + return params, err } func (config StickerConfig) method() string { @@ -555,12 +625,14 @@ func (config StickerConfig) files() []RequestFile { // VideoConfig contains information about a SendVideo request. type VideoConfig struct { BaseFile - Thumb RequestFileData - Duration int - Caption string - ParseMode string - CaptionEntities []MessageEntity - SupportsStreaming bool + BaseSpoiler + Thumb RequestFileData + Duration int + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool + SupportsStreaming bool } func (config VideoConfig) params() (Params, error) { @@ -573,7 +645,17 @@ func (config VideoConfig) params() (Params, error) { params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("supports_streaming", config.SupportsStreaming) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } + + p1, err := config.BaseSpoiler.params() + if err != nil { + return params, err + } + params.Merge(p1) return params, err } @@ -590,7 +672,7 @@ func (config VideoConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -601,11 +683,13 @@ func (config VideoConfig) files() []RequestFile { // AnimationConfig contains information about a SendAnimation request. type AnimationConfig struct { BaseFile - Duration int - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity + BaseSpoiler + Duration int + Thumb RequestFileData + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config AnimationConfig) params() (Params, error) { @@ -617,7 +701,17 @@ func (config AnimationConfig) params() (Params, error) { params.AddNonZero("duration", config.Duration) params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } + + p1, err := config.BaseSpoiler.params() + if err != nil { + return params, err + } + params.Merge(p1) return params, err } @@ -634,7 +728,7 @@ func (config AnimationConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -671,7 +765,7 @@ func (config VideoNoteConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -679,6 +773,60 @@ func (config VideoNoteConfig) files() []RequestFile { return files } +// Use this method to send paid media to channel chats. On success, the sent Message is returned. +type PaidMediaConfig struct { + BaseChat + StarCount int64 + Media []InputPaidMedia + Payload string // optional + Caption string // optional + ParseMode string // optional + CaptionEntities []MessageEntity // optional + ShowCaptionAboveMedia bool // optional +} + +func (config PaidMediaConfig) params() (Params, error) { + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + + params.AddNonZero64("star_count", config.StarCount) + params.AddNonEmpty("payload", config.Payload) + params.AddNonEmpty("caption", config.Caption) + params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) + + err = params.AddInterface("media", config.Media) + if err != nil { + return params, err + } + err = params.AddInterface("caption_entities", config.CaptionEntities) + return params, err +} + +func (config PaidMediaConfig) files() []RequestFile { + files := []RequestFile{} + for i, v := range config.Media { + files = append(files, RequestFile{ + Name: fmt.Sprintf("%s-%d", v.Type, i), + Data: v.Media, + }) + if v.Thumb != nil { + files = append(files, RequestFile{ + Name: fmt.Sprintf("thumbnail-%d", i), + Data: v.Thumb, + }) + } + } + + return files +} + +func (config PaidMediaConfig) method() string { + return "sendPaidMedia" +} + // VoiceConfig contains information about a SendVoice request. type VoiceConfig struct { BaseFile @@ -715,7 +863,7 @@ func (config VoiceConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -756,6 +904,7 @@ type EditMessageLiveLocationConfig struct { BaseEdit Latitude float64 // required Longitude float64 // required + LivePeriod int // optional HorizontalAccuracy float64 // optional Heading int // optional ProximityAlertRadius int // optional @@ -768,6 +917,7 @@ func (config EditMessageLiveLocationConfig) params() (Params, error) { params.AddNonZeroFloat("longitude", config.Longitude) params.AddNonZeroFloat("horizontal_accuracy", config.HorizontalAccuracy) params.AddNonZero("heading", config.Heading) + params.AddNonZero("live_period", config.LivePeriod) params.AddNonZero("proximity_alert_radius", config.ProximityAlertRadius) return params, err @@ -851,7 +1001,9 @@ func (config ContactConfig) method() string { type SendPollConfig struct { BaseChat Question string - Options []string + QuestionParseMode string // optional + QuestionEntities []MessageEntity // optional + Options []InputPollOption IsAnonymous bool Type string AllowsMultipleAnswers bool @@ -871,6 +1023,10 @@ func (config SendPollConfig) params() (Params, error) { } params["question"] = config.Question + params.AddNonEmpty("question_parse_mode", config.QuestionParseMode) + if err = params.AddInterface("question_entities", config.QuestionEntities); err != nil { + return params, err + } if err = params.AddInterface("options", config.Options); err != nil { return params, err } @@ -912,13 +1068,12 @@ func (config GameConfig) method() string { // SetGameScoreConfig allows you to update the game score in a chat. type SetGameScoreConfig struct { + BaseChatMessage + UserID int64 Score int Force bool DisableEditMessage bool - ChatID int64 - ChannelUsername string - MessageID int InlineMessageID string } @@ -932,8 +1087,11 @@ func (config SetGameScoreConfig) params() (Params, error) { if config.InlineMessageID != "" { params["inline_message_id"] = config.InlineMessageID } else { - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) + p1, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } + params.Merge(p1) } return params, nil @@ -945,10 +1103,9 @@ func (config SetGameScoreConfig) method() string { // GetGameHighScoresConfig allows you to fetch the high scores for a game. type GetGameHighScoresConfig struct { + BaseChatMessage + UserID int64 - ChatID int64 - ChannelUsername string - MessageID int InlineMessageID string } @@ -960,8 +1117,11 @@ func (config GetGameHighScoresConfig) params() (Params, error) { if config.InlineMessageID != "" { params["inline_message_id"] = config.InlineMessageID } else { - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) + p1, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } + params.Merge(p1) } return params, nil @@ -974,13 +1134,15 @@ func (config GetGameHighScoresConfig) method() string { // ChatActionConfig contains information about a SendChatAction request. type ChatActionConfig struct { BaseChat - Action string // required + MessageThreadID int + Action string // required } func (config ChatActionConfig) params() (Params, error) { params, err := config.BaseChat.params() params["action"] = config.Action + params.AddNonZero("message_thread_id", config.MessageThreadID) return params, err } @@ -992,10 +1154,10 @@ func (config ChatActionConfig) method() string { // EditMessageTextConfig allows you to modify the text in a message. type EditMessageTextConfig struct { BaseEdit - Text string - ParseMode string - Entities []MessageEntity - DisableWebPagePreview bool + Text string + ParseMode string + Entities []MessageEntity + LinkPreviewOptions LinkPreviewOptions } func (config EditMessageTextConfig) params() (Params, error) { @@ -1006,8 +1168,11 @@ func (config EditMessageTextConfig) params() (Params, error) { params["text"] = config.Text params.AddNonEmpty("parse_mode", config.ParseMode) - params.AddBool("disable_web_page_preview", config.DisableWebPagePreview) err = params.AddInterface("entities", config.Entities) + if err != nil { + return params, err + } + err = params.AddInterface("link_preview_options", config.LinkPreviewOptions) return params, err } @@ -1019,9 +1184,10 @@ func (config EditMessageTextConfig) method() string { // EditMessageCaptionConfig allows you to modify the caption of a message. type EditMessageCaptionConfig struct { BaseEdit - Caption string - ParseMode string - CaptionEntities []MessageEntity + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config EditMessageCaptionConfig) params() (Params, error) { @@ -1032,6 +1198,7 @@ func (config EditMessageCaptionConfig) params() (Params, error) { params["caption"] = config.Caption params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) return params, err @@ -1094,6 +1261,28 @@ func (StopPollConfig) method() string { return "stopPoll" } +// SetMessageReactionConfig changes reactions on a message. Returns true on success. +type SetMessageReactionConfig struct { + BaseChatMessage + Reaction []ReactionType + IsBig bool +} + +func (config SetMessageReactionConfig) params() (Params, error) { + params, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } + params.AddBool("is_big", config.IsBig) + err = params.AddInterface("reaction", config.Reaction) + + return params, err +} + +func (SetMessageReactionConfig) method() string { + return "setMessageReaction" +} + // UserProfilePhotosConfig contains information about a // GetUserProfilePhotos request. type UserProfilePhotosConfig struct { @@ -1164,6 +1353,7 @@ type WebhookConfig struct { MaxConnections int AllowedUpdates []string DropPendingUpdates bool + SecretToken string } func (config WebhookConfig) method() string { @@ -1181,6 +1371,7 @@ func (config WebhookConfig) params() (Params, error) { params.AddNonZero("max_connections", config.MaxConnections) err := params.AddInterface("allowed_updates", config.AllowedUpdates) params.AddBool("drop_pending_updates", config.DropPendingUpdates) + params.AddNonEmpty("secret_token", config.SecretToken) return params, err } @@ -1213,15 +1404,28 @@ func (config DeleteWebhookConfig) params() (Params, error) { return params, nil } +// InlineQueryResultsButton represents a button to be shown above inline query results. You must use exactly one of the optional fields. +type InlineQueryResultsButton struct { + // Label text on the button + Text string `json:"text"` + //Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method switchInlineQuery inside the Web App. + // + //Optional + WebApp *WebAppInfo `json:"web_app,omitempty"` + // Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. + // + //Optional + StartParam string `json:"start_parameter,omitempty"` +} + // InlineConfig contains information on making an InlineQuery response. type InlineConfig struct { - InlineQueryID string `json:"inline_query_id"` - Results []interface{} `json:"results"` - CacheTime int `json:"cache_time"` - IsPersonal bool `json:"is_personal"` - NextOffset string `json:"next_offset"` - SwitchPMText string `json:"switch_pm_text"` - SwitchPMParameter string `json:"switch_pm_parameter"` + InlineQueryID string `json:"inline_query_id"` + Results []interface{} `json:"results"` + CacheTime int `json:"cache_time"` + IsPersonal bool `json:"is_personal"` + NextOffset string `json:"next_offset"` + Button *InlineQueryResultsButton `json:"button,omitempty"` } func (config InlineConfig) method() string { @@ -1235,9 +1439,11 @@ func (config InlineConfig) params() (Params, error) { params.AddNonZero("cache_time", config.CacheTime) params.AddBool("is_personal", config.IsPersonal) params.AddNonEmpty("next_offset", config.NextOffset) - params.AddNonEmpty("switch_pm_text", config.SwitchPMText) - params.AddNonEmpty("switch_pm_parameter", config.SwitchPMParameter) - err := params.AddInterface("results", config.Results) + err := params.AddInterface("button", config.Button) + if err != nil { + return params, err + } + err = params.AddInterface("results", config.Results) return params, err } @@ -1293,10 +1499,17 @@ func (config CallbackConfig) params() (Params, error) { // ChatMemberConfig contains information about a user in a chat for use // with administrative functions such as kicking or unbanning a user. type ChatMemberConfig struct { - ChatID int64 - SuperGroupUsername string - ChannelUsername string - UserID int64 + ChatConfig + UserID int64 +} + +func (config ChatMemberConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + params.AddNonZero64("user_id", config.UserID) + return params, nil } // UnbanChatMemberConfig allows you to unban a user. @@ -1310,10 +1523,11 @@ func (config UnbanChatMemberConfig) method() string { } func (config UnbanChatMemberConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) params.AddBool("only_if_banned", config.OnlyIfBanned) return params, nil @@ -1331,10 +1545,11 @@ func (config BanChatMemberConfig) method() string { } func (config BanChatMemberConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero64("user_id", config.UserID) params.AddNonZero64("until_date", config.UntilDate) params.AddBool("revoke_messages", config.RevokeMessages) @@ -1349,8 +1564,9 @@ type KickChatMemberConfig = BanChatMemberConfig // RestrictChatMemberConfig contains fields to restrict members of chat type RestrictChatMemberConfig struct { ChatMemberConfig - UntilDate int64 - Permissions *ChatPermissions + UntilDate int64 + UseIndependentChatPermissions bool + Permissions *ChatPermissions } func (config RestrictChatMemberConfig) method() string { @@ -1358,13 +1574,14 @@ func (config RestrictChatMemberConfig) method() string { } func (config RestrictChatMemberConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } - err := params.AddInterface("permissions", config.Permissions) + params.AddBool("use_independent_chat_permissions", config.UseIndependentChatPermissions) params.AddNonZero64("until_date", config.UntilDate) + err = params.AddInterface("permissions", config.Permissions) return params, err } @@ -1383,6 +1600,10 @@ type PromoteChatMemberConfig struct { CanRestrictMembers bool CanPinMessages bool CanPromoteMembers bool + CanPostStories bool + CanEditStories bool + CanDeleteStories bool + CanManageTopics bool } func (config PromoteChatMemberConfig) method() string { @@ -1390,10 +1611,10 @@ func (config PromoteChatMemberConfig) method() string { } func (config PromoteChatMemberConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } params.AddBool("is_anonymous", config.IsAnonymous) params.AddBool("can_manage_chat", config.CanManageChat) @@ -1406,6 +1627,10 @@ func (config PromoteChatMemberConfig) params() (Params, error) { params.AddBool("can_restrict_members", config.CanRestrictMembers) params.AddBool("can_pin_messages", config.CanPinMessages) params.AddBool("can_promote_members", config.CanPromoteMembers) + params.AddBool("can_post_stories", config.CanPostStories) + params.AddBool("can_edit_stories", config.CanEditStories) + params.AddBool("can_delete_stories", config.CanDeleteStories) + params.AddBool("can_manage_topics", config.CanManageTopics) return params, nil } @@ -1422,10 +1647,10 @@ func (SetChatAdministratorCustomTitle) method() string { } func (config SetChatAdministratorCustomTitle) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } params.AddNonEmpty("custom_title", config.CustomTitle) return params, nil @@ -1437,10 +1662,9 @@ func (config SetChatAdministratorCustomTitle) params() (Params, error) { // administrator in the supergroup or channel for this to work and must have the // appropriate administrator rights. type BanChatSenderChatConfig struct { - ChatID int64 - ChannelUsername string - SenderChatID int64 - UntilDate int + ChatConfig + SenderChatID int64 + UntilDate int } func (config BanChatSenderChatConfig) method() string { @@ -1448,9 +1672,10 @@ func (config BanChatSenderChatConfig) method() string { } func (config BanChatSenderChatConfig) params() (Params, error) { - params := make(Params) - - _ = params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } params.AddNonZero64("sender_chat_id", config.SenderChatID) params.AddNonZero("until_date", config.UntilDate) @@ -1461,9 +1686,8 @@ func (config BanChatSenderChatConfig) params() (Params, error) { // supergroup or channel. The bot must be an administrator for this to work and // must have the appropriate administrator rights. type UnbanChatSenderChatConfig struct { - ChatID int64 - ChannelUsername string - SenderChatID int64 + ChatConfig + SenderChatID int64 } func (config UnbanChatSenderChatConfig) method() string { @@ -1471,28 +1695,15 @@ func (config UnbanChatSenderChatConfig) method() string { } func (config UnbanChatSenderChatConfig) params() (Params, error) { - params := make(Params) - - _ = params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } params.AddNonZero64("sender_chat_id", config.SenderChatID) return params, nil } -// ChatConfig contains information about getting information on a chat. -type ChatConfig struct { - ChatID int64 - SuperGroupUsername string -} - -func (config ChatConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil -} - // ChatInfoConfig contains information about getting chat information. type ChatInfoConfig struct { ChatConfig @@ -1525,7 +1736,8 @@ func (ChatAdministratorsConfig) method() string { // restrict members. type SetChatPermissionsConfig struct { ChatConfig - Permissions *ChatPermissions + UseIndependentChatPermissions bool + Permissions *ChatPermissions } func (SetChatPermissionsConfig) method() string { @@ -1533,10 +1745,13 @@ func (SetChatPermissionsConfig) method() string { } func (config SetChatPermissionsConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - err := params.AddInterface("permissions", config.Permissions) + params.AddBool("use_independent_chat_permissions", config.UseIndependentChatPermissions) + err = params.AddInterface("permissions", config.Permissions) return params, err } @@ -1553,12 +1768,8 @@ func (ChatInviteLinkConfig) method() string { } func (config ChatInviteLinkConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil -} + return config.ChatConfig.params() +} // CreateChatInviteLinkConfig allows you to create an additional invite link for // a chat. The bot must be an administrator in the chat for this to work and @@ -1577,10 +1788,12 @@ func (CreateChatInviteLinkConfig) method() string { } func (config CreateChatInviteLinkConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } params.AddNonEmpty("name", config.Name) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero("expire_date", config.ExpireDate) params.AddNonZero("member_limit", config.MemberLimit) params.AddBool("creates_join_request", config.CreatesJoinRequest) @@ -1605,9 +1818,11 @@ func (EditChatInviteLinkConfig) method() string { } func (config EditChatInviteLinkConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonEmpty("name", config.Name) params["invite_link"] = config.InviteLink params.AddNonZero("expire_date", config.ExpireDate) @@ -1617,6 +1832,60 @@ func (config EditChatInviteLinkConfig) params() (Params, error) { return params, nil } +// CreateChatSubscriptionLinkConfig creates a subscription invite link for a channel chat. +// The bot must have the can_invite_users administrator rights. +// The link can be edited using the method editChatSubscriptionInviteLink or +// revoked using the method revokeChatInviteLink. +// Returns the new invite link as a ChatInviteLink object. +type CreateChatSubscriptionLinkConfig struct { + ChatConfig + Name string + SubscriptionPeriod int + SubscriptionPrice int +} + +func (CreateChatSubscriptionLinkConfig) method() string { + return "createChatSubscriptionInviteLink" +} + +func (config CreateChatSubscriptionLinkConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params.AddNonEmpty("name", config.Name) + params.AddNonZero("subscription_period", config.SubscriptionPeriod) + params.AddNonZero("subscription_price", config.SubscriptionPrice) + + return params, nil +} + +// EditChatSubscriptionLinkConfig edits a subscription invite link created by the bot. +// The bot must have the can_invite_users administrator rights. +// Returns the edited invite link as a ChatInviteLink object. +type EditChatSubscriptionLinkConfig struct { + ChatConfig + InviteLink string + Name string +} + +func (EditChatSubscriptionLinkConfig) method() string { + return "editChatSubscriptionInviteLink" +} + +func (config EditChatSubscriptionLinkConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params["invite_link"] = config.InviteLink + params.AddNonEmpty("name", config.Name) + + return params, nil +} + // RevokeChatInviteLinkConfig allows you to revoke an invite link created by the // bot. If the primary link is revoked, a new link is automatically generated. // The bot must be an administrator in the chat for this to work and must have @@ -1631,9 +1900,11 @@ func (RevokeChatInviteLinkConfig) method() string { } func (config RevokeChatInviteLinkConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params["invite_link"] = config.InviteLink return params, nil @@ -1650,10 +1921,12 @@ func (ApproveChatJoinRequestConfig) method() string { } func (config ApproveChatJoinRequestConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("user_id", int(config.UserID)) + params.AddNonZero64("user_id", config.UserID) return params, nil } @@ -1669,18 +1942,18 @@ func (DeclineChatJoinRequest) method() string { } func (config DeclineChatJoinRequest) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("user_id", int(config.UserID)) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + params.AddNonZero64("user_id", config.UserID) return params, nil } // LeaveChatConfig allows you to leave a chat. type LeaveChatConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config LeaveChatConfig) method() string { @@ -1688,24 +1961,21 @@ func (config LeaveChatConfig) method() string { } func (config LeaveChatConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil + return config.ChatConfig.params() } // ChatConfigWithUser contains information about a chat and a user. type ChatConfigWithUser struct { - ChatID int64 - SuperGroupUsername string - UserID int64 + ChatConfig + UserID int64 } func (config ChatConfigWithUser) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero64("user_id", config.UserID) return params, nil @@ -1755,12 +2025,12 @@ func (config InvoiceConfig) params() (Params, error) { params["title"] = config.Title params["description"] = config.Description params["payload"] = config.Payload - params["provider_token"] = config.ProviderToken params["currency"] = config.Currency if err = params.AddInterface("prices", config.Prices); err != nil { return params, err } + params.AddNonEmpty("provider_token", config.ProviderToken) params.AddNonZero("max_tip_amount", config.MaxTipAmount) err = params.AddInterface("suggested_tip_amounts", config.SuggestedTipAmounts) params.AddNonEmpty("start_parameter", config.StartParameter) @@ -1784,6 +2054,64 @@ func (config InvoiceConfig) method() string { return "sendInvoice" } +// InvoiceLinkConfig contains information for createInvoiceLink method +type InvoiceLinkConfig struct { + Title string // Required + Description string // Required + Payload string // Required + ProviderToken string // Required + Currency string // Required + Prices []LabeledPrice // Required + MaxTipAmount int + SuggestedTipAmounts []int + ProviderData string + PhotoURL string + PhotoSize int + PhotoWidth int + PhotoHeight int + NeedName bool + NeedPhoneNumber bool + NeedEmail bool + NeedShippingAddress bool + SendPhoneNumberToProvider bool + SendEmailToProvider bool + IsFlexible bool +} + +func (config InvoiceLinkConfig) params() (Params, error) { + params := make(Params) + + params["title"] = config.Title + params["description"] = config.Description + params["payload"] = config.Payload + params["currency"] = config.Currency + if err := params.AddInterface("prices", config.Prices); err != nil { + return params, err + } + + params.AddNonEmpty("provider_token", config.ProviderToken) + params.AddNonZero("max_tip_amount", config.MaxTipAmount) + err := params.AddInterface("suggested_tip_amounts", config.SuggestedTipAmounts) + params.AddNonEmpty("provider_data", config.ProviderData) + params.AddNonEmpty("photo_url", config.PhotoURL) + params.AddNonZero("photo_size", config.PhotoSize) + params.AddNonZero("photo_width", config.PhotoWidth) + params.AddNonZero("photo_height", config.PhotoHeight) + params.AddBool("need_name", config.NeedName) + params.AddBool("need_phone_number", config.NeedPhoneNumber) + params.AddBool("need_email", config.NeedEmail) + params.AddBool("need_shipping_address", config.NeedShippingAddress) + params.AddBool("send_phone_number_to_provider", config.SendPhoneNumberToProvider) + params.AddBool("send_email_to_provider", config.SendEmailToProvider) + params.AddBool("is_flexible", config.IsFlexible) + + return params, err +} + +func (config InvoiceLinkConfig) method() string { + return "createInvoiceLink" +} + // ShippingConfig contains information for answerShippingQuery request. type ShippingConfig struct { ShippingQueryID string // required @@ -1828,11 +2156,50 @@ func (config PreCheckoutConfig) params() (Params, error) { return params, nil } +// Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object. +type GetStarTransactionsConfig struct { + // Number of transactions to skip in the response + Offset int64 + // The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100. + Limit int64 +} + +func (config GetStarTransactionsConfig) method() string { + return "getStarTransactions" +} + +func (config GetStarTransactionsConfig) params() (Params, error) { + params := make(Params) + + params.AddNonZero64("offset", config.Offset) + params.AddNonZero64("limit", config.Limit) + + return params, nil +} + +// RefundStarPaymentConfig refunds a successful payment in Telegram Stars. +// Returns True on success. +type RefundStarPaymentConfig struct { + UserID int64 // required + TelegramPaymentChargeID string // required +} + +func (config RefundStarPaymentConfig) method() string { + return "refundStarPayment" +} + +func (config RefundStarPaymentConfig) params() (Params, error) { + params := make(Params) + + params["telegram_payment_charge_id"] = config.TelegramPaymentChargeID + params.AddNonZero64("user_id", config.UserID) + + return params, nil +} + // DeleteMessageConfig contains information of a message in a chat to delete. type DeleteMessageConfig struct { - ChannelUsername string - ChatID int64 - MessageID int + BaseChatMessage } func (config DeleteMessageConfig) method() string { @@ -1840,19 +2207,25 @@ func (config DeleteMessageConfig) method() string { } func (config DeleteMessageConfig) params() (Params, error) { - params := make(Params) + return config.BaseChatMessage.params() +} - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) +// DeleteMessageConfig contains information of a messages in a chat to delete. +type DeleteMessagesConfig struct { + BaseChatMessages +} - return params, nil +func (config DeleteMessagesConfig) method() string { + return "deleteMessages" +} + +func (config DeleteMessagesConfig) params() (Params, error) { + return config.BaseChatMessages.params() } // PinChatMessageConfig contains information of a message in a chat to pin. type PinChatMessageConfig struct { - ChatID int64 - ChannelUsername string - MessageID int + BaseChatMessage DisableNotification bool } @@ -1861,10 +2234,11 @@ func (config PinChatMessageConfig) method() string { } func (config PinChatMessageConfig) params() (Params, error) { - params := make(Params) + params, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) params.AddBool("disable_notification", config.DisableNotification) return params, nil @@ -1874,9 +2248,7 @@ func (config PinChatMessageConfig) params() (Params, error) { // // If MessageID is not specified, it will unpin the most recent pin. type UnpinChatMessageConfig struct { - ChatID int64 - ChannelUsername string - MessageID int + BaseChatMessage } func (config UnpinChatMessageConfig) method() string { @@ -1884,19 +2256,13 @@ func (config UnpinChatMessageConfig) method() string { } func (config UnpinChatMessageConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) - - return params, nil + return config.BaseChatMessage.params() } // UnpinAllChatMessagesConfig contains information of all messages to unpin in // a chat. type UnpinAllChatMessagesConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config UnpinAllChatMessagesConfig) method() string { @@ -1904,11 +2270,7 @@ func (config UnpinAllChatMessagesConfig) method() string { } func (config UnpinAllChatMessagesConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil + return config.ChatConfig.params() } // SetChatPhotoConfig allows you to set a group, supergroup, or channel's photo. @@ -1929,8 +2291,7 @@ func (config SetChatPhotoConfig) files() []RequestFile { // DeleteChatPhotoConfig allows you to delete a group, supergroup, or channel's photo. type DeleteChatPhotoConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config DeleteChatPhotoConfig) method() string { @@ -1938,18 +2299,12 @@ func (config DeleteChatPhotoConfig) method() string { } func (config DeleteChatPhotoConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil + return config.ChatConfig.params() } // SetChatTitleConfig allows you to set the title of something other than a private chat. type SetChatTitleConfig struct { - ChatID int64 - ChannelUsername string - + ChatConfig Title string } @@ -1958,9 +2313,11 @@ func (config SetChatTitleConfig) method() string { } func (config SetChatTitleConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) params["title"] = config.Title return params, nil @@ -1968,9 +2325,7 @@ func (config SetChatTitleConfig) params() (Params, error) { // SetChatDescriptionConfig allows you to set the description of a supergroup or channel. type SetChatDescriptionConfig struct { - ChatID int64 - ChannelUsername string - + ChatConfig Description string } @@ -1979,9 +2334,11 @@ func (config SetChatDescriptionConfig) method() string { } func (config SetChatDescriptionConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) params["description"] = config.Description return params, nil @@ -2004,10 +2361,29 @@ func (config GetStickerSetConfig) params() (Params, error) { return params, nil } +// GetCustomEmojiStickersConfig get information about +// custom emoji stickers by their identifiers. +type GetCustomEmojiStickersConfig struct { + CustomEmojiIDs []string +} + +func (config GetCustomEmojiStickersConfig) params() (Params, error) { + params := make(Params) + + params.AddInterface("custom_emoji_ids", config.CustomEmojiIDs) + + return params, nil +} + +func (config GetCustomEmojiStickersConfig) method() string { + return "getCustomEmojiStickers" +} + // UploadStickerConfig allows you to upload a sticker for use in a set later. type UploadStickerConfig struct { - UserID int64 - PNGSticker RequestFileData + UserID int64 + Sticker RequestFile + StickerFormat string } func (config UploadStickerConfig) method() string { @@ -2018,29 +2394,23 @@ func (config UploadStickerConfig) params() (Params, error) { params := make(Params) params.AddNonZero64("user_id", config.UserID) + params["sticker_format"] = config.StickerFormat return params, nil } func (config UploadStickerConfig) files() []RequestFile { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} + return []RequestFile{config.Sticker} } // NewStickerSetConfig allows creating a new sticker set. -// -// You must set either PNGSticker or TGSSticker. type NewStickerSetConfig struct { - UserID int64 - Name string - Title string - PNGSticker RequestFileData - TGSSticker RequestFileData - Emojis string - ContainsMasks bool - MaskPosition *MaskPosition + UserID int64 + Name string + Title string + Stickers []InputSticker + StickerType string + NeedsRepainting bool // optional; Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only } func (config NewStickerSetConfig) method() string { @@ -2054,37 +2424,26 @@ func (config NewStickerSetConfig) params() (Params, error) { params["name"] = config.Name params["title"] = config.Title - params["emojis"] = config.Emojis - - params.AddBool("contains_masks", config.ContainsMasks) - - err := params.AddInterface("mask_position", config.MaskPosition) + params.AddBool("needs_repainting", config.NeedsRepainting) + params.AddNonEmpty("sticker_type", string(config.StickerType)) + err := params.AddInterface("stickers", config.Stickers) return params, err } func (config NewStickerSetConfig) files() []RequestFile { - if config.PNGSticker != nil { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} + requestFiles := []RequestFile{} + for _, v := range config.Stickers { + requestFiles = append(requestFiles, v.Sticker) } - - return []RequestFile{{ - Name: "tgs_sticker", - Data: config.TGSSticker, - }} + return requestFiles } // AddStickerConfig allows you to add a sticker to a set. type AddStickerConfig struct { - UserID int64 - Name string - PNGSticker RequestFileData - TGSSticker RequestFileData - Emojis string - MaskPosition *MaskPosition + UserID int64 + Name string + Sticker InputSticker } func (config AddStickerConfig) method() string { @@ -2096,26 +2455,12 @@ func (config AddStickerConfig) params() (Params, error) { params.AddNonZero64("user_id", config.UserID) params["name"] = config.Name - params["emojis"] = config.Emojis - - err := params.AddInterface("mask_position", config.MaskPosition) - + err := params.AddInterface("sticker", config.Sticker) return params, err } func (config AddStickerConfig) files() []RequestFile { - if config.PNGSticker != nil { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} - } - - return []RequestFile{{ - Name: "tgs_sticker", - Data: config.TGSSticker, - }} - + return []RequestFile{config.Sticker.Sticker} } // SetStickerPositionConfig allows you to change the position of a sticker in a set. @@ -2137,99 +2482,417 @@ func (config SetStickerPositionConfig) params() (Params, error) { return params, nil } -// DeleteStickerConfig allows you to delete a sticker from a set. -type DeleteStickerConfig struct { - Sticker string +// SetCustomEmojiStickerSetThumbnailConfig allows you to set the thumbnail of a custom emoji sticker set +type SetCustomEmojiStickerSetThumbnailConfig struct { + Name string + CustomEmojiID string } -func (config DeleteStickerConfig) method() string { - return "deleteStickerFromSet" +func (config SetCustomEmojiStickerSetThumbnailConfig) method() string { + return "setCustomEmojiStickerSetThumbnail" } -func (config DeleteStickerConfig) params() (Params, error) { +func (config SetCustomEmojiStickerSetThumbnailConfig) params() (Params, error) { params := make(Params) - params["sticker"] = config.Sticker + params["name"] = config.Name + params.AddNonEmpty("position", config.CustomEmojiID) return params, nil } -// SetStickerSetThumbConfig allows you to set the thumbnail for a sticker set. -type SetStickerSetThumbConfig struct { - Name string - UserID int64 - Thumb RequestFileData +// SetStickerSetTitle allows you to set the title of a created sticker set +type SetStickerSetTitleConfig struct { + Name string + Title string } -func (config SetStickerSetThumbConfig) method() string { - return "setStickerSetThumb" +func (config SetStickerSetTitleConfig) method() string { + return "setStickerSetTitle" } -func (config SetStickerSetThumbConfig) params() (Params, error) { +func (config SetStickerSetTitleConfig) params() (Params, error) { params := make(Params) params["name"] = config.Name - params.AddNonZero64("user_id", config.UserID) + params["title"] = config.Title return params, nil } -func (config SetStickerSetThumbConfig) files() []RequestFile { - return []RequestFile{{ - Name: "thumb", - Data: config.Thumb, - }} -} - -// SetChatStickerSetConfig allows you to set the sticker set for a supergroup. -type SetChatStickerSetConfig struct { - ChatID int64 - SuperGroupUsername string - - StickerSetName string +// DeleteStickerSetConfig allows you to delete a sticker set that was created by the bot. +type DeleteStickerSetConfig struct { + Name string } -func (config SetChatStickerSetConfig) method() string { - return "setChatStickerSet" +func (config DeleteStickerSetConfig) method() string { + return "deleteStickerSet" } -func (config SetChatStickerSetConfig) params() (Params, error) { +func (config DeleteStickerSetConfig) params() (Params, error) { params := make(Params) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params["sticker_set_name"] = config.StickerSetName + params["name"] = config.Name return params, nil } -// DeleteChatStickerSetConfig allows you to remove a supergroup's sticker set. -type DeleteChatStickerSetConfig struct { - ChatID int64 - SuperGroupUsername string +// DeleteStickerConfig allows you to delete a sticker from a set. +type DeleteStickerConfig struct { + Sticker string } -func (config DeleteChatStickerSetConfig) method() string { - return "deleteChatStickerSet" +func (config DeleteStickerConfig) method() string { + return "deleteStickerFromSet" } -func (config DeleteChatStickerSetConfig) params() (Params, error) { +func (config DeleteStickerConfig) params() (Params, error) { + params := make(Params) + + params["sticker"] = config.Sticker + + return params, nil +} + +// ReplaceStickerInSetConfig allows you to replace an existing sticker in a sticker set +// with a new one. The method is equivalent to calling deleteStickerFromSet, +// then addStickerToSet, then setStickerPositionInSet. +// Returns True on success. +type ReplaceStickerInSetConfig struct { + UserID int64 + Name string + OldSticker string + Sticker InputSticker +} + +func (config ReplaceStickerInSetConfig) method() string { + return "replaceStickerInSet" +} + +func (config ReplaceStickerInSetConfig) params() (Params, error) { params := make(Params) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddNonZero64("user_id", config.UserID) + params["name"] = config.Name + params["old_sticker"] = config.OldSticker + + err := params.AddInterface("sticker", config.Sticker) + + return params, err +} + +// SetStickerEmojiListConfig allows you to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot +type SetStickerEmojiListConfig struct { + Sticker string + EmojiList []string +} + +func (config SetStickerEmojiListConfig) method() string { + return "setStickerEmojiList" +} + +func (config SetStickerEmojiListConfig) params() (Params, error) { + params := make(Params) + + params["sticker"] = config.Sticker + err := params.AddInterface("emoji_list", config.EmojiList) + + return params, err +} + +// SetStickerKeywordsConfig allows you to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. +type SetStickerKeywordsConfig struct { + Sticker string + Keywords []string +} + +func (config SetStickerKeywordsConfig) method() string { + return "setStickerKeywords" +} + +func (config SetStickerKeywordsConfig) params() (Params, error) { + params := make(Params) + + params["sticker"] = config.Sticker + err := params.AddInterface("keywords", config.Keywords) + + return params, err +} + +// SetStickerMaskPositionConfig allows you to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot +type SetStickerMaskPositionConfig struct { + Sticker string + MaskPosition *MaskPosition +} + +func (config SetStickerMaskPositionConfig) method() string { + return "setStickerMaskPosition" +} + +func (config SetStickerMaskPositionConfig) params() (Params, error) { + params := make(Params) + + params["sticker"] = config.Sticker + err := params.AddInterface("keywords", config.MaskPosition) + + return params, err +} + +// SetStickerSetThumbConfig allows you to set the thumbnail for a sticker set. +type SetStickerSetThumbConfig struct { + Name string + UserID int64 + Thumb RequestFileData + Format string +} + +func (config SetStickerSetThumbConfig) method() string { + return "setStickerSetThumbnail" +} + +func (config SetStickerSetThumbConfig) params() (Params, error) { + params := make(Params) + + params["name"] = config.Name + params["format"] = config.Format + + params.AddNonZero64("user_id", config.UserID) + + return params, nil +} + +func (config SetStickerSetThumbConfig) files() []RequestFile { + return []RequestFile{{ + Name: "thumbnail", + Data: config.Thumb, + }} +} + +// SetChatStickerSetConfig allows you to set the sticker set for a supergroup. +type SetChatStickerSetConfig struct { + ChatConfig + + StickerSetName string +} + +func (config SetChatStickerSetConfig) method() string { + return "setChatStickerSet" +} + +func (config SetChatStickerSetConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params["sticker_set_name"] = config.StickerSetName return params, nil } +// DeleteChatStickerSetConfig allows you to remove a supergroup's sticker set. +type DeleteChatStickerSetConfig struct { + ChatConfig +} + +func (config DeleteChatStickerSetConfig) method() string { + return "deleteChatStickerSet" +} + +func (config DeleteChatStickerSetConfig) params() (Params, error) { + return config.ChatConfig.params() +} + +// GetForumTopicIconStickersConfig allows you to get custom emoji stickers, +// which can be used as a forum topic icon by any user. +type GetForumTopicIconStickersConfig struct{} + +func (config GetForumTopicIconStickersConfig) method() string { + return "getForumTopicIconStickers" +} + +func (config GetForumTopicIconStickersConfig) params() (Params, error) { + return nil, nil +} + +// CreateForumTopicConfig allows you to create a topic +// in a forum supergroup chat. +type CreateForumTopicConfig struct { + ChatConfig + Name string + IconColor int + IconCustomEmojiID string +} + +func (config CreateForumTopicConfig) method() string { + return "createForumTopic" +} + +func (config CreateForumTopicConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params.AddNonEmpty("name", config.Name) + params.AddNonZero("icon_color", config.IconColor) + params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) + + return params, nil +} + +type BaseForum struct { + ChatConfig + MessageThreadID int +} + +func (base BaseForum) params() (Params, error) { + params, err := base.ChatConfig.params() + if err != nil { + return params, err + } + params.AddNonZero("message_thread_id", base.MessageThreadID) + + return params, nil +} + +// EditForumTopicConfig allows you to edit +// name and icon of a topic in a forum supergroup chat. +type EditForumTopicConfig struct { + BaseForum + Name string + IconCustomEmojiID string +} + +func (config EditForumTopicConfig) method() string { + return "editForumTopic" +} + +func (config EditForumTopicConfig) params() (Params, error) { + params, err := config.BaseForum.params() + if err != nil { + return params, err + } + params.AddNonEmpty("name", config.Name) + params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) + + return params, nil +} + +// CloseForumTopicConfig allows you to close +// an open topic in a forum supergroup chat. +type CloseForumTopicConfig struct{ BaseForum } + +func (config CloseForumTopicConfig) method() string { + return "closeForumTopic" +} + +// ReopenForumTopicConfig allows you to reopen +// an closed topic in a forum supergroup chat. +type ReopenForumTopicConfig struct{ BaseForum } + +func (config ReopenForumTopicConfig) method() string { + return "reopenForumTopic" +} + +// DeleteForumTopicConfig allows you to delete a forum topic +// along with all its messages in a forum supergroup chat. +type DeleteForumTopicConfig struct{ BaseForum } + +func (config DeleteForumTopicConfig) method() string { + return "deleteForumTopic" +} + +// UnpinAllForumTopicMessagesConfig allows you to clear the list +// of pinned messages in a forum topic. +type UnpinAllForumTopicMessagesConfig struct{ BaseForum } + +func (config UnpinAllForumTopicMessagesConfig) method() string { + return "unpinAllForumTopicMessages" +} + +// UnpinAllForumTopicMessagesConfig allows you to edit the name of +// the 'General' topic in a forum supergroup chat. +// The bot must be an administrator in the chat for this to work +// and must have can_manage_topics administrator rights. Returns True on success. +type EditGeneralForumTopicConfig struct { + BaseForum + Name string +} + +func (config EditGeneralForumTopicConfig) method() string { + return "editGeneralForumTopic" +} + +func (config EditGeneralForumTopicConfig) params() (Params, error) { + params, err := config.BaseForum.params() + if err != nil { + return params, err + } + params.AddNonEmpty("name", config.Name) + + return params, nil +} + +// CloseGeneralForumTopicConfig allows you to to close an open 'General' topic +// in a forum supergroup chat. The bot must be an administrator in the chat +// for this to work and must have the can_manage_topics administrator rights. +// Returns True on success. +type CloseGeneralForumTopicConfig struct{ BaseForum } + +func (config CloseGeneralForumTopicConfig) method() string { + return "closeGeneralForumTopic" +} + +// CloseGeneralForumTopicConfig allows you to reopen a closed 'General' topic +// in a forum supergroup chat. The bot must be an administrator in the chat +// for this to work and must have the can_manage_topics administrator rights. +// The topic will be automatically unhidden if it was hidden. +// Returns True on success. +type ReopenGeneralForumTopicConfig struct{ BaseForum } + +func (config ReopenGeneralForumTopicConfig) method() string { + return "reopenGeneralForumTopic" +} + +// HideGeneralForumTopicConfig allows you to hide the 'General' topic +// in a forum supergroup chat. The bot must be an administrator in the chat +// for this to work and must have the can_manage_topics administrator rights. +// The topic will be automatically closed if it was open. +// Returns True on success. +type HideGeneralForumTopicConfig struct{ BaseForum } + +func (config HideGeneralForumTopicConfig) method() string { + return "hideGeneralForumTopic" +} + +// UnhideGeneralForumTopicConfig allows you to unhide the 'General' topic +// in a forum supergroup chat. The bot must be an administrator in the chat +// for this to work and must have the can_manage_topics administrator rights. +// Returns True on success. +type UnhideGeneralForumTopicConfig struct{ BaseForum } + +func (config UnhideGeneralForumTopicConfig) method() string { + return "unhideGeneralForumTopic" +} + +// UnpinAllGeneralForumTopicMessagesConfig allows you to to clear +// the list of pinned messages in a General forum topic. +// The bot must be an administrator in the chat for this to work +// and must have the can_pin_messages administrator right in the supergroup. +// Returns True on success. +type UnpinAllGeneralForumTopicMessagesConfig struct{ BaseForum } + +func (config UnpinAllGeneralForumTopicMessagesConfig) method() string { + return "unpinAllGeneralForumTopicMessages" +} + // MediaGroupConfig allows you to send a group of media. // // Media consist of InputMedia items (InputMediaPhoto, InputMediaVideo). type MediaGroupConfig struct { - ChatID int64 - ChannelUsername string - - Media []interface{} - DisableNotification bool - ReplyToMessageID int + BaseChat + Media []interface{} } func (config MediaGroupConfig) method() string { @@ -2237,13 +2900,12 @@ func (config MediaGroupConfig) method() string { } func (config MediaGroupConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddBool("disable_notification", config.DisableNotification) - params.AddNonZero("reply_to_message_id", config.ReplyToMessageID) + params, err := config.BaseChat.params() + if err != nil { + return nil, err + } - err := params.AddInterface("media", prepareInputMediaForParams(config.Media)) + err = params.AddInterface("media", prepareInputMediaForParams(config.Media)) return params, err } @@ -2278,6 +2940,49 @@ func (config DiceConfig) params() (Params, error) { return params, err } +type GetUserChatBoostsConfig struct { + ChatConfig + UserID int64 +} + +func (config GetUserChatBoostsConfig) method() string { + return "getUserChatBoosts" +} + +func (config GetUserChatBoostsConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params.AddNonZero64("user_id", config.UserID) + + return params, err +} + +type ( + GetBusinessConnectionConfig struct { + BusinessConnectionID BusinessConnectionID + } + BusinessConnectionID string +) + +func (GetBusinessConnectionConfig) method() string { + return "getBusinessConnection" +} + +func (config GetBusinessConnectionConfig) params() (Params, error) { + return config.BusinessConnectionID.params() +} + +func (config BusinessConnectionID) params() (Params, error) { + params := make(Params) + + params["business_connection_id"] = string(config) + + return params, nil +} + // GetMyCommandsConfig gets a list of the currently registered commands. type GetMyCommandsConfig struct { Scope *BotCommandScope @@ -2338,11 +3043,125 @@ func (config DeleteMyCommandsConfig) params() (Params, error) { return params, err } +// SetMyNameConfig change the bot's name +type SetMyNameConfig struct { + Name string + LanguageCode string +} + +func (config SetMyNameConfig) method() string { + return "setMyName" +} + +func (config SetMyNameConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("name", config.Name) + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +type GetMyNameConfig struct { + LanguageCode string +} + +func (config GetMyNameConfig) method() string { + return "getMyName" +} + +func (config GetMyNameConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +// GetMyDescriptionConfig get the current bot description for the given user language +type GetMyDescriptionConfig struct { + LanguageCode string +} + +func (config GetMyDescriptionConfig) method() string { + return "getMyDescription" +} + +func (config GetMyDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +// SetMyDescroptionConfig sets the bot's description, which is shown in the chat with the bot if the chat is empty +type SetMyDescriptionConfig struct { + // Pass an empty string to remove the dedicated description for the given language. + Description string + // If empty, the description will be applied to all users for whose language there is no dedicated description. + LanguageCode string +} + +func (config SetMyDescriptionConfig) method() string { + return "setMyDescription" +} + +func (config SetMyDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("description", config.Description) + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +// GetMyShortDescriptionConfig get the current bot short description for the given user language +type GetMyShortDescriptionConfig struct { + LanguageCode string +} + +func (config GetMyShortDescriptionConfig) method() string { + return "getMyShortDescription" +} + +func (config GetMyShortDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +// SetMyDescroptionConfig sets the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. +type SetMyShortDescriptionConfig struct { + // New short description for the bot; 0-120 characters. + // + //Pass an empty string to remove the dedicated short description for the given language. + ShortDescription string + //A two-letter ISO 639-1 language code. + // + //If empty, the short description will be applied to all users for whose language there is no dedicated short description. + LanguageCode string +} + +func (config SetMyShortDescriptionConfig) method() string { + return "setMyShortDescription" +} + +func (config SetMyShortDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("short_description", config.ShortDescription) + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + // SetChatMenuButtonConfig changes the bot's menu button in a private chat, // or the default menu button. type SetChatMenuButtonConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig MenuButton *MenuButton } @@ -2352,19 +3171,18 @@ func (config SetChatMenuButtonConfig) method() string { } func (config SetChatMenuButtonConfig) params() (Params, error) { - params := make(Params) - - if err := params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername); err != nil { + params, err := config.ChatConfig.params() + if err != nil { return params, err } - err := params.AddInterface("menu_button", config.MenuButton) + + err = params.AddInterface("menu_button", config.MenuButton) return params, err } type GetChatMenuButtonConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config GetChatMenuButtonConfig) method() string { @@ -2372,11 +3190,7 @@ func (config GetChatMenuButtonConfig) method() string { } func (config GetChatMenuButtonConfig) params() (Params, error) { - params := make(Params) - - err := params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, err + return config.ChatConfig.params() } type SetMyDefaultAdministratorRightsConfig struct { @@ -2450,6 +3264,16 @@ func prepareInputMediaParam(inputMedia interface{}, idx int) interface{} { m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) } + return m + case InputMediaAnimation: + if m.Media.NeedsUpload() { + m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) + } + + if m.Thumb != nil && m.Thumb.NeedsUpload() { + m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) + } + return m case InputMediaDocument: if m.Media.NeedsUpload() { @@ -2477,6 +3301,11 @@ func prepareInputMediaParam(inputMedia interface{}, idx int) interface{} { func prepareInputMediaFile(inputMedia interface{}, idx int) []RequestFile { files := []RequestFile{} + // Unwrap the PaidMediaConfig to get the media + if paidMedia, ok := inputMedia.(PaidMediaConfig); ok { + inputMedia = paidMedia.Media + } + switch m := inputMedia.(type) { case InputMediaPhoto: if m.Media.NeedsUpload() { @@ -2493,6 +3322,20 @@ func prepareInputMediaFile(inputMedia interface{}, idx int) []RequestFile { }) } + if m.Thumb != nil && m.Thumb.NeedsUpload() { + files = append(files, RequestFile{ + Name: fmt.Sprintf("file-%d", idx), + Data: m.Thumb, + }) + } + case InputMediaAnimation: + if m.Media.NeedsUpload() { + files = append(files, RequestFile{ + Name: fmt.Sprintf("file-%d", idx), + Data: m.Media, + }) + } + if m.Thumb != nil && m.Thumb.NeedsUpload() { files = append(files, RequestFile{ Name: fmt.Sprintf("file-%d", idx), diff --git a/examples/polling_echo.go b/examples/polling_echo.go new file mode 100644 index 00000000..c9852e0c --- /dev/null +++ b/examples/polling_echo.go @@ -0,0 +1,73 @@ +package main + +import ( + "log" + "time" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { polling_echo() } + +func polling_echo() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + + // Empty list allows all updates excluding + // UpdateTypeChatMember, UpdateTypeMessageReaction and UpdateTypeMessageReactionCount + updateConfig.AllowedUpdates = []string{ + api.UpdateTypeMessage, + api.UpdateTypeEditedMessage, + api.UpdateTypeChannelPost, + api.UpdateTypeEditedChannelPost, + api.UpdateTypeBusinessConnection, + api.UpdateTypeBusinessMessage, + api.UpdateTypeEditedBusinessMessage, + api.UpdateTypeDeletedBusinessMessages, + api.UpdateTypeMessageReaction, + api.UpdateTypeMessageReactionCount, + api.UpdateTypeInlineQuery, + api.UpdateTypeChosenInlineResult, + api.UpdateTypeCallbackQuery, + api.UpdateTypeShippingQuery, + api.UpdateTypePreCheckoutQuery, + api.UpdateTypePurchasedPaidMedia, + api.UpdateTypePoll, + api.UpdateTypePollAnswer, + api.UpdateTypeMyChatMember, + api.UpdateTypeChatMember, + api.UpdateTypeChatJoinRequest, + api.UpdateTypeChatBoost, + api.UpdateTypeRemovedChatBoost, + } + + updatesChannel := bot.GetUpdatesChan(updateConfig) + + // Optional: wait for updates and clear them if you don't want to handle + // a large backlog of old messages + time.Sleep(time.Millisecond * 500) + updatesChannel.Clear() + + for update := range updatesChannel { + if update.Message == nil { + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + } +} diff --git a/examples/polling_inline_query.go b/examples/polling_inline_query.go new file mode 100644 index 00000000..1591f3fe --- /dev/null +++ b/examples/polling_inline_query.go @@ -0,0 +1,43 @@ +package main + +import ( + "log" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { polling_inline_query() } + +func polling_inline_query() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") // create new bot + if err != nil { + panic(err) + } + + log.Printf("Authorized on account %s", bot.Self.UserName) + + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + + updatesChannel := bot.GetUpdatesChan(updateConfig) + + for update := range updatesChannel { + if update.InlineQuery == nil { // if no inline query, skip update + continue + } + + article := api.NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query) + article.Description = update.InlineQuery.Query + + inlineConfig := api.InlineConfig{ + InlineQueryID: update.InlineQuery.ID, + IsPersonal: true, + CacheTime: 0, + Results: []interface{}{article}, + } + + if _, err := bot.Request(inlineConfig); err != nil { + log.Println(err) + } + } +} diff --git a/examples/webhook_custom_handler.go b/examples/webhook_custom_handler.go new file mode 100644 index 00000000..cdf98230 --- /dev/null +++ b/examples/webhook_custom_handler.go @@ -0,0 +1,86 @@ +package main + +import ( + "log" + "net/http" + "sync" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { webhook_custom_handler() } + +func webhook_custom_handler() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + // Listen for updates from the webhook and handle them yourself + http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) { + update, err := bot.HandleUpdate(r) + if err != nil { + log.Printf("%+v\n", err.Error()) + } else { + log.Printf("%+v\n", *update) + } + + if update.Message == nil { + return + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + }) + + waitGroup := sync.WaitGroup{} + + waitGroup.Add(1) + go func() { + defer waitGroup.Done() + if err := http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil); err != nil { + log.Printf("Error listening on TLS: %v", err) + } + }() + + // Set the webhook + webHook, err := api.NewWebhookWithCert("https://your-bot-host-url/"+bot.Token, api.FilePath("cert.pem")) + if err != nil { + panic(err) + } + if err != nil { + panic(err) + } + + apiResponse, err := bot.Request(webHook) + if err != nil { + panic(err) + } + + if apiResponse.Ok { + log.Printf("Webhook set successfully") + } else { + log.Printf("Failed to set webhook: %s", apiResponse.Description) + } + + info, err := bot.GetWebhookInfo() + if err != nil { + panic(err) + } + + if info.LastErrorDate != 0 { + log.Printf("Failed to get webhook info: %s", info.LastErrorMessage) + } + + // Wait for the server to terminate + waitGroup.Wait() +} diff --git a/examples/webhook_echo.go b/examples/webhook_echo.go new file mode 100644 index 00000000..2be84bcc --- /dev/null +++ b/examples/webhook_echo.go @@ -0,0 +1,65 @@ +package main + +import ( + "log" + "net/http" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { webhook_echo() } + +func webhook_echo() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + // Listen for updates from the webhook + updates := bot.ListenForWebhook("/" + bot.Token) + go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) + + // Set the webhook + webHook, err := api.NewWebhookWithCert("https://your-bot-host-url/"+bot.Token, api.FilePath("cert.pem")) + if err != nil { + panic(err) + } + + apiResponse, err := bot.Request(webHook) + if err != nil { + panic(err) + } + + if apiResponse.Ok { + log.Printf("Webhook set successfully") + } else { + log.Printf("Failed to set webhook: %s", apiResponse.Description) + } + + info, err := bot.GetWebhookInfo() + if err != nil { + panic(err) + } + + if info.LastErrorDate != 0 { + log.Printf("Failed to get webhook info: %s", info.LastErrorMessage) + } + + for update := range updates { + if update.Message == nil { + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + } +} diff --git a/go.mod b/go.mod index 167e5e45..ac59cc91 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/go-telegram-bot-api/telegram-bot-api/v5 +module github.com/OvyFlash/telegram-bot-api -go 1.16 +go 1.23 diff --git a/helpers.go b/helper_methods.go similarity index 71% rename from helpers.go rename to helper_methods.go index 3a0e8187..c7150faa 100644 --- a/helpers.go +++ b/helper_methods.go @@ -17,19 +17,39 @@ import ( func NewMessage(chatID int64, text string) MessageConfig { return MessageConfig{ BaseChat: BaseChat{ - ChatID: chatID, - ReplyToMessageID: 0, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + }, + Text: text, + LinkPreviewOptions: LinkPreviewOptions{ + IsDisabled: false, }, - Text: text, - DisableWebPagePreview: false, } } // NewDeleteMessage creates a request to delete a message. func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { return DeleteMessageConfig{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + } +} + +// NewDeleteMessages creates a request to delete multiple messages. The messages have to be +// in the same chat. Provide the message ids as an array of integers +func NewDeleteMessages(chatID int64, messageIDs []int) DeleteMessagesConfig { + return DeleteMessagesConfig{ + BaseChatMessages: BaseChatMessages{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageIDs: messageIDs, + }, } } @@ -41,8 +61,9 @@ func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { func NewMessageToChannel(username string, text string) MessageConfig { return MessageConfig{ BaseChat: BaseChat{ - ChannelUsername: username, - }, + ChatConfig: ChatConfig{ + ChannelUsername: username, + }}, Text: text, } } @@ -53,9 +74,9 @@ func NewMessageToChannel(username string, text string) MessageConfig { // and messageID is the ID of the original message. func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig { return ForwardConfig{ - BaseChat: BaseChat{ChatID: chatID}, - FromChatID: fromChatID, - MessageID: messageID, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, + FromChat: ChatConfig{ChatID: fromChatID}, + MessageID: messageID, } } @@ -65,9 +86,9 @@ func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig { // and messageID is the ID of the original message. func NewCopyMessage(chatID int64, fromChatID int64, messageID int) CopyMessageConfig { return CopyMessageConfig{ - BaseChat: BaseChat{ChatID: chatID}, - FromChatID: fromChatID, - MessageID: messageID, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, + FromChat: ChatConfig{ChatID: fromChatID}, + MessageID: messageID, } } @@ -80,7 +101,7 @@ func NewCopyMessage(chatID int64, fromChatID int64, messageID int) CopyMessageCo func NewPhoto(chatID int64, file RequestFileData) PhotoConfig { return PhotoConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -92,10 +113,8 @@ func NewPhoto(chatID int64, file RequestFileData) PhotoConfig { func NewPhotoToChannel(username string, file RequestFileData) PhotoConfig { return PhotoConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ - ChannelUsername: username, - }, - File: file, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChannelUsername: username}}, + File: file, }, } } @@ -104,7 +123,7 @@ func NewPhotoToChannel(username string, file RequestFileData) PhotoConfig { func NewAudio(chatID int64, file RequestFileData) AudioConfig { return AudioConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -114,7 +133,7 @@ func NewAudio(chatID int64, file RequestFileData) AudioConfig { func NewDocument(chatID int64, file RequestFileData) DocumentConfig { return DocumentConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -124,17 +143,40 @@ func NewDocument(chatID int64, file RequestFileData) DocumentConfig { func NewSticker(chatID int64, file RequestFileData) StickerConfig { return StickerConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } } +// NewCustomEmojiStickerSetThumbnal creates a new setCustomEmojiStickerSetThumbnal request +func NewCustomEmojiStickerSetThumbnal(name, customEmojiID string) SetCustomEmojiStickerSetThumbnailConfig { + return SetCustomEmojiStickerSetThumbnailConfig{ + Name: name, + CustomEmojiID: customEmojiID, + } +} + +// NewStickerSetTitle creates a new setStickerSetTitle request +func NewStickerSetTitle(name, title string) SetStickerSetTitleConfig { + return SetStickerSetTitleConfig{ + Name: name, + Title: title, + } +} + +// NewDeleteStickerSet creates a new deleteStickerSet request +func NewDeleteStickerSet(name, title string) DeleteStickerSetConfig { + return DeleteStickerSetConfig{ + Name: name, + } +} + // NewVideo creates a new sendVideo request. func NewVideo(chatID int64, file RequestFileData) VideoConfig { return VideoConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -144,7 +186,7 @@ func NewVideo(chatID int64, file RequestFileData) VideoConfig { func NewAnimation(chatID int64, file RequestFileData) AnimationConfig { return AnimationConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -157,7 +199,7 @@ func NewAnimation(chatID int64, file RequestFileData) AnimationConfig { func NewVideoNote(chatID int64, length int, file RequestFileData) VideoNoteConfig { return VideoNoteConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, Length: length, @@ -168,7 +210,7 @@ func NewVideoNote(chatID int64, length int, file RequestFileData) VideoNoteConfi func NewVoice(chatID int64, file RequestFileData) VoiceConfig { return VoiceConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -178,8 +220,18 @@ func NewVoice(chatID int64, file RequestFileData) VoiceConfig { // two to ten InputMediaPhoto or InputMediaVideo. func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { return MediaGroupConfig{ - ChatID: chatID, - Media: files, + BaseChat: BaseChat{ + ChatConfig: ChatConfig{ChatID: chatID}, + }, + Media: files, + } +} + +// NewBaseInputMedia creates a new BaseInputMedia. +func NewBaseInputMedia(mediaType string, media RequestFileData) BaseInputMedia { + return BaseInputMedia{ + Type: mediaType, + Media: media, } } @@ -237,7 +289,7 @@ func NewInputMediaDocument(media RequestFileData) InputMediaDocument { func NewContact(chatID int64, phoneNumber, firstName string) ContactConfig { return ContactConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, PhoneNumber: phoneNumber, FirstName: firstName, @@ -250,7 +302,7 @@ func NewContact(chatID int64, phoneNumber, firstName string) ContactConfig { func NewLocation(chatID int64, latitude float64, longitude float64) LocationConfig { return LocationConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Latitude: latitude, Longitude: longitude, @@ -261,7 +313,7 @@ func NewLocation(chatID int64, latitude float64, longitude float64) LocationConf func NewVenue(chatID int64, title, address string, latitude, longitude float64) VenueConfig { return VenueConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Title: title, Address: address, @@ -276,7 +328,7 @@ func NewVenue(chatID int64, title, address string, latitude, longitude float64) // chatID is where to send it, action should be set via Chat constants. func NewChatAction(chatID int64, action string) ChatActionConfig { return ChatActionConfig{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, Action: action, } } @@ -563,12 +615,56 @@ func NewInlineQueryResultVenue(id, title, address string, latitude, longitude fl } } +// NewEditMessageMedia allows you to edit the media content of a message. +func NewEditMessageMedia(chatID int64, messageID int, inputMedia interface{}) EditMessageMediaConfig { + return EditMessageMediaConfig{ + BaseEdit: BaseEdit{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + }, + Media: inputMedia, + } +} + +// NewEditMessagePhoto allows you to edit the photo content of a message. +func NewEditMessagePhoto(chatID int64, messageID int, inputPhoto InputMediaPhoto) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputPhoto) +} + +// NewEditMessageVideo allows you to edit the video content of a message. +func NewEditMessageVideo(chatID int64, messageID int, inputVideo InputMediaVideo) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputVideo) +} + +// NewEditMessageAnimation allows you to edit the animation content of a message. +func NewEditMessageAnimation(chatID int64, messageID int, inputAnimation InputMediaAnimation) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputAnimation) +} + +// NewEditMessageAudio allows you to edit the audio content of a message. +func NewEditMessageAudio(chatID int64, messageID int, inputAudio InputMediaAudio) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputAudio) +} + +// NewEditMessageDocument allows you to edit the document content of a message. +func NewEditMessageDocument(chatID int64, messageID int, inputDocument InputMediaDocument) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputDocument) +} + // NewEditMessageText allows you to edit the text of a message. func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTextConfig { return EditMessageTextConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, }, Text: text, } @@ -578,8 +674,12 @@ func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTex func NewEditMessageTextAndMarkup(chatID int64, messageID int, text string, replyMarkup InlineKeyboardMarkup) EditMessageTextConfig { return EditMessageTextConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, ReplyMarkup: &replyMarkup, }, Text: text, @@ -590,8 +690,12 @@ func NewEditMessageTextAndMarkup(chatID int64, messageID int, text string, reply func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMessageCaptionConfig { return EditMessageCaptionConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, }, Caption: caption, } @@ -602,8 +706,12 @@ func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMess func NewEditMessageReplyMarkup(chatID int64, messageID int, replyMarkup InlineKeyboardMarkup) EditMessageReplyMarkupConfig { return EditMessageReplyMarkupConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, ReplyMarkup: &replyMarkup, }, } @@ -698,6 +806,15 @@ func NewInlineKeyboardButtonWebApp(text string, webapp WebAppInfo) InlineKeyboar } } +// NewInlineKeyboardButtonSwitchInlineQueryChoosenChat creates an inline keyboard button with text +// which goes to a SwitchInlineQueryChosenChat. +func NewInlineKeyboardButtonSwitchInlineQueryChoosenChat(text string, switchInlineQueryChosenChat SwitchInlineQueryChosenChat) InlineKeyboardButton { + return InlineKeyboardButton{ + Text: text, + SwitchInlineQueryChosenChat: &switchInlineQueryChosenChat, + } +} + // NewInlineKeyboardButtonLoginURL creates an inline keyboard button with text // which goes to a LoginURL. func NewInlineKeyboardButtonLoginURL(text string, loginURL LoginURL) InlineKeyboardButton { @@ -765,40 +882,122 @@ func NewCallbackWithAlert(id, text string) CallbackConfig { } // NewInvoice creates a new Invoice request to the user. -func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices []LabeledPrice) InvoiceConfig { +func NewInvoice( + chatID int64, + title string, + description string, + payload string, + providerToken string, + startParameter string, + currency string, + prices []LabeledPrice, + suggestedTipAmounts []int, +) InvoiceConfig { + var maxTipAmount, n int + for n = range suggestedTipAmounts { + if maxTipAmount < suggestedTipAmounts[n] { + maxTipAmount = suggestedTipAmounts[n] + } + } return InvoiceConfig{ - BaseChat: BaseChat{ChatID: chatID}, - Title: title, - Description: description, - Payload: payload, - ProviderToken: providerToken, - StartParameter: startParameter, - Currency: currency, - Prices: prices} + BaseChat: BaseChat{ + ChatConfig: ChatConfig{ChatID: chatID}, + }, + Title: title, + Description: description, + Payload: payload, + ProviderToken: providerToken, + StartParameter: startParameter, + Currency: currency, + Prices: prices, + SuggestedTipAmounts: suggestedTipAmounts, + MaxTipAmount: maxTipAmount, + } +} + +// NewInvoiceLink creates a new createInvoiceLink request. +func NewInvoiceLink(ico InvoiceConfig) InvoiceLinkConfig { + return InvoiceLinkConfig{ + Title: ico.Title, + Description: ico.Description, + Payload: ico.Payload, + ProviderToken: ico.ProviderToken, + Currency: ico.Currency, + Prices: ico.Prices, + SuggestedTipAmounts: ico.SuggestedTipAmounts, + MaxTipAmount: ico.MaxTipAmount, + } } // NewChatTitle allows you to update the title of a chat. func NewChatTitle(chatID int64, title string) SetChatTitleConfig { return SetChatTitleConfig{ - ChatID: chatID, - Title: title, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + Title: title, } } // NewChatDescription allows you to update the description of a chat. func NewChatDescription(chatID int64, description string) SetChatDescriptionConfig { return SetChatDescriptionConfig{ - ChatID: chatID, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, Description: description, } } +func NewPinChatMessage(chatID int64, messageID int, disableNotification bool) PinChatMessageConfig { + return PinChatMessageConfig{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + DisableNotification: disableNotification, + } +} + +func NewUnpinChatMessage(chatID int64, messageID int) UnpinChatMessageConfig { + return UnpinChatMessageConfig{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + } +} + +func NewGetChatMember(chatID, userID int64) GetChatMemberConfig { + return GetChatMemberConfig{ + ChatConfigWithUser: ChatConfigWithUser{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + UserID: userID, + }, + } +} + +func NewChatMember(chatID, userID int64) ChatMemberConfig { + return ChatMemberConfig{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + UserID: userID, + } +} + // NewChatPhoto allows you to update the photo for a chat. func NewChatPhoto(chatID int64, photo RequestFileData) SetChatPhotoConfig { return SetChatPhotoConfig{ BaseFile: BaseFile{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, File: photo, }, @@ -808,15 +1007,17 @@ func NewChatPhoto(chatID int64, photo RequestFileData) SetChatPhotoConfig { // NewDeleteChatPhoto allows you to delete the photo for a chat. func NewDeleteChatPhoto(chatID int64) DeleteChatPhotoConfig { return DeleteChatPhotoConfig{ - ChatID: chatID, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, } } // NewPoll allows you to create a new poll. -func NewPoll(chatID int64, question string, options ...string) SendPollConfig { +func NewPoll(chatID int64, question string, options ...InputPollOption) SendPollConfig { return SendPollConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Question: question, Options: options, @@ -824,12 +1025,23 @@ func NewPoll(chatID int64, question string, options ...string) SendPollConfig { } } +// NewPollOption allows you to create poll option +func NewPollOption(text string) InputPollOption { + return InputPollOption{ + Text: text, + } +} + // NewStopPoll allows you to stop a poll. func NewStopPoll(chatID int64, messageID int) StopPollConfig { return StopPollConfig{ BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, }, } } @@ -838,7 +1050,7 @@ func NewStopPoll(chatID int64, messageID int) StopPollConfig { func NewDice(chatID int64) DiceConfig { return DiceConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, } } @@ -849,12 +1061,26 @@ func NewDice(chatID int64) DiceConfig { func NewDiceWithEmoji(chatID int64, emoji string) DiceConfig { return DiceConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Emoji: emoji, } } +// NewSetMessageReaction allows you to set a message's reactions. +func NewSetMessageReaction(chatID int64, messageID int, reaction []ReactionType, isBig bool) SetMessageReactionConfig { + return SetMessageReactionConfig{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + Reaction: reaction, + IsBig: isBig, + } +} + // NewBotCommandScopeDefault represents the default scope of bot commands. func NewBotCommandScopeDefault() BotCommandScope { return BotCommandScope{Type: "default"} @@ -906,6 +1132,58 @@ func NewBotCommandScopeChatMember(chatID, userID int64) BotCommandScope { } } +// NewSetMyDescription allows you to change the bot's description, which is shown in the chat with the bot if the chat is empty. +func NewSetMyDescription(description, languageCode string) SetMyDescriptionConfig { + return SetMyDescriptionConfig{ + Description: description, + LanguageCode: languageCode, + } +} + +// NewGetMyDescription returns the current bot description for the given user language +func NewGetMyDescription(languageCode string) GetMyDescriptionConfig { + return GetMyDescriptionConfig{ + LanguageCode: languageCode, + } +} + +// NewSetMyShortDescription allows you change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. +func NewSetMyShortDescription(shortDescription, languageCode string) SetMyShortDescriptionConfig { + return SetMyShortDescriptionConfig{ + ShortDescription: shortDescription, + LanguageCode: languageCode, + } +} + +// NewGetMyShortDescription returns the current bot short description for the given user language. +func NewGetMyShortDescription(languageCode string) GetMyShortDescriptionConfig { + return GetMyShortDescriptionConfig{ + LanguageCode: languageCode, + } +} + +// NewGetMyName get the current bot name for the given user language +func NewGetMyName(languageCode string) GetMyNameConfig { + return GetMyNameConfig{ + LanguageCode: languageCode, + } +} + +// NewSetMyName change the bot's name +func NewSetMyName(languageCode, name string) SetMyNameConfig { + return SetMyNameConfig{ + Name: name, + LanguageCode: languageCode, + } +} + +// NewGetBusinessConnection gets business connection request struct +func NewGetBusinessConnection(id string) GetBusinessConnectionConfig { + return GetBusinessConnectionConfig{ + BusinessConnectionID: BusinessConnectionID(id), + } +} + // NewGetMyCommandsWithScope allows you to set the registered commands for a // given scope. func NewGetMyCommandsWithScope(scope BotCommandScope) GetMyCommandsConfig { diff --git a/helper_structs.go b/helper_structs.go new file mode 100644 index 00000000..10ddc847 --- /dev/null +++ b/helper_structs.go @@ -0,0 +1,141 @@ +package tgbotapi + +// ChatConfig is a base type for all chat identifiers +type ChatConfig struct { + ChatID int64 + ChannelUsername string + SuperGroupUsername string +} + +func (base ChatConfig) params() (Params, error) { + return base.paramsWithKey("chat_id") +} + +func (base ChatConfig) paramsWithKey(key string) (Params, error) { + params := make(Params) + return params, params.AddFirstValid(key, base.ChatID, base.ChannelUsername, base.SuperGroupUsername) +} + +// BaseChat is base type for all chat config types. +type BaseChat struct { + ChatConfig + BusinessConnectionID BusinessConnectionID + MessageThreadID int + ProtectContent bool + ReplyMarkup interface{} + DisableNotification bool + MessageEffectID string // for private chats only + ReplyParameters ReplyParameters +} + +func (chat *BaseChat) params() (Params, error) { + params, err := chat.ChatConfig.params() + if err != nil { + return params, err + } + p1, err := chat.BusinessConnectionID.params() + if err != nil { + return params, err + } + params.Merge(p1) + + params.AddNonZero("message_thread_id", chat.MessageThreadID) + params.AddBool("disable_notification", chat.DisableNotification) + params.AddBool("protect_content", chat.ProtectContent) + params.AddNonEmpty("message_effect_id", chat.MessageEffectID) + + err = params.AddInterface("reply_markup", chat.ReplyMarkup) + if err != nil { + return params, err + } + err = params.AddInterface("reply_parameters", chat.ReplyParameters) + return params, err +} + +// BaseFile is a base type for all file config types. +type BaseFile struct { + BaseChat + File RequestFileData +} + +func (file BaseFile) params() (Params, error) { + return file.BaseChat.params() +} + +// BaseEdit is base type of all chat edits. +type BaseEdit struct { + BaseChatMessage + InlineMessageID string + ReplyMarkup *InlineKeyboardMarkup +} + +func (edit BaseEdit) params() (Params, error) { + params := make(Params) + + if edit.InlineMessageID != "" { + params["inline_message_id"] = edit.InlineMessageID + } else { + p1, err := edit.BaseChatMessage.params() + if err != nil { + return params, err + } + params.Merge(p1) + } + + err := params.AddInterface("reply_markup", edit.ReplyMarkup) + + return params, err +} + +// BaseSpoiler is base type of structures with spoilers. +type BaseSpoiler struct { + HasSpoiler bool +} + +func (spoiler BaseSpoiler) params() (Params, error) { + params := make(Params) + + if spoiler.HasSpoiler { + params.AddBool("has_spoiler", true) + } + + return params, nil +} + +// BaseChatMessage is a base type for all messages in chats. +type BaseChatMessage struct { + ChatConfig + MessageID int + BusinessConnectionID BusinessConnectionID +} + +func (base BaseChatMessage) params() (Params, error) { + params, err := base.ChatConfig.params() + if err != nil { + return params, err + } + p1, err := base.BusinessConnectionID.params() + if err != nil { + return params, err + } + params.Merge(p1) + params.AddNonZero("message_id", base.MessageID) + + return params, err +} + +// BaseChatMessages is a base type for all messages in chats. +type BaseChatMessages struct { + ChatConfig + MessageIDs []int +} + +func (base BaseChatMessages) params() (Params, error) { + params, err := base.ChatConfig.params() + if err != nil { + return params, err + } + err = params.AddInterface("message_ids", base.MessageIDs) + + return params, err +} diff --git a/helpers_test.go b/helpers_test.go index 9119543d..ffe3805f 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -178,6 +178,133 @@ func TestNewInlineKeyboardButtonLoginURL(t *testing.T) { } } +func TestNewInlineKeyboardButtonSwitchInlineQueryChoosenChat(t *testing.T) { + result := NewInlineKeyboardButtonSwitchInlineQueryChoosenChat("text", SwitchInlineQueryChosenChat{ + Query: "query", + AllowUserChats: false, + AllowBotChats: false, + AllowGroupChats: false, + AllowChannelChats: false, + }) + + if result.Text != "text" || + result.SwitchInlineQueryChosenChat.Query != "query" || + result.SwitchInlineQueryChosenChat.AllowUserChats != false || + result.SwitchInlineQueryChosenChat.AllowBotChats != false || + result.SwitchInlineQueryChosenChat.AllowGroupChats != false || + result.SwitchInlineQueryChosenChat.AllowChannelChats != false { + t.Fail() + } +} + +func TestNewEditMessageMedia(t *testing.T) { + baseInputMedia := NewBaseInputMedia("photo", FileID("test")) + edit := NewEditMessageMedia(ChatID, ReplyToMessageID, baseInputMedia) + + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(BaseInputMedia); !ok || + media.Type != "photo" || + media.Media != baseInputMedia.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessagePhoto(t *testing.T) { + inputMediaPhoto := NewInputMediaPhoto(FilePath("tests/image.jpg")) + edit := NewEditMessagePhoto(ChatID, ReplyToMessageID, inputMediaPhoto) + + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaPhoto); !ok || + media.Type != "photo" || + media.Media != inputMediaPhoto.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageVideo(t *testing.T) { + inputMediaVideo := NewInputMediaVideo(FilePath("tests/video.mp4")) + edit := NewEditMessageVideo(ChatID, ReplyToMessageID, inputMediaVideo) + + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaVideo); !ok || + media.Type != "video" || + media.Media != inputMediaVideo.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageAnimation(t *testing.T) { + inputMediaAnimation := NewInputMediaAnimation(FileID("test")) + edit := NewEditMessageAnimation(ChatID, ReplyToMessageID, inputMediaAnimation) + + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaAnimation); !ok || + media.Type != "animation" || + media.Media != inputMediaAnimation.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageAudio(t *testing.T) { + inputMediaAudio := NewInputMediaAudio(FileID("test")) + edit := NewEditMessageAudio(ChatID, ReplyToMessageID, inputMediaAudio) + + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaAudio); !ok || + media.Type != "audio" || + media.Media != inputMediaAudio.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageDocument(t *testing.T) { + inputMediaDocument := NewInputMediaDocument(FileID("test")) + edit := NewEditMessageDocument(ChatID, ReplyToMessageID, inputMediaDocument) + + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaDocument); !ok || + media.Type != "document" || + media.Media != inputMediaDocument.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + func TestNewEditMessageText(t *testing.T) { edit := NewEditMessageText(ChatID, ReplyToMessageID, "new text") diff --git a/params.go b/params.go index 134f85e4..9afd07df 100644 --- a/params.go +++ b/params.go @@ -95,3 +95,10 @@ func (p Params) AddFirstValid(key string, args ...interface{}) error { return nil } + +// Merge merges two sets of parameters. Overwrites old fields if present +func (p *Params) Merge(p1 Params) { + for k, v := range p1 { + (*p)[k] = v + } +} diff --git a/types.go b/types.go index 36c174b8..75d8fc42 100644 --- a/types.go +++ b/types.go @@ -61,6 +61,34 @@ type Update struct { // // optional EditedChannelPost *Message `json:"edited_channel_post,omitempty"` + // BusinessConnection the bot was connected to or disconnected from a + // business account, or a user edited an existing connection with the bot + // + // optional + BusinessConnection *BusinessConnection `json:"business_connection,omitempty"` + // BusinessMessage is a new non-service message from a + // connected business account + // + // optional + BusinessMessage *Message `json:"business_message,omitempty"` + // EditedBusinessMessage is a new version of a message from a + // connected business account + // + // optional + EditedBusinessMessage *Message `json:"edited_business_message,omitempty"` + // DeletedBusinessMessages are the messages were deleted from a + // connected business account + // + // optional + DeletedBusinessMessages *BusinessMessagesDeleted `json:"deleted_business_messages,omitempty"` + // MessageReaction is a reaction to a message was changed by a user. + // + // optional + MessageReaction *MessageReactionUpdated `json:"message_reaction,omitempty"` + // MessageReactionCount reactions to a message with anonymous reactions were changed. + // + // optional + MessageReactionCount *MessageReactionCountUpdated `json:"message_reaction_count,omitempty"` // InlineQuery new incoming inline query // // optional @@ -86,6 +114,11 @@ type Update struct { // // optional PreCheckoutQuery *PreCheckoutQuery `json:"pre_checkout_query,omitempty"` + // PurchasedPaidMedia is user purchased paid media with a non-empty + // payload sent by the bot in a non-channel chat + // + // optional + PurchasedPaidMedia *PaidMediaPurchased `json:"purchased_paid_media,omitempty"` // Pool new poll state. Bots receive only updates about stopped polls and // polls, which are sent by the bot // @@ -114,6 +147,14 @@ type Update struct { // // optional ChatJoinRequest *ChatJoinRequest `json:"chat_join_request,omitempty"` + // ChatBoostUpdated represents a boost added to a chat or changed. + // + // optional + ChatBoost *ChatBoostUpdated `json:"chat_boost,omitempty"` + // ChatBoostRemoved represents a boost removed from a chat. + // + // optional + ChatBoostRemoved *ChatBoostRemoved `json:"removed_chat_boost,omitempty"` } // SentFrom returns the user who sent an update. Can be nil, if Telegram did not provide information @@ -151,15 +192,15 @@ func (u *Update) CallbackData() string { func (u *Update) FromChat() *Chat { switch { case u.Message != nil: - return u.Message.Chat + return &u.Message.Chat case u.EditedMessage != nil: - return u.EditedMessage.Chat + return &u.EditedMessage.Chat case u.ChannelPost != nil: - return u.ChannelPost.Chat + return &u.ChannelPost.Chat case u.EditedChannelPost != nil: - return u.EditedChannelPost.Chat - case u.CallbackQuery != nil: - return u.CallbackQuery.Message.Chat + return &u.EditedChannelPost.Chat + case u.CallbackQuery != nil && u.CallbackQuery.Message != nil: + return &u.CallbackQuery.Message.Chat default: return nil } @@ -187,6 +228,10 @@ type User struct { // // optional IsPremium bool `json:"is_premium,omitempty"` + // AddedToAttachmentMenu true, if this user added the bot to the attachment menu + // + // optional + AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"` // FirstName user's or bot's first name FirstName string `json:"first_name"` // LastName user's or bot's last name @@ -217,6 +262,16 @@ type User struct { // // optional SupportsInlineQueries bool `json:"supports_inline_queries,omitempty"` + // CanConnectToBusiness is true, if the bot can be connected to a + // Telegram Business account to receive its messages. + // Returned only in getMe. + // + // optional + CanConnectToBusiness bool `json:"can_connect_to_business,omitempty"` + // True, if the bot has a main Web App. Returned only in getMe. + // + // optional + HasMainWebApp bool `json:"has_main_web_app,omitempty"` } // String displays a simple text version of a user. @@ -261,8 +316,87 @@ type Chat struct { // // optional LastName string `json:"last_name,omitempty"` + // IsForum is true if the supergroup chat is a forum (has topics enabled) + // + // optional + IsForum bool `json:"is_forum,omitempty"` +} + +// ChatFullInfo contains full information about a chat. +type ChatFullInfo struct { + Chat // Photo is a chat photo Photo *ChatPhoto `json:"photo"` + // If non-empty, the list of all active chat usernames; + // for private chats, supergroups and channels. Returned only in getChat. + // + // optional + ActiveUsernames []string `json:"active_usernames,omitempty"` + // Birthdate for private chats, the date of birth of the user. + // Returned only in getChat. + // + // optional + Birthdate *Birthdate `json:"birthdate,omitempty"` + // BusinessIntro is for private chats with business accounts, the intro of the business. + // Returned only in getChat. + // + // optional + BusinessIntro *BusinessIntro `json:"business_intro,omitempty"` + // BusinessLocation is for private chats with business accounts, the location + // of the business. Returned only in getChat. + // + // optional + BusinessLocation *BusinessLocation `json:"business_location,omitempty"` + // BusinessOpeningHours is for private chats with business accounts, + // the opening hours of the business. Returned only in getChat. + // + // optional + BusinessOpeningHours *BusinessOpeningHours `json:"business_opening_hours,omitempty"` + // PersonalChat is for private chats, the personal channel of the user. + // Returned only in getChat. + // + // optional + PersonalChat *Chat `json:"personal_chat,omitempty"` + // AvailableReactions is a list of available reactions allowed in the chat. + // If omitted, then all emoji reactions are allowed. Returned only in getChat. + // + // optional + AvailableReactions []ReactionType `json:"available_reactions,omitempty"` + // AccentColorID is an identifier of the accent color for the chat name and backgrounds of + // the chat photo, reply header, and link preview. + // See accent colors for more details. Returned only in getChat. + // Always returned in getChat. + // + // optional + AccentColorID int `json:"accent_color_id,omitempty"` + // The maximum number of reactions that can be set on a message in the chat + MaxReactionCount int `json:"max_reaction_count"` + // BackgroundCustomEmojiID is a custom emoji identifier of emoji chosen by + // the chat for the reply header and link preview background. + // Returned only in getChat. + // + // optional + BackgroundCustomEmojiID string `json:"background_custom_emoji_id,omitempty"` + // ProfileAccentColorID is ani dentifier of the accent color for the chat's profile background. + // See profile accent colors for more details. Returned only in getChat. + // + // optional + ProfileAccentColorID int `json:"profile_accent_color_id,omitempty"` + // ProfileBackgroundCustomEmojiID is a custom emoji identifier of the emoji chosen by + // the chat for its profile background. Returned only in getChat. + // + // optional + ProfileBackgroundCustomEmojiID string `json:"profile_background_custom_emoji_id,omitempty"` + // EmojiStatusCustomEmojiID is a custom emoji identifier of emoji status of the other party + // in a private chat. Returned only in getChat. + // + // optional + EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"` + // EmojiStatusExpirationDate is a date of the emoji status of the chat or the other party + // in a private chat, in Unix time, if any. Returned only in getChat. + // + // optional + EmojiStatusExpirationDate int64 `json:"emoji_status_expiration_date,omitempty"` // Bio is the bio of the other party in a private chat. Returned only in // getChat // @@ -274,6 +408,24 @@ type Chat struct { // // optional HasPrivateForwards bool `json:"has_private_forwards,omitempty"` + // HasRestrictedVoiceAndVideoMessages if the privacy settings of the other party + // restrict sending voice and video note messages + // in the private chat. Returned only in getChat. + // + // optional + HasRestrictedVoiceAndVideoMessages bool `json:"has_restricted_voice_and_video_messages,omitempty"` + // JoinToSendMessages is true, if users need to join the supergroup + // before they can send messages. + // Returned only in getChat + // + // optional + JoinToSendMessages bool `json:"join_to_send_messages,omitempty"` + // JoinByRequest is true, if all users directly joining the supergroup + // need to be approved by supergroup administrators. + // Returned only in getChat. + // + // optional + JoinByRequest bool `json:"join_by_request,omitempty"` // Description for groups, supergroups and channel chats // // optional @@ -293,22 +445,49 @@ type Chat struct { // // optional Permissions *ChatPermissions `json:"permissions,omitempty"` + // True, if paid media messages can be sent or forwarded to the channel chat. + // The field is available only for channel chats. + // + // optional + CanSendPaidMedia bool `json:"can_send_paid_media,omitempty"` // SlowModeDelay is for supergroups, the minimum allowed delay between // consecutive messages sent by each unprivileged user. Returned only in // getChat. // // optional SlowModeDelay int `json:"slow_mode_delay,omitempty"` + // UnrestrictBoostCount is for supergroups, the minimum number of boosts that + // a non-administrator user needs to add in order to + // ignore slow mode and chat permissions. Returned only in getChat. + // + // optional + UnrestrictBoostCount int `json:"unrestrict_boost_count,omitempty"` // MessageAutoDeleteTime is the time after which all messages sent to the // chat will be automatically deleted; in seconds. Returned only in getChat. // // optional MessageAutoDeleteTime int `json:"message_auto_delete_time,omitempty"` + // HasAggressiveAntiSpamEnabled is true if aggressive anti-spam checks are enabled + // in the supergroup. The field is only available to chat administrators. + // Returned only in getChat. + // + // optional + HasAggressiveAntiSpamEnabled bool `json:"has_aggressive_anti_spam_enabled,omitempty"` + // HasHiddenMembers is true if non-administrators can only get + // the list of bots and administrators in the chat. + // + // optional + HasHiddenMembers bool `json:"has_hidden_members,omitempty"` // HasProtectedContent is true if messages from the chat can't be forwarded // to other chats. Returned only in getChat. // // optional HasProtectedContent bool `json:"has_protected_content,omitempty"` + // HasVisibleHistory is True, if new chat members will have access to old messages; + // available only to chat administrators. Returned only in getChat. + // + // optional + HasVisibleHistory bool `json:"has_visible_history,omitempty"` // StickerSetName is for supergroups, name of group sticker set.Returned // only in getChat. // @@ -319,6 +498,12 @@ type Chat struct { // // optional CanSetStickerSet bool `json:"can_set_sticker_set,omitempty"` + // CustomEmojiStickerSetName is for supergroups, the name of the group's + // custom emoji sticker set. Custom emoji from this set can be used by all + // users and bots in the group. Returned only in getChat. + // + // optional + CustomEmojiStickerSetName string `json:"custom_emoji_sticker_set_name,omitempty"` // LinkedChatID is a unique identifier for the linked chat, i.e. the // discussion group identifier for a channel and vice versa; for supergroups // and channel chats. @@ -357,10 +542,25 @@ func (c Chat) ChatConfig() ChatConfig { return ChatConfig{ChatID: c.ID} } +// InaccessibleMessage describes a message that was deleted or is otherwise inaccessible to the bot. +type InaccessibleMessage struct { + // Chat the message belonged to + Chat Chat `json:"chat"` + // MessageID is unique message identifier inside the chat + MessageID int `json:"message_id"` + // Date is always 0. The field can be used to differentiate regular and inaccessible messages. + Date int `json:"date"` +} + // Message represents a message. type Message struct { // MessageID is a unique message identifier inside this chat MessageID int `json:"message_id"` + // Unique identifier of a message thread to which the message belongs; + // for supergroups only + // + // optional + MessageThreadID int `json:"message_thread_id,omitempty"` // From is a sender, empty for messages sent to channels; // // optional @@ -372,38 +572,36 @@ type Message struct { // // optional SenderChat *Chat `json:"sender_chat,omitempty"` - // Date of the message was sent in Unix time - Date int `json:"date"` - // Chat is the conversation the message belongs to - Chat *Chat `json:"chat"` - // ForwardFrom for forwarded messages, sender of the original message; - // - // optional - ForwardFrom *User `json:"forward_from,omitempty"` - // ForwardFromChat for messages forwarded from channels, - // information about the original channel; + // SenderBoostCount is the number of boosts added by the user, + // if the sender of the message boosted the chat // // optional - ForwardFromChat *Chat `json:"forward_from_chat,omitempty"` - // ForwardFromMessageID for messages forwarded from channels, - // identifier of the original message in the channel; + SenderBoostCount int `json:"sender_boost_count,omitempty"` + // SenderBusinessBot is the bot that actually sent the message on behalf of + // the business account. Available only for outgoing messages sent on + // behalf of the connected business account. // // optional - ForwardFromMessageID int `json:"forward_from_message_id,omitempty"` - // ForwardSignature for messages forwarded from channels, signature of the - // post author if present + SenderBusinessBot *User `json:"sender_business_bot,omitempty"` + // Date of the message was sent in Unix time + Date int `json:"date"` + // BusinessConnectionID is an unique identifier of the business connection + // from which the message was received. If non-empty, the message belongs to + // a chat of the corresponding business account that is independent from + // any potential bot chat which might share the same identifier. // // optional - ForwardSignature string `json:"forward_signature,omitempty"` - // ForwardSenderName is the sender's name for messages forwarded from users - // who disallow adding a link to their account in forwarded messages + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Chat is the conversation the message belongs to + Chat Chat `json:"chat"` + // ForwardOrigin is information about the original message for forwarded messages // // optional - ForwardSenderName string `json:"forward_sender_name,omitempty"` - // ForwardDate for forwarded messages, date the original message was sent in Unix time; + ForwardOrigin *MessageOrigin `json:"forward_origin,omitempty"` + // IsTopicMessage true if the message is sent to a forum topic // // optional - ForwardDate int `json:"forward_date,omitempty"` + IsTopicMessage bool `json:"is_topic_message,omitempty"` // IsAutomaticForward is true if the message is a channel post that was // automatically forwarded to the connected discussion group. // @@ -415,6 +613,19 @@ type Message struct { // // optional ReplyToMessage *Message `json:"reply_to_message,omitempty"` + // ExternalReply is an information about the message that is being replied to, + // which may come from another chat or forum topic. + // + // optional + ExternalReply *ExternalReplyInfo `json:"external_reply,omitempty"` + // Quote for replies that quote part of the original message, the quoted part of the message + // + // optional + Quote *TextQuote `json:"text_quote,omitempty"` + // ReplyToStory for replies to a story, the original story + // + // ReplyToStory + ReplyToStory *Story `json:"reply_to_story"` // ViaBot through which the message was sent; // // optional @@ -427,6 +638,11 @@ type Message struct { // // optional HasProtectedContent bool `json:"has_protected_content,omitempty"` + // IsFromOffline is True, if the message was sent by an implicit action, + // for example, as an away or a greeting business message, or as a scheduled message + // + // optional + IsFromOffline bool `json:"is_from_offline,omitempty"` // MediaGroupID is the unique identifier of a media message group this message belongs to; // // optional @@ -444,6 +660,15 @@ type Message struct { // // optional Entities []MessageEntity `json:"entities,omitempty"` + // LinkPreviewOptions are options used for link preview generation for the message, + // if it is a text message and link preview options were changed + // + // Optional + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // EffectID is the unique identifier of the message effect added to the message + // + // optional + EffectID string `json:"effect_id,omitempty"` // Animation message is an animation, information about the animation. // For backward compatibility, when this field is set, the document field will also be set; // @@ -462,6 +687,10 @@ type Message struct { // // optional Document *Document `json:"document,omitempty"` + // Message contains paid media; information about the paid media + // + // optional + PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"` // Photo message is a photo, available sizes of the photo; // // optional @@ -470,6 +699,10 @@ type Message struct { // // optional Sticker *Sticker `json:"sticker,omitempty"` + // Story message is a forwarded story; + // + // optional + Story *Story `json:"story,omitempty"` // Video message is a video, information about the video; // // optional @@ -490,6 +723,14 @@ type Message struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // ShowCaptionAboveMedia is True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` + // HasSpoiler True, if the message media is covered by a spoiler animation + // + // optional + HasMediaSpoiler bool `json:"has_media_spoiler,omitempty"` // Contact message is a shared contact, information about the contact; // // optional @@ -579,9 +820,9 @@ type Message struct { // // optional MigrateFromChatID int64 `json:"migrate_from_chat_id,omitempty"` - // PinnedMessage is a specified message was pinned. - // Note that the Message object in this field will not contain further ReplyToMessage - // fields even if it is itself a reply; + // Specified message was pinned. + // Note that the Message object in this field will not contain + // further reply_to_message fields even if it itself is a reply. // // optional PinnedMessage *Message `json:"pinned_message,omitempty"` @@ -594,11 +835,28 @@ type Message struct { // // optional SuccessfulPayment *SuccessfulPayment `json:"successful_payment,omitempty"` + // Message is a service message about a refunded payment, information about the payment + // + // optional + RefundedPayment *RefundedPayment `json:"refunded_payment,omitempty"` + // UsersShared is a service message: the users were shared with the bot + // + // optional + UsersShared *UsersShared `json:"users_shared,omitempty"` + // ChatShared is a service message: a chat was shared with the bot + // + // optional + ChatShared *ChatShared `json:"chat_shared,omitempty"` // ConnectedWebsite is the domain name of the website on which the user has // logged in; // // optional ConnectedWebsite string `json:"connected_website,omitempty"` + // WriteAccessAllowed is a service message: the user allowed the bot + // added to the attachment menu to write messages + // + // optional + WriteAccessAllowed *WriteAccessAllowed `json:"write_access_allowed,omitempty"` // PassportData is a Telegram Passport data; // // optional @@ -608,6 +866,54 @@ type Message struct { // // optional ProximityAlertTriggered *ProximityAlertTriggered `json:"proximity_alert_triggered,omitempty"` + // BoostAdded is a service message: user boosted the chat + // + // optional + BoostAdded *ChatBoostAdded `json:"boost_added,omitempty"` + // Service message: chat background set + // + // optional + ChatBackgroundSet *ChatBackground `json:"chat_background_set,omitempty"` + // ForumTopicCreated is a service message: forum topic created + // + // optional + ForumTopicCreated *ForumTopicCreated `json:"forum_topic_created,omitempty"` + // ForumTopicClosed is a service message: forum topic edited + // + // optional + ForumTopicEdited *ForumTopicEdited `json:"forum_topic_edited,omitempty"` + // ForumTopicClosed is a service message: forum topic closed + // + // optional + ForumTopicClosed *ForumTopicClosed `json:"forum_topic_closed,omitempty"` + // ForumTopicReopened is a service message: forum topic reopened + // + // optional + ForumTopicReopened *ForumTopicReopened `json:"forum_topic_reopened,omitempty"` + // GeneralForumTopicHidden is a service message: the 'General' forum topic hidden + // + // optional + GeneralForumTopicHidden *GeneralForumTopicHidden `json:"general_forum_topic_hidden,omitempty"` + // GeneralForumTopicUnhidden is a service message: the 'General' forum topic unhidden + // + // optional + GeneralForumTopicUnhidden *GeneralForumTopicUnhidden `json:"general_forum_topic_unhidden,omitempty"` + // GiveawayCreated is as service message: a scheduled giveaway was created + // + // optional + GiveawayCreated *GiveawayCreated `json:"giveaway_created,omitempty"` + // Giveaway is a scheduled giveaway message + // + // optional + Giveaway *Giveaway `json:"giveaway,omitempty"` + // GiveawayWinners is a giveaway with public winners was completed + // + // optional + GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"` + // GiveawayCompleted is a service message: a giveaway without public winners was completed + // + // optional + GiveawayCompleted *GiveawayCompleted `json:"giveaway_completed,omitempty"` // VideoChatScheduled is a service message: video chat scheduled. // // optional @@ -726,10 +1032,13 @@ type MessageEntity struct { // “underline” (underlined text), // “strikethrough” (strikethrough text), // "spoiler" (spoiler message), + // “blockquote” (block quotation), + // “expandable_blockquote” (collapsed-by-default block quotation), // “code” (monowidth string), // “pre” (monowidth block), // “text_link” (for clickable text URLs), // “text_mention” (for users without usernames) + // “text_mention” (for inline custom emoji stickers) Type string `json:"type"` // Offset in UTF-16 code units to the start of the entity Offset int `json:"offset"` @@ -747,6 +1056,10 @@ type MessageEntity struct { // // optional Language string `json:"language,omitempty"` + // CustomEmojiID for “custom_emoji” only, unique identifier of the custom emoji + // + // optional + CustomEmojiID string `json:"custom_emoji_id"` } // ParseURL attempts to parse a URL contained within a MessageEntity. @@ -814,6 +1127,220 @@ func (e MessageEntity) IsTextLink() bool { return e.Type == "text_link" } +// TextQuote contains information about the quoted part of a message +// that is replied to by the given message +type TextQuote struct { + // Text of the quoted part of a message that is replied to by the given message + Text string `json:"text"` + // Entities special entities that appear in the quote. + // Currently, only bold, italic, underline, strikethrough, spoiler, + // and custom_emoji entities are kept in quotes. + // + // optional + Entities []MessageEntity `json:"entities,omitempty"` + // Position is approximate quote position in the original message + // in UTF-16 code units as specified by the sender + Position int `json:"position"` + // IsManual True, if the quote was chosen manually by the message sender. + // Otherwise, the quote was added automatically by the server. + // + // optional + IsManual bool `json:"is_manual,omitempty"` +} + +// ExternalReplyInfo contains information about a message that is being replied to, +// which may come from another chat or forum topic. +type ExternalReplyInfo struct { + // Origin of the message replied to by the given message + Origin MessageOrigin `json:"origin"` + // Chat is the conversation the message belongs to + Chat *Chat `json:"chat"` + // MessageID is a unique message identifier inside this chat + MessageID int `json:"message_id"` + // LinkPreviewOptions used for link preview generation for the original message, + // if it is a text message + // + // Optional + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // Animation message is an animation, information about the animation. + // For backward compatibility, when this field is set, the document field will also be set; + // + // optional + Animation *Animation `json:"animation,omitempty"` + // Audio message is an audio file, information about the file; + // + // optional + Audio *Audio `json:"audio,omitempty"` + // Document message is a general file, information about the file; + // + // optional + Document *Document `json:"document,omitempty"` + // Message contains paid media; information about the paid media + // + // optional + PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"` + // Photo message is a photo, available sizes of the photo; + // + // optional + Photo []PhotoSize `json:"photo,omitempty"` + // Sticker message is a sticker, information about the sticker; + // + // optional + Sticker *Sticker `json:"sticker,omitempty"` + // Story message is a forwarded story; + // + // optional + Story *Story `json:"story,omitempty"` + // Video message is a video, information about the video; + // + // optional + Video *Video `json:"video,omitempty"` + // VideoNote message is a video note, information about the video message; + // + // optional + VideoNote *VideoNote `json:"video_note,omitempty"` + // Voice message is a voice message, information about the file; + // + // optional + Voice *Voice `json:"voice,omitempty"` + // HasMediaSpoiler True, if the message media is covered by a spoiler animation + // + // optional + HasMediaSpoiler bool `json:"has_media_spoiler,omitempty"` + // Contact message is a shared contact, information about the contact; + // + // optional + Contact *Contact `json:"contact,omitempty"` + // Dice is a dice with random value; + // + // optional + Dice *Dice `json:"dice,omitempty"` + // Game message is a game, information about the game; + // + // optional + Game *Game `json:"game,omitempty"` + // Giveaway is information about the giveaway + // + // optional + Giveaway *Giveaway `json:"giveaway,omitempty"` + // GiveawayWinners a giveaway with public winners was completed + // + // optional + GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"` + // Invoice message is an invoice for a payment; + // + // optional + Invoice *Invoice `json:"invoice,omitempty"` + // Location message is a shared location, information about the location; + // + // optional + Location *Location `json:"location,omitempty"` + // Poll is a native poll, information about the poll; + // + // optional + Poll *Poll `json:"poll,omitempty"` + // Venue message is a venue, information about the venue. + // For backward compatibility, when this field is set, the location field + // will also be set; + // + // optional + Venue *Venue `json:"venue,omitempty"` +} + +// ReplyParameters describes reply parameters for the message that is being sent. +type ReplyParameters struct { + // MessageID identifier of the message that will be replied to in + // the current chat, or in the chat chat_id if it is specified + MessageID int `json:"message_id"` + // ChatID if the message to be replied to is from a different chat, + // unique identifier for the chat or username of the channel (in the format @channelusername) + // + // optional + ChatID interface{} `json:"chat_id,omitempty"` + // AllowSendingWithoutReply true if the message should be sent even + // if the specified message to be replied to is not found; + // can be used only for replies in the same chat and forum topic. + // + // optional + AllowSendingWithoutReply bool `json:"allow_sending_without_reply,omitempty"` + // Quote is a quoted part of the message to be replied to; + // 0-1024 characters after entities parsing. The quote must be + // an exact substring of the message to be replied to, + // including bold, italic, underline, strikethrough, spoiler, and custom_emoji entities. + // The message will fail to send if the quote isn't found in the original message. + // + // optional + Quote string `json:"quote,omitempty"` + // QuoteParseMode mode for parsing entities in the quote. + // + // optional + QuoteParseMode string `json:"quote_parse_mode,omitempty"` + // QuoteEntities a JSON-serialized list of special entities that appear in the quote. + // It can be specified instead of quote_parse_mode. + // + // optional + QuoteEntities []MessageEntity `json:"quote_entities,omitempty"` + // QuotePosition is a position of the quote in the original message in UTF-16 code units + // + // optional + QuotePosition int `json:"quote_position,omitempty"` +} + +const ( + MessageOriginUser = "user" + MessageOriginHiddenUser = "hidden_user" + MessageOriginChat = "chat" + MessageOriginChannel = "channel" +) + +// MessageOrigin describes the origin of a message. It can be one of: "user", "hidden_user", "origin_chat", "origin_channel" +type MessageOrigin struct { + // Type of the message origin. + Type string `json:"type"` + // Date the message was sent originally in Unix time + Date int64 `json:"date"` + // SenderUser "user" only. + // Is a user that sent the message originally + SenderUser *User `json:"sender_user,omitempty"` + // SenderUserName "hidden_user" only. + // Name of the user that sent the message originally + SenderUserName string `json:"sender_user_name,omitempty"` + // SenderChat "chat" only. + // Chat that sent the message originally + SenderChat *Chat `json:"sender_chat,omitempty"` + // Chat "channel" only. + // Channel chat to which the message was originally sent + Chat *Chat `json:"chat,omitempty"` + // AuthorSignature "chat" and "channel". + // For "chat": For messages originally sent by an anonymous chat administrator, + // original message author signature. + // For "channel": Signature of the original post author + // + // Optional + AuthorSignature string `json:"author_signature,omitempty"` + // MessageID "channel" only. + // Unique message identifier inside the chat + // + // Optional + MessageID int `json:"message_id,omitempty"` +} + +func (m MessageOrigin) IsUser() bool { + return m.Type == MessageOriginUser +} + +func (m MessageOrigin) IsHiddenUser() bool { + return m.Type == MessageOriginHiddenUser +} + +func (m MessageOrigin) IsChat() bool { + return m.Type == MessageOriginChat +} + +func (m MessageOrigin) IsChannel() bool { + return m.Type == MessageOriginChannel +} + // PhotoSize represents one size of a photo or a file / sticker thumbnail. type PhotoSize struct { // FileID identifier for this file, which can be used to download or reuse @@ -851,7 +1378,7 @@ type Animation struct { // Thumbnail animation thumbnail as defined by sender // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileName original animation filename as defined by sender // // optional @@ -863,7 +1390,7 @@ type Animation struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` } // Audio represents an audio file to be treated as music by the Telegram clients. @@ -896,11 +1423,11 @@ type Audio struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` // Thumbnail is the album cover to which the music file belongs // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` } // Document represents a general file. @@ -915,7 +1442,7 @@ type Document struct { // Thumbnail document thumbnail as defined by sender // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileName original filename as defined by sender // // optional @@ -927,7 +1454,15 @@ type Document struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` +} + +// Story represents a message about a forwarded story in the chat. +type Story struct { + // Chat that posted the story + Chat Chat `json:"chat"` + // ID is an unique identifier for the story in the chat + ID int `json:"id"` } // Video represents a video file. @@ -948,7 +1483,7 @@ type Video struct { // Thumbnail video thumbnail // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileName is the original filename as defined by sender // // optional @@ -960,7 +1495,7 @@ type Video struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` } // VideoNote object represents a video message. @@ -978,7 +1513,7 @@ type VideoNote struct { // Thumbnail video thumbnail // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileSize file size // // optional @@ -1002,7 +1537,48 @@ type Voice struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` +} + +// PaidMediaInfo describes the paid media added to a message. +type PaidMediaInfo struct { + // The number of Telegram Stars that must be paid to buy access to the media + StarCount int64 `json:"star_count"` + // Information about the paid media + PaidMedia []PaidMedia `json:"paid_media"` +} + +// This object describes paid media. Currently, it can be one of +// - PaidMediaPreview +// - PaidMediaPhoto +// - PaidMediaVideo +type PaidMedia struct { + // Type of the paid media, should be one of: + // - "photo" + // - "video" + // - "preview" + Type string `json:"type"` + // PaidMediaPreview only. + // Media width as defined by the sender. + // + // optional + Width int64 `json:"width,omitempty"` + // PaidMediaPreview only. + // Media height as defined by the sender + // + // optional + Height int64 `json:"height,omitempty"` + // PaidMediaPreview only. + // Duration of the media in seconds as defined by the sender + // + // optional + Duration int64 `json:"duration,omitempty"` + // PaidMediaPhoto only. + // The photo + Photo []PhotoSize `json:"photo,omitempty"` + // PaidMediaVideo only. + // The video + Video *Video `json:"video,omitempty"` } // Contact represents a phone contact. @@ -1039,16 +1615,45 @@ type Dice struct { type PollOption struct { // Text is the option text, 1-100 characters Text string `json:"text"` + // Special entities that appear in the option text. + // Currently, only custom emoji entities are allowed in poll option texts + // + // optional + TextEntities []MessageEntity `json:"text_entities,omitempty"` // VoterCount is the number of users that voted for this option VoterCount int `json:"voter_count"` } +// InputPollOption contains information about one answer option in a poll to send. +type InputPollOption struct { + // Option text, 1-100 characters + Text string `json:"text"` + // Mode for parsing entities in the text. See formatting options for more details. + // Currently, only custom emoji entities are allowed + // + // optional + TextParseMode string `json:"text_parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the poll option text. + // It can be specified instead of text_parse_mode + // + // optional + TextEntities []MessageEntity `json:"text_entities,omitempty"` +} + // PollAnswer represents an answer of a user in a non-anonymous poll. type PollAnswer struct { // PollID is the unique poll identifier PollID string `json:"poll_id"` - // User who changed the answer to the poll - User User `json:"user"` + // Chat that changed the answer to the poll, if the voter is anonymous. + // + // Optional + VoterChat *Chat `json:"voter_chat,omitempty"` + // User who changed the answer to the poll, if the voter isn't anonymous + // For backward compatibility, the field user in such objects + // will contain the user 136817688 (@Channel_Bot). + // + // Optional + User *User `json:"user,omitempty"` // OptionIDs is the 0-based identifiers of poll options chosen by the user. // May be empty if user retracted vote. OptionIDs []int `json:"option_ids"` @@ -1060,6 +1665,11 @@ type Poll struct { ID string `json:"id"` // Question is the poll question, 1-255 characters Question string `json:"question"` + // Special entities that appear in the question. + // Currently, only custom emoji entities are allowed in poll questions + // + // optional + QuestionEntities []MessageEntity `json:"question_entities,omitempty"` // Options is the list of poll options Options []PollOption `json:"options"` // TotalVoterCount is the total numbers of users who voted in the poll @@ -1113,6 +1723,7 @@ type Location struct { HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"` // LivePeriod is time relative to the message sending date, during which the // location can be updated, in seconds. For active live locations only. + // Use 0x7FFFFFFF (2147483647 - max positive Int) to edit indefinitely // // optional LivePeriod int `json:"live_period,omitempty"` @@ -1181,6 +1792,217 @@ type MessageAutoDeleteTimerChanged struct { MessageAutoDeleteTime int `json:"message_auto_delete_time"` } +// ChatBoostAdded represents a service message about a user boosting a chat. +type ChatBoostAdded struct { + // BoostCount is a number of boosts added by the user + BoostCount int `json:"boost_count"` +} + +// BackgroundFill describes the way a background is filled based on the selected colors. +// Currently, it can be one of: +// - BackgroundFillSolid +// - BackgroundFillGradient +// - BackgroundFillFreeformGradient +type BackgroundFill struct { + // Type of the background fill, can be: + // - solid + // - gradient + // - freeform_gradient + Type string `json:"type"` + // BackgroundFillSolid only. + // The color of the background fill in the RGB24 format + Color int `json:"color"` + // BackgroundFillGradient only. + // Top color of the gradient in the RGB24 format + TopColor int `json:"top_color"` + // BackgroundFillGradient only. + // Bottom color of the gradient in the RGB24 format + BottomColor int `json:"bottom_color"` + // BackgroundFillGradient only. + // Clockwise rotation angle of the background fill in degrees; 0-359 + RotationAngle int `json:"rotation_angle"` + // BackgroundFillFreeformGradient only. + // A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format + Colors []int `json:"colors"` +} + +// BackgroundType describes the type of a background. Currently, it can be one of: +// - BackgroundTypeFill +// - BackgroundTypeWallpaper +// - BackgroundTypePattern +// - BackgroundTypeChatTheme +type BackgroundType struct { + // Type of the background. + // Currently, it can be one of: + // - fill + // - wallpaper + // - pattern + // - chat_theme + Type string `json:"type"` + // BackgroundTypeFill and BackgroundTypePattern only. + // The background fill or fill that is combined with the pattern + Fill BackgroundFill `json:"fill"` + // BackgroundTypeFill and BackgroundTypeWallpaper only. + // Dimming of the background in dark themes, as a percentage; 0-100 + DarkThemeDimming int `json:"dark_theme_dimming"` + // BackgroundTypeWallpaper and BackgroundTypePattern only. + // Document with the wallpaper / pattern + Document Document `json:"document"` + // BackgroundTypeWallpaper only. + // True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12 + // + // optional + IsBlurred bool `json:"is_blurred,omitempty"` + // BackgroundTypeWallpaper and BackgroundTypePattern only. + // True, if the background moves slightly when the device is tilted + // + // optional + IsMoving bool `json:"is_moving,omitempty"` + // BackgroundTypePattern only. + // Intensity of the pattern when it is shown above the filled background; 0-100 + Intensity int `json:"intensity"` + // BackgroundTypePattern only. + // True, if the background fill must be applied only to the pattern itself. + // All other pixels are black in this case. For dark themes only + // + // optional + IsInverted bool `json:"is_inverted,omitempty"` + // BackgroundTypeChatTheme only. + // Name of the chat theme, which is usually an emoji + ThemeName string `json:"theme_name"` +} + +// ChatBackground represents a chat background. +type ChatBackground struct { + // Type of the background + Type BackgroundType `json:"type"` +} + +// ForumTopicCreated represents a service message about a new forum topic +// created in the chat. +type ForumTopicCreated struct { + // Name is the name of topic + Name string `json:"name"` + // IconColor is the color of the topic icon in RGB format + IconColor int `json:"icon_color"` + // IconCustomEmojiID is the unique identifier of the custom emoji + // shown as the topic icon + // + // optional + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` +} + +// ForumTopicClosed represents a service message about a forum topic +// closed in the chat. Currently holds no information. +type ForumTopicClosed struct { +} + +// ForumTopicEdited object represents a service message about an edited forum topic. +type ForumTopicEdited struct { + // Name is the new name of the topic, if it was edited + // + // optional + Name string `json:"name,omitempty"` + // IconCustomEmojiID is the new identifier of the custom emoji + // shown as the topic icon, if it was edited; + // an empty string if the icon was removed + // + // optional + IconCustomEmojiID *string `json:"icon_custom_emoji_id,omitempty"` +} + +// ForumTopicReopened represents a service message about a forum topic +// reopened in the chat. Currently holds no information. +type ForumTopicReopened struct { +} + +// GeneralForumTopicHidden represents a service message about General forum topic +// hidden in the chat. Currently holds no information. +type GeneralForumTopicHidden struct { +} + +// GeneralForumTopicUnhidden represents a service message about General forum topic +// unhidden in the chat. Currently holds no information. +type GeneralForumTopicUnhidden struct { +} + +// SharedUser contains information about a user that was +// shared with the bot using a KeyboardButtonRequestUsers button. +type SharedUser struct { + // UserID is the identifier of the shared user. + UserID int64 `json:"user_id"` + // FirstName of the user, if the name was requested by the bot. + // + // optional + FirstName *string `json:"first_name,omitempty"` + // LastName of the user, if the name was requested by the bot. + // + // optional + LastName *string `json:"last_name,omitempty"` + // Username of the user, if the username was requested by the bot. + // + // optional + UserName *string `json:"username,omitempty"` + // Photo is array of available sizes of the chat photo, + // if the photo was requested by the bot + // + // optional + Photo []PhotoSize `json:"photo,omitempty"` +} + +// UsersShared object contains information about the user whose identifier +// was shared with the bot using a KeyboardButtonRequestUser button. +type UsersShared struct { + // RequestID is an indentifier of the request. + RequestID int `json:"request_id"` + // Users shared with the bot. + Users []SharedUser `json:"users"` +} + +// ChatShared contains information about the chat whose identifier +// was shared with the bot using a KeyboardButtonRequestChat button. +type ChatShared struct { + // RequestID is an indentifier of the request. + RequestID int `json:"request_id"` + // ChatID is an identifier of the shared chat. + ChatID int64 `json:"chat_id"` + // Title of the chat, if the title was requested by the bot. + // + // optional + Title *string `json:"title,omitempty"` + // UserName of the chat, if the username was requested by + // the bot and available. + // + // optional + UserName *string `json:"username,omitempty"` + // Photo is array of available sizes of the chat photo, + // if the photo was requested by the bot + // + // optional + Photo []PhotoSize `json:"photo,omitempty"` +} + +// WriteAccessAllowed represents a service message about a user allowing a bot +// to write messages after adding the bot to the attachment menu or launching +// a Web App from a link. +type WriteAccessAllowed struct { + // FromRequest is true, if the access was granted after + // the user accepted an explicit request from a Web App + // sent by the method requestWriteAccess. + // + // Optional + FromRequest bool `json:"from_request,omitempty"` + // Name of the Web App which was launched from a link + // + // Optional + WebAppName string `json:"web_app_name,omitempty"` + // FromAttachmentMenu is true, if the access was granted when + // the bot was added to the attachment or side menu + // + // Optional + FromAttachmentMenu bool `json:"from_attachment_menu,omitempty"` +} + // VideoChatScheduled represents a service message about a voice chat scheduled // in the chat. type VideoChatScheduled struct { @@ -1214,6 +2036,156 @@ type VideoChatParticipantsInvited struct { Users []User `json:"users,omitempty"` } +// This object represents a service message about the creation of a scheduled giveaway. Currently holds no information. +type GiveawayCreated struct { + // PrizeStarCount is the number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` +} + +// Giveaway represents a message about a scheduled giveaway. +type Giveaway struct { + // Chats is the list of chats which the user must join to participate in the giveaway + Chats []Chat `json:"chats"` + // WinnersSelectionDate is point in time (Unix timestamp) when + // winners of the giveaway will be selected + WinnersSelectionDate int64 `json:"winners_selection_date"` + // WinnerCount is the number of users which are supposed + // to be selected as winners of the giveaway + WinnerCount int `json:"winner_count"` + // OnlyNewMembers True, if only users who join the chats after + // the giveaway started should be eligible to win + // + // optional + OnlyNewMembers bool `json:"only_new_members,omitempty"` + // HasPublicWinners True, if the list of giveaway winners will be visible to everyone + // + // optional + HasPublicWinners bool `json:"has_public_winners,omitempty"` + // PrizeDescription is description of additional giveaway prize + // + // optional + PrizeDescription string `json:"prize_description,omitempty"` + // CountryCodes is a list of two-letter ISO 3166-1 alpha-2 country codes + // indicating the countries from which eligible users for the giveaway must come. + // If empty, then all users can participate in the giveaway. + // + // optional + CountryCodes []string `json:"country_codes,omitempty"` + // PrizeStarCount is the number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` + // PremiumSubscriptionMonthCount the number of months the Telegram Premium + // subscription won from the giveaway will be active for + // + // optional + PremiumSubscriptionMonthCount int `json:"premium_subscription_month_count,omitempty"` +} + +// Giveaway represents a message about a scheduled giveaway. +type GiveawayWinners struct { + // Chat that created the giveaway + Chat Chat `json:"chat"` + // GiveawayMessageID is the identifier of the messsage with the giveaway in the chat + GiveawayMessageID int `json:"giveaway_message_id"` + // WinnersSelectionDate is point in time (Unix timestamp) when + // winners of the giveaway will be selected + WinnersSelectionDate int64 `json:"winners_selection_date"` + // WinnerCount is the number of users which are supposed + // to be selected as winners of the giveaway + WinnerCount int `json:"winner_count"` + // Winners is a list of up to 100 winners of the giveaway + Winners []User `json:"winners"` + // AdditionalChatCount is the number of other chats + // the user had to join in order to be eligible for the giveaway + // + // optional + AdditionalChatCount int `json:"additional_chat_count,omitempty"` + // PrizeStarCount is the number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` + // PremiumSubscriptionMonthCount the number of months the Telegram Premium + // subscription won from the giveaway will be active for + // + // optional + PremiumSubscriptionMonthCount int `json:"premium_subscription_month_count,omitempty"` + // UnclaimedPrizeCount is the number of undistributed prizes + // + // optional + UnclaimedPrizeCount int `json:"unclaimed_prize_count,omitempty"` + // OnlyNewMembers True, if only users who join the chats after + // the giveaway started should be eligible to win + // + // optional + OnlyNewMembers bool `json:"only_new_members,omitempty"` + // WasRefunded True, if the giveaway was canceled because the payment for it was refunded + // + // optional + WasRefunded bool `json:"was_refunded,omitempty"` + // PrizeDescription is description of additional giveaway prize + // + // optional + PrizeDescription string `json:"prize_description,omitempty"` +} + +// This object represents a service message about the completion of a giveaway without public winners. +type GiveawayCompleted struct { + // Number of winners in the giveaway + WinnerCount int `json:"winner_count"` + // Number of undistributed prizes + // + // optional + UnclaimedPrizeCount int `json:"unclaimed_prize_count,omitempty"` + // Message with the giveaway that was completed, if it wasn't deleted + // + // optional + GiveawayMessage *Message `json:"giveaway_message,omitempty"` + // IsStarGiveaway True, if the giveaway is a Telegram Star giveaway. + // Otherwise, currently, the giveaway is a Telegram Premium giveaway. + // + // optional + IsStarGiveaway bool `json:"is_star_giveaway,omitempty"` +} + +// LinkPreviewOptions describes the options used for link preview generation. +type LinkPreviewOptions struct { + // IsDisabled True, if the link preview is disabled + // + // optional + IsDisabled bool `json:"is_disabled,omitempty"` + // URL to use for the link preview. If empty, + // then the first URL found in the message text will be used + // + // optional + URL string `json:"url,omitempty"` + // PreferSmallMedia True, if the media in the link preview is suppposed + // to be shrunk; ignored if the URL isn't explicitly specified + // or media size change isn't supported for the preview + // + // optional + PreferSmallMedia bool `json:"prefer_small_media,omitempty"` + // PreferLargeMedia True, if the media in the link preview is suppposed + // to be enlarged; ignored if the URL isn't explicitly specified + // or media size change isn't supported for the preview + // + // optional + PreferLargeMedia bool `json:"prefer_large_media,omitempty"` + // ShowAboveText True, if the link preview must be shown above the message text; + // otherwise, the link preview will be shown below the message text + // + // optional + ShowAboveText bool `json:"show_above_text,omitempty"` +} + // UserProfilePhotos contains a set of user profile photos. type UserProfilePhotos struct { // TotalCount total number of profile pictures the target user has @@ -1234,7 +2206,7 @@ type File struct { // FileSize file size, if known // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` // FilePath file path // // optional @@ -1259,6 +2231,13 @@ type WebAppInfo struct { type ReplyKeyboardMarkup struct { // Keyboard is an array of button rows, each represented by an Array of KeyboardButton objects Keyboard [][]KeyboardButton `json:"keyboard"` + // IsPersistent requests clients to always show the keyboard + // when the regular keyboard is hidden. + // Defaults to false, in which case the custom keyboard can be hidden + // and opened with a keyboard icon. + // + // optional + IsPersistent bool `json:"is_persistent"` // ResizeKeyboard requests clients to resize the keyboard vertically for optimal fit // (e.g., make the keyboard smaller if there are just two rows of buttons). // Defaults to false, in which case the custom keyboard @@ -1300,6 +2279,20 @@ type KeyboardButton struct { // Text of the button. If none of the optional fields are used, // it will be sent as a message when the button is pressed. Text string `json:"text"` + // RequestUsers if specified, pressing the button will open + // a list of suitable users. Tapping on any user will send + // their identifier to the bot in a "user_shared" service message. + // Available in private chats only. + // + // optional + RequestUsers *KeyboardButtonRequestUsers `json:"request_users,omitempty"` + // RequestChat if specified, pressing the button will open + // a list of suitable chats. Tapping on a chat will send + // its identifier to the bot in a "chat_shared" service message. + // Available in private chats only. + // + // optional + RequestChat *KeyboardButtonRequestChat `json:"request_chat,omitempty"` // RequestContact if True, the user's phone number will be sent // as a contact when the button is pressed. // Available in private chats only. @@ -1325,6 +2318,101 @@ type KeyboardButton struct { WebApp *WebAppInfo `json:"web_app,omitempty"` } +// KeyboardButtonRequestUsers defines the criteria used to request +// a suitable user. The identifier of the selected user will be shared +// with the bot when the corresponding button is pressed. +type KeyboardButtonRequestUsers struct { + // RequestID is a signed 32-bit identifier of the request. + RequestID int `json:"request_id"` + // UserIsBot pass True to request a bot, + // pass False to request a regular user. + // If not specified, no additional restrictions are applied. + // + // optional + UserIsBot *bool `json:"user_is_bot,omitempty"` + // UserIsPremium pass True to request a premium user, + // pass False to request a non-premium user. + // If not specified, no additional restrictions are applied. + // + // optional + UserIsPremium *bool `json:"user_is_premium,omitempty"` + // MaxQuantity is the maximum number of users to be selected. + // 1-10. Defaults to 1 + // + // optional + MaxQuantity int `json:"max_quantity,omitempty"` + // RequestName pass True to request the users' first and last names + // + // optional + RequestName bool `json:"request_name,omitempty"` + // RequestUsername pass True to request the users' usernames + // + // optional + RequestUsername bool `json:"request_username,omitempty"` + // RequestPhoto pass True to request the users' photos + // + // optional + RequestPhoto bool `json:"request_photo,omitempty"` +} + +// KeyboardButtonRequestChat defines the criteria used to request +// a suitable chat. The identifier of the selected chat will be shared +// with the bot when the corresponding button is pressed. +type KeyboardButtonRequestChat struct { + // RequestID is a signed 32-bit identifier of the request. + RequestID int `json:"request_id"` + // ChatIsChannel pass True to request a channel chat, + // pass False to request a group or a supergroup chat. + ChatIsChannel bool `json:"chat_is_channel"` + // ChatIsForum pass True to request a forum supergroup, + // pass False to request a non-forum chat. + // If not specified, no additional restrictions are applied. + // + // optional + ChatIsForum bool `json:"chat_is_forum,omitempty"` + // ChatHasUsername pass True to request a supergroup or a channel with a username, + // pass False to request a chat without a username. + // If not specified, no additional restrictions are applied. + // + // optional + ChatHasUsername bool `json:"chat_has_username,omitempty"` + // ChatIsCreated pass True to request a chat owned by the user. + // Otherwise, no additional restrictions are applied. + // + // optional + ChatIsCreated bool `json:"chat_is_created,omitempty"` + // UserAdministratorRights is a JSON-serialized object listing + // the required administrator rights of the user in the chat. + // If not specified, no additional restrictions are applied. + // + // optional + UserAdministratorRights *ChatAdministratorRights `json:"user_administrator_rights,omitempty"` + // BotAdministratorRights is a JSON-serialized object listing + // the required administrator rights of the bot in the chat. + // The rights must be a subset of user_administrator_rights. + // If not specified, no additional restrictions are applied. + // + // optional + BotAdministratorRights *ChatAdministratorRights `json:"bot_administrator_rights,omitempty"` + // BotIsMember pass True to request a chat with the bot as a member. + // Otherwise, no additional restrictions are applied. + // + // optional + BotIsMember bool `json:"bot_is_member,omitempty"` + // RequestTitle pass True to request the chat's title + // + // optional + RequestTitle bool `json:"request_title,omitempty"` + // RequestUsername pass True to request the chat's username + // + // optional + RequestUsername bool `json:"request_username,omitempty"` + // RequestPhoto pass True to request the chat's photo + // + // optional + RequestPhoto bool `json:"request_photo,omitempty"` +} + // KeyboardButtonPollType represents type of poll, which is allowed to // be created and sent when the corresponding button is pressed. type KeyboardButtonPollType struct { @@ -1377,6 +2465,8 @@ type InlineKeyboardButton struct { // Text label text on the button Text string `json:"text"` // URL HTTP or tg:// url to be opened when button is pressed. + // Links tg://user?id= can be used to mention a user by their identifier without using a username, + // if this is allowed by their privacy settings. // // optional URL *string `json:"url,omitempty"` @@ -1392,6 +2482,7 @@ type InlineKeyboardButton struct { // WebApp is the Description of the Web App that will be launched when the user presses the button. // The Web App will be able to send an arbitrary message on behalf of the user using the method // answerWebAppQuery. Available only in private chats between a user and the bot. + // Not supported for messages sent on behalf of a Telegram Business account. // // optional WebApp *WebAppInfo `json:"web_app,omitempty"` @@ -1404,6 +2495,7 @@ type InlineKeyboardButton struct { // Especially useful when combined with switch_pm… actions – in this case // the user will be automatically returned to the chat they switched from, // skipping the chat selection screen. + // Not supported for messages sent on behalf of a Telegram Business account. // // optional SwitchInlineQuery *string `json:"switch_inline_query,omitempty"` @@ -1413,14 +2505,23 @@ type InlineKeyboardButton struct { // // This offers a quick way for the user to open your bot in inline mode // in the same chat – good for selecting something from multiple options. + // Not supported for messages sent on behalf of a Telegram Business account. // // optional SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` + //SwitchInlineQueryChosenChat If set, pressing the button will prompt the user to + //select one of their chats of the specified type, open that chat and insert the bot's + //username and the specified inline query in the input field. + // Not supported for messages sent on behalf of a Telegram Business account. + // + //optional + SwitchInlineQueryChosenChat *SwitchInlineQueryChosenChat `json:"switch_inline_query_chosen_chat,omitempty"` // CallbackGame description of the game that will be launched when the user presses the button. // // optional CallbackGame *CallbackGame `json:"callback_game,omitempty"` // Pay specify True, to send a Pay button. + // Substrings “⭐” and “XTR” in the buttons's text will be replaced with a Telegram Star icon. // // NOTE: This type of button must always be the first button in the first row. // @@ -1473,9 +2574,7 @@ type CallbackQuery struct { ID string `json:"id"` // From sender From *User `json:"from"` - // Message with the callback button that originated the query. - // Note that message content and message date will not be available if the - // message is too old. + // Message sent by the bot with the callback button that originated the query // // optional Message *Message `json:"message,omitempty"` @@ -1499,6 +2598,21 @@ type CallbackQuery struct { GameShortName string `json:"game_short_name,omitempty"` } +// IsInaccessibleMessage method that shows whether message is inaccessible +func (c CallbackQuery) IsInaccessibleMessage() bool { + return c.Message != nil && c.Message.Date == 0 +} + +func (c CallbackQuery) GetInaccessibleMessage() InaccessibleMessage { + if c.Message == nil { + return InaccessibleMessage{} + } + return InaccessibleMessage{ + Chat: c.Message.Chat, + MessageID: c.Message.MessageID, + } +} + // ForceReply when receiving a message with this object, Telegram clients will // display a reply interface to the user (act as if the user has selected the // bot's message and tapped 'Reply'). This can be extremely useful if you want @@ -1577,6 +2691,17 @@ type ChatInviteLink struct { // // optional PendingJoinRequestCount int `json:"pending_join_request_count,omitempty"` + // SubscriptionPeriod is the number of seconds the subscription + // will be active for before the next payment + // + // optional + SubscriptionPeriod int `json:"subscription_period,omitempty"` + // SubscriptionPrice is the amount of Telegram Stars a user + // must pay initially and after each subsequent subscription + // period to be a member of the chat using the link + // + // optional + SubscriptionPrice int `json:"subscription_price,omitempty"` } type ChatAdministratorRights struct { @@ -1591,6 +2716,10 @@ type ChatAdministratorRights struct { CanPostMessages bool `json:"can_post_messages"` CanEditMessages bool `json:"can_edit_messages"` CanPinMessages bool `json:"can_pin_messages"` + CanPostStories bool `json:"can_post_stories"` + CanEditStories bool `json:"can_edit_stories"` + CanDeleteStories bool `json:"can_delete_stories"` + CanManageTopics bool `json:"can_manage_topics"` } // ChatMember contains information about one member of a chat. @@ -1615,10 +2744,14 @@ type ChatMember struct { // // optional IsAnonymous bool `json:"is_anonymous,omitempty"` - // UntilDate restricted and kicked only. + // UntilDate for restricted and kicked. // Date when restrictions will be lifted for this user; // unix time. // + // Until date for member. + // Date when the user's subscription will expire; + // Unix time + // // optional UntilDate int64 `json:"until_date,omitempty"` // CanBeEdited administrators only. @@ -1672,17 +2805,38 @@ type ChatMember struct { // True, if the user is allowed to change the chat title, photo and other settings. // // optional - CanChangeInfo bool `json:"can_change_info,omitempty"` - // CanInviteUsers administrators and restricted only. - // True, if the user is allowed to invite new users to the chat. + CanChangeInfo bool `json:"can_change_info,omitempty"` + // CanInviteUsers administrators and restricted only. + // True, if the user is allowed to invite new users to the chat. + // + // optional + CanInviteUsers bool `json:"can_invite_users,omitempty"` + // CanPinMessages administrators and restricted only. + // True, if the user is allowed to pin messages; groups and supergroups only + // + // optional + CanPinMessages bool `json:"can_pin_messages,omitempty"` + // CanPostStories administrators only. + // True, if the administrator can post stories in the channel; channels only + // + // optional + CanPostStories bool `json:"can_post_stories,omitempty"` + // CanEditStories administrators only. + // True, if the administrator can edit stories posted by other users; channels only + // + // optional + CanEditStories bool `json:"can_edit_stories,omitempty"` + // CanDeleteStories administrators only. + // True, if the administrator can delete stories posted by other users; channels only // // optional - CanInviteUsers bool `json:"can_invite_users,omitempty"` - // CanPinMessages administrators and restricted only. - // True, if the user is allowed to pin messages; groups and supergroups only + CanDeleteStories bool `json:"can_delete_stories,omitempty"` + // CanManageTopics administrators and restricted only. + // True, if the user is allowed to create, rename, + // close, and reopen forum topics; supergroups only // // optional - CanPinMessages bool `json:"can_pin_messages,omitempty"` + CanManageTopics bool `json:"can_manage_topics,omitempty"` // IsMember is true, if the user is a member of the chat at the moment of // the request IsMember bool `json:"is_member"` @@ -1690,11 +2844,36 @@ type ChatMember struct { // // optional CanSendMessages bool `json:"can_send_messages,omitempty"` - // CanSendMediaMessages restricted only. - // True, if the user is allowed to send text messages, contacts, locations and venues + // CanSendAudios restricted only. + // True, if the user is allowed to send audios + // + // optional + CanSendAudios bool `json:"can_send_audios,omitempty"` + // CanSendDocuments restricted only. + // True, if the user is allowed to send documents + // + // optional + CanSendDocuments bool `json:"can_send_documents,omitempty"` + // CanSendPhotos is restricted only. + // True, if the user is allowed to send photos + // + // optional + CanSendPhotos bool `json:"can_send_photos,omitempty"` + // CanSendVideos restricted only. + // True, if the user is allowed to send videos + // + // optional + CanSendVideos bool `json:"can_send_videos,omitempty"` + // CanSendVideoNotes restricted only. + // True, if the user is allowed to send video notes + // + // optional + CanSendVideoNotes bool `json:"can_send_video_notes,omitempty"` + // CanSendVoiceNotes restricted only. + // True, if the user is allowed to send voice notes // // optional - CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` + CanSendVoiceNotes bool `json:"can_send_voice_notes,omitempty"` // CanSendPolls restricted only. // True, if the user is allowed to send polls // @@ -1725,6 +2904,27 @@ func (chat ChatMember) HasLeft() bool { return chat.Status == "left" } // WasKicked returns if the ChatMember was kicked from the chat. func (chat ChatMember) WasKicked() bool { return chat.Status == "kicked" } +// SetCanSendMediaMessages is a method to replace field "can_send_media_messages". +// It sets CanSendAudio, CanSendDocuments, CanSendPhotos, CanSendVideos, +// CanSendVideoNotes, CanSendVoiceNotes to passed value. +func (chat *ChatMember) SetCanSendMediaMessages(b bool) { + chat.CanSendAudios = b + chat.CanSendDocuments = b + chat.CanSendPhotos = b + chat.CanSendVideos = b + chat.CanSendVideoNotes = b + chat.CanSendVoiceNotes = b +} + +// CanSendMediaMessages method to replace field "can_send_media_messages". +// It returns true if CanSendAudio and CanSendDocuments and CanSendPhotos and CanSendVideos and +// CanSendVideoNotes and CanSendVoiceNotes are true. +func (chat *ChatMember) CanSendMediaMessages() bool { + return chat.CanSendAudios && chat.CanSendDocuments && + chat.CanSendPhotos && chat.CanSendVideos && + chat.CanSendVideoNotes && chat.CanSendVoiceNotes +} + // ChatMemberUpdated represents changes in the status of a chat member. type ChatMemberUpdated struct { // Chat the user belongs to. @@ -1742,6 +2942,17 @@ type ChatMemberUpdated struct { // // optional InviteLink *ChatInviteLink `json:"invite_link,omitempty"` + // ViaJoinRequest is true, if the user joined the chat + // after sending a direct join request + // and being approved by an administrator + // + // optional + ViaJoinRequest bool `json:"via_join_request,omitempty"` + // ViaChatFolderInviteLink is True, if the user joined the chat + // via a chat folder invite link + // + // optional + ViaChatFolderInviteLink bool `json:"via_chat_folder_invite_link,omitempty"` } // ChatJoinRequest represents a join request sent to a chat. @@ -1750,6 +2961,8 @@ type ChatJoinRequest struct { Chat Chat `json:"chat"` // User that sent the join request. From User `json:"from"` + // UserChatID identifier of a private chat with the user who sent the join request. + UserChatID int64 `json:"user_chat_id"` // Date the request was sent in Unix time. Date int `json:"date"` // Bio of the user. @@ -1770,12 +2983,30 @@ type ChatPermissions struct { // // optional CanSendMessages bool `json:"can_send_messages,omitempty"` - // CanSendMediaMessages is true, if the user is allowed to send audios, - // documents, photos, videos, video notes and voice notes, implies - // can_send_messages + // CanSendAudios is true, if the user is allowed to send audios + // + // optional + CanSendAudios bool `json:"can_send_audios,omitempty"` + // CanSendDocuments is true, if the user is allowed to send documents + // + // optional + CanSendDocuments bool `json:"can_send_documents,omitempty"` + // CanSendPhotos is true, if the user is allowed to send photos + // + // optional + CanSendPhotos bool `json:"can_send_photos,omitempty"` + // CanSendVideos is true, if the user is allowed to send videos // // optional - CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` + CanSendVideos bool `json:"can_send_videos,omitempty"` + // CanSendVideoNotes is true, if the user is allowed to send video notes + // + // optional + CanSendVideoNotes bool `json:"can_send_video_notes,omitempty"` + // CanSendVoiceNotes is true, if the user is allowed to send voice notes + // + // optional + CanSendVoiceNotes bool `json:"can_send_voice_notes,omitempty"` // CanSendPolls is true, if the user is allowed to send polls, implies // can_send_messages // @@ -1806,6 +3037,90 @@ type ChatPermissions struct { // // optional CanPinMessages bool `json:"can_pin_messages,omitempty"` + // CanManageTopics is true, if the user is allowed to create forum topics. + // If omitted defaults to the value of can_pin_messages + // + // optional + CanManageTopics bool `json:"can_manage_topics,omitempty"` +} + +// SetCanSendMediaMessages is a method to replace field "can_send_media_messages". +// It sets CanSendAudio, CanSendDocuments, CanSendPhotos, CanSendVideos, +// CanSendVideoNotes, CanSendVoiceNotes to passed value. +func (c *ChatPermissions) SetCanSendMediaMessages(b bool) { + c.CanSendAudios = b + c.CanSendDocuments = b + c.CanSendPhotos = b + c.CanSendVideos = b + c.CanSendVideoNotes = b + c.CanSendVoiceNotes = b +} + +// CanSendMediaMessages method to replace field "can_send_media_messages". +// It returns true if CanSendAudio and CanSendDocuments and CanSendPhotos and CanSendVideos and +// CanSendVideoNotes and CanSendVoiceNotes are true. +func (c *ChatPermissions) CanSendMediaMessages() bool { + return c.CanSendAudios && c.CanSendDocuments && + c.CanSendPhotos && c.CanSendVideos && + c.CanSendVideoNotes && c.CanSendVoiceNotes +} + +// Birthdate represents a user's birthdate +type Birthdate struct { + // Day of the user's birth; 1-31 + Day int `json:"day"` + // Month of the user's birth; 1-12 + Month int `json:"month"` + // Year of the user's birth + // + // optional + Year *int `json:"year,omitempty"` +} + +// BusinessIntro represents a basic information about your business +type BusinessIntro struct { + // Title text of the business intro + // + // optional + Title *string `json:"title,omitempty"` + // Message text of the business intro + // + // optional + Message *string `json:"message,omitempty"` + // Sticker of the business intro + // + // optional + Sticker *Sticker `json:"sticker,omitempty"` +} + +// BusinessLocation represents a business geodata +type BusinessLocation struct { + // Address of the business + Address string `json:"address"` + // Location of the business + // + // optional + Location *Location `json:"location,omitempty"` +} + +// BusinessOpeningHoursInterval represents a business working interval +type BusinessOpeningHoursInterval struct { + // OpeningMinute is the minute's sequence number in a week, starting on Monday, + // marking the start of the time interval during which the business is open; 0 - 7 * 24 * 60 + OpeningMinute int `json:"opening_minute"` + // ClosingMinute is the minute's sequence number in a week, starting on Monday, + // marking the end of the time interval during which the business is open; 0 - 8 * 24 * 60 + ClosingMinute int `json:"closing_minute"` +} + +// BusinessOpeningHours represents a set of business working intervals +type BusinessOpeningHours struct { + // TimeZoneName is the unique name of the time zone + // for which the opening hours are defined + TimeZoneName string `json:"time_zone_name"` + // OpeningHours is the list of time intervals describing + // business opening hours + OpeningHours []BusinessOpeningHoursInterval `json:"opening_hours"` } // ChatLocation represents a location to which a chat is connected. @@ -1818,6 +3133,93 @@ type ChatLocation struct { Address string `json:"address"` } +const ( + ReactionTypeEmoji = "emoji" + ReactionTypeCustomEmoji = "custom_emoji" + ReactionTypePaid = "paid" +) + +// ReactionType describes the type of a reaction. +// Currently, it can be one of: "emoji", "custom_emoji", "paid" +type ReactionType struct { + // Type of the reaction. Can be "emoji", "custom_emoji", "paid" + Type string `json:"type"` + // Emoji type "emoji" only. Is a reaction emoji. + Emoji string `json:"emoji"` + // CustomEmoji type "custom_emoji" only. Is a custom emoji identifier. + CustomEmoji string `json:"custom_emoji"` +} + +func (r ReactionType) IsEmoji() bool { + return r.Type == ReactionTypeEmoji +} + +func (r ReactionType) IsCustomEmoji() bool { + return r.Type == ReactionTypeCustomEmoji +} + +func (r ReactionType) IsPaid() bool { + return r.Type == ReactionTypePaid +} + +// ReactionCount represents a reaction added to a message along with the number of times it was added. +type ReactionCount struct { + // Type of the reaction + Type ReactionType `json:"type"` + // TotalCount number of times the reaction was added + TotalCount int `json:"total_count"` +} + +// MessageReactionUpdated represents a change of a reaction on a message performed by a user. +type MessageReactionUpdated struct { + // Chat containing the message the user reacted to. + Chat Chat `json:"chat"` + // MessageID unique identifier of the message inside the chat. + MessageID int `json:"message_id"` + // User that changed the reaction, if the user isn't anonymous. + // + // optional + User *User `json:"user"` + // ActorChat the chat on behalf of which the reaction was changed, + // if the user is anonymous. + // + // optional + ActorChat *Chat `json:"actor_chat"` + // Date of the change in Unix time. + Date int64 `json:"date"` + // OldReaction is a previous list of reaction types that were set by the user. + OldReaction []ReactionType `json:"old_reaction"` + // NewReaction is a new list of reaction types that have been set by the user. + NewReaction []ReactionType `json:"new_reaction"` +} + +// MessageReactionCountUpdated represents reaction changes on a message with anonymous reactions. +type MessageReactionCountUpdated struct { + // Chat containing the message. + Chat Chat `json:"chat"` + // MessageID unique identifier of the message inside the chat. + MessageID int `json:"message_id"` + // Date of the change in Unix time. + Date int64 `json:"date"` + // Reactions is a list of reactions that are present on the message. + Reactions []ReactionCount `json:"reactions"` +} + +// ForumTopic represents a forum topic. +type ForumTopic struct { + // MessageThreadID is the unique identifier of the forum topic + MessageThreadID int `json:"message_thread_id"` + // Name is the name of the topic + Name string `json:"name"` + // IconColor is the color of the topic icon in RGB format + IconColor int `json:"icon_color"` + // IconCustomEmojiID is the unique identifier of the custom emoji + // shown as the topic icon + // + // optional + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` +} + // BotCommand represents a bot command. type BotCommand struct { // Command text of the command, 1-32 characters. @@ -1837,6 +3239,21 @@ type BotCommandScope struct { UserID int64 `json:"user_id,omitempty"` } +// BotName represents the bot's name. +type BotName struct { + Name string `json:"name"` +} + +// BotDescription represents the bot's description. +type BotDescription struct { + Description string `json:"description"` +} + +// BotShortDescription represents the bot's short description +type BotShortDescription struct { + ShortDescription string `json:"short_description"` +} + // MenuButton describes the bot's menu button in a private chat. type MenuButton struct { // Type is the type of menu button, must be one of: @@ -1848,9 +3265,128 @@ type MenuButton struct { Text string `json:"text,omitempty"` // WebApp is the description of the Web App that will be launched when the // user presses the button for the `web_app` type. + // + // Alternatively, a t.me link to a Web App of the bot can be specified in the object instead of the Web App's URL, + // in which case the Web App will be opened as if the user pressed the link. WebApp *WebAppInfo `json:"web_app,omitempty"` } +const ( + ChatBoostSourcePremium = "premium" + ChatBoostSourceGiftCode = "gift_code" + ChatBoostSourceGiveaway = "giveaway" +) + +// ChatBoostSource describes the source of a chat boost +type ChatBoostSource struct { + // Source of the boost, It can be one of: + // "premium", "gift_code", "giveaway" + Source string `json:"source"` + // For "premium": User that boosted the chat + // For "gift_code": User for which the gift code was created + // Optional for "giveaway": User that won the prize in the giveaway if any + User *User `json:"user,omitempty"` + // GiveawayMessageID "giveaway" only. + // Is an identifier of a message in the chat with the giveaway; + // the message could have been deleted already. May be 0 if the message isn't sent yet. + GiveawayMessageID int `json:"giveaway_message_id,omitempty"` + // PrizeStarCount "giveaway" only. + // The number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` + // IsUnclaimed "giveaway" only. + // True, if the giveaway was completed, but there was no user to win the prize + // + // optional + IsUnclaimed bool `json:"is_unclaimed,omitempty"` +} + +func (c ChatBoostSource) IsPremium() bool { + return c.Source == ChatBoostSourcePremium +} + +func (c ChatBoostSource) IsGiftCode() bool { + return c.Source == ChatBoostSourceGiftCode +} + +func (c ChatBoostSource) IsGiveaway() bool { + return c.Source == ChatBoostSourceGiveaway +} + +// ChatBoost contains information about a chat boost. +type ChatBoost struct { + // BoostID is an unique identifier of the boost + BoostID string `json:"boost_id"` + // AddDate is a point in time (Unix timestamp) when the chat was boosted + AddDate int64 `json:"add_date"` + // ExpirationDate is a point in time (Unix timestamp) when the boost will + // automatically expire, unless the booster's Telegram Premium subscription is prolonged + ExpirationDate int64 `json:"expiration_date"` + // Source of the added boost + Source ChatBoostSource `json:"source"` +} + +// ChatBoostUpdated represents a boost added to a chat or changed. +type ChatBoostUpdated struct { + // Chat which was boosted + Chat Chat `json:"chat"` + // Boost infomation about the chat boost + Boost ChatBoost `json:"boost"` +} + +// ChatBoostRemoved represents a boost removed from a chat. +type ChatBoostRemoved struct { + // Chat which was boosted + Chat Chat `json:"chat"` + // BoostID unique identifier of the boost + BoostID string `json:"boost_id"` + // RemoveDate point in time (Unix timestamp) when the boost was removed + RemoveDate int64 `json:"remove_date"` + // Source of the removed boost + Source ChatBoostSource `json:"source"` +} + +// UserChatBoosts represents a list of boosts added to a chat by a user. +type UserChatBoosts struct { + // Boosts is the list of boosts added to the chat by the user + Boosts []ChatBoost `json:"boosts"` +} + +// BusinessConnection describes the connection of the bot with a business account. +type BusinessConnection struct { + // ID is an unique identifier of the business connection + ID string `json:"id"` + // User is a business account user that created the business connection + User User `json:"user"` + // UserChatID identifier of a private chat with the user who + // created the business connection. + UserChatID int64 `json:"user_chat_id"` + // Date the connection was established in Unix time + Date int64 `json:"date"` + // CanReply is True, if the bot can act on behalf of the + // business account in chats that were active in the last 24 hours + CanReply bool `json:"can_reply"` + // IsEnabled is True, if the connection is active + IsEnabled bool `json:"is_enabled"` +} + +// BusinessMessagesDeleted is received when messages are deleted +// from a connected business account. +type BusinessMessagesDeleted struct { + // BusinessConnectionID is an unique identifier + // of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Chat is the information about a chat in the business account. + // The bot may not have access to the chat or the corresponding user. + Chat Chat `json:"chat"` + // MessageIDs is a JSON-serialized list of identifiers of deleted messages + // in the chat of the business account + MessageIDs []int `json:"message_ids"` +} + // ResponseParameters are various errors that can be returned in APIResponse. type ResponseParameters struct { // The group has been migrated to a supergroup with the specified identifier. @@ -1891,6 +3427,14 @@ type BaseInputMedia struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` + // HasSpoiler pass True, if the photo needs to be covered with a spoiler animation + // + // optional + HasSpoiler bool `json:"has_spoiler,omitempty"` } // InputMediaPhoto is a photo to send as part of a media group. @@ -1905,7 +3449,7 @@ type InputMediaVideo struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // Width video width // // optional @@ -1922,6 +3466,10 @@ type InputMediaVideo struct { // // optional SupportsStreaming bool `json:"supports_streaming,omitempty"` + // HasSpoiler pass True, if the video needs to be covered with a spoiler animation + // + // optional + HasSpoiler bool `json:"has_spoiler,omitempty"` } // InputMediaAnimation is an animation to send as part of a media group. @@ -1931,7 +3479,7 @@ type InputMediaAnimation struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // Width video width // // optional @@ -1944,6 +3492,10 @@ type InputMediaAnimation struct { // // optional Duration int `json:"duration,omitempty"` + // HasSpoiler pass True, if the photo needs to be covered with a spoiler animation + // + // optional + HasSpoiler bool `json:"has_spoiler,omitempty"` } // InputMediaAudio is an audio to send as part of a media group. @@ -1953,7 +3505,7 @@ type InputMediaAudio struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // Duration of the audio in seconds // // optional @@ -1975,7 +3527,7 @@ type InputMediaDocument struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // DisableContentTypeDetection disables automatic server-side content type // detection for files uploaded using multipart/form-data. Always true, if // the document is sent as part of an album @@ -1984,6 +3536,55 @@ type InputMediaDocument struct { DisableContentTypeDetection bool `json:"disable_content_type_detection,omitempty"` } +// This object describes the paid media to be sent. Currently, it can be one of: +// - InputPaidMediaPhoto +// - InputPaidMediaVideo +type InputPaidMedia struct { + // Type of the media, must be one of: + // - "photo" + // - "video" + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), + // pass an HTTP URL for Telegram to get a file from the Internet, + // or pass “attach://” to upload a new one using multipart/form-data under name. + // More information on https://core.telegram.org/bots/api#sending-files + Media RequestFileData `json:"media"` + // InputPaidMediaVideo only. + // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. + // The thumbnail should be in JPEG format and less than 200 kB in size. + // A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. + // Thumbnails can't be reused and can be only uploaded as a new file, + // so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . + // + // optional + Thumb RequestFileData `json:"thumbnail"` + // InputPaidMediaVideo only. + // Video width + // + // optional + Width int64 `json:"width,omitempty"` + // InputPaidMediaVideo only. + // Video height + // + // optional + Height int64 `json:"height,omitempty"` + // InputPaidMediaVideo only. + // Video duration in seconds + // + // optional + Duration int64 `json:"duration,omitempty"` + // InputPaidMediaVideo only. + // Pass True if the uploaded video is suitable for streaming + SupportsStreaming bool `json:"supports_streaming,omitempty"` +} + +// Constant values for sticker types +const ( + StickerTypeRegular = "regular" + StickerTypeMask = "mask" + StickerTypeCustomEmoji = "custom_emoji" +) + // Sticker represents a sticker. type Sticker struct { // FileID is an identifier for this file, which can be used to download or @@ -1993,6 +3594,10 @@ type Sticker struct { // which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` + // Type is a type of the sticker, currently one of “regular”, + // “mask”, “custom_emoji”. The type of the sticker is independent + // from its format, which is determined by the fields is_animated and is_video. + Type string `json:"type"` // Width sticker width Width int `json:"width"` // Height sticker height @@ -2008,7 +3613,7 @@ type Sticker struct { // Thumbnail sticker thumbnail in the .WEBP or .JPG format // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // Emoji associated with the sticker // // optional @@ -2030,12 +3635,31 @@ type Sticker struct { // // optional CustomEmojiID string `json:"custom_emoji_id,omitempty"` + // NeedsRepainting True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places + // + //optional + NeedsRepainting bool `json:"needs_repainting,omitempty"` // FileSize // // optional FileSize int `json:"file_size,omitempty"` } +// IsRegular returns if the Sticker is regular +func (s Sticker) IsRegular() bool { + return s.Type == StickerTypeRegular +} + +// IsMask returns if the Sticker is mask +func (s Sticker) IsMask() bool { + return s.Type == StickerTypeMask +} + +// IsCustomEmoji returns if the Sticker is custom emoji +func (s Sticker) IsCustomEmoji() bool { + return s.Type == StickerTypeCustomEmoji +} + // StickerSet represents a sticker set. type StickerSet struct { // Name sticker set name @@ -2044,16 +3668,29 @@ type StickerSet struct { Title string `json:"title"` // StickerType of stickers in the set, currently one of “regular”, “mask”, “custom_emoji” StickerType string `json:"sticker_type"` - // IsAnimated true, if the sticker set contains animated stickers - IsAnimated bool `json:"is_animated"` - // IsVideo true, if the sticker set contains video stickers - IsVideo bool `json:"is_video"` // ContainsMasks true, if the sticker set contains masks + // + // deprecated. Use sticker_type instead ContainsMasks bool `json:"contains_masks"` // Stickers list of all set stickers Stickers []Sticker `json:"stickers"` // Thumb is the sticker set thumbnail in the .WEBP or .TGS format - Thumbnail *PhotoSize `json:"thumb"` + Thumbnail *PhotoSize `json:"thumbnail"` +} + +// IsRegular returns if the StickerSet is regular +func (s StickerSet) IsRegular() bool { + return s.StickerType == StickerTypeRegular +} + +// IsMask returns if the StickerSet is mask +func (s StickerSet) IsMask() bool { + return s.StickerType == StickerTypeMask +} + +// IsCustomEmoji returns if the StickerSet is custom emoji +func (s StickerSet) IsCustomEmoji() bool { + return s.StickerType == StickerTypeCustomEmoji } // MaskPosition describes the position on faces where a mask should be placed @@ -2074,6 +3711,25 @@ type MaskPosition struct { Scale float64 `json:"scale"` } +// InputSticker describes a sticker to be added to a sticker set. +type InputSticker struct { + // The added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, upload a new one using multipart/form-data, or pass “attach://” to upload a new one using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL. + Sticker RequestFile `json:"sticker"` + // Format of the added sticker, must be one of “static” for a + // .WEBP or .PNG image, “animated” for a .TGS animation, “video” for a WEBM video + Format string `json:"format"` + // List of 1-20 emoji associated with the sticker + EmojiList []string `json:"emoji_list"` + // Position where the mask should be placed on faces. For “mask” stickers only. + // + // optional + MaskPosition *MaskPosition `json:"mask_position"` + // List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only. + // + // optional + Keywords []string `json:"keywords"` +} + // Game represents a game. Use BotFather to create and edit games, their short // names will act as unique identifiers. type Game struct { @@ -2113,6 +3769,32 @@ type GameHighScore struct { // CallbackGame is for starting a game in an inline keyboard button. type CallbackGame struct{} +// SwitchInlineQueryChosenChat represents an inline button that switches the current +// user to inline mode in a chosen chat, with an optional default inline query. +type SwitchInlineQueryChosenChat struct { + // Query is default inline query to be inserted in the input field. + // If left empty, only the bot's username will be inserted + // + // optional + Query string `json:"query,omitempty"` + // AllowUserChats is True, if private chats with users can be chosen + // + // optional + AllowUserChats bool `json:"allow_user_chats,omitempty"` + // AllowBotChats is True, if private chats with bots can be chosen + // + // optional + AllowBotChats bool `json:"allow_bot_chats,omitempty"` + // AllowGroupChats is True, if group and supergroup chats can be chosen + // + // optional + AllowGroupChats bool `json:"allow_group_chats,omitempty"` + // AllowChannelChats is True, if channel chats can be chosen + // + // optional + AllowChannelChats bool `json:"allow_channel_chats,omitempty"` +} + // WebhookInfo is information about a currently set webhook. type WebhookInfo struct { // URL webhook URL, may be empty if webhook is not set up. @@ -2280,6 +3962,10 @@ type InlineQueryResultCachedGIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message. // // optional @@ -2319,6 +4005,10 @@ type InlineQueryResultCachedMPEG4GIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message. // // optional @@ -2360,6 +4050,10 @@ type InlineQueryResultCachedPhoto struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message. // // optional @@ -2419,6 +4113,10 @@ type InlineQueryResultCachedVideo struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message // // optional @@ -2493,15 +4191,15 @@ type InlineQueryResultArticle struct { // ThumbURL url of the thumbnail for the result // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultAudio is an inline query response audio. @@ -2557,9 +4255,9 @@ type InlineQueryResultContact struct { VCard string `json:"vcard"` ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` InputMessageContent interface{} `json:"input_message_content,omitempty"` - ThumbURL string `json:"thumb_url"` - ThumbWidth int `json:"thumb_width"` - ThumbHeight int `json:"thumb_height"` + ThumbURL string `json:"thumbnail_url"` + ThumbWidth int `json:"thumbnail_width"` + ThumbHeight int `json:"thumbnail_height"` } // InlineQueryResultGame is an inline query response game. @@ -2607,15 +4305,15 @@ type InlineQueryResultDocument struct { // ThumbURL url of the thumbnail (jpeg only) for the file // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultGIF is an inline query response GIF. @@ -2627,7 +4325,9 @@ type InlineQueryResultGIF struct { // URL a valid URL for the GIF file. File size must not exceed 1MB. URL string `json:"gif_url"` // ThumbURL url of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result. - ThumbURL string `json:"thumb_url"` + ThumbURL string `json:"thumbnail_url"` + // MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” + ThumbMimeType string `json:"thumbnail_mime_type,omitempty"` // Width of the GIF // // optional @@ -2659,6 +4359,10 @@ type InlineQueryResultGIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message // // optional @@ -2713,15 +4417,15 @@ type InlineQueryResultLocation struct { // ThumbURL url of the thumbnail for the result // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF. @@ -2745,7 +4449,9 @@ type InlineQueryResultMPEG4GIF struct { // optional Duration int `json:"mpeg4_duration,omitempty"` // ThumbURL url of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result. - ThumbURL string `json:"thumb_url"` + ThumbURL string `json:"thumbnail_url"` + // MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” + ThumbMimeType string `json:"thumbnail_mime_type,omitempty"` // Title for the result // // optional @@ -2765,6 +4471,10 @@ type InlineQueryResultMPEG4GIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message // // optional @@ -2797,7 +4507,7 @@ type InlineQueryResultPhoto struct { // ThumbURL url of the thumbnail for the photo. // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // Title for the result // // optional @@ -2825,6 +4535,10 @@ type InlineQueryResultPhoto struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // InputMessageContent content of the message to be sent instead of the photo. // // optional @@ -2873,15 +4587,15 @@ type InlineQueryResultVenue struct { // ThumbURL url of the thumbnail for the result // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultVideo is an inline query response video. @@ -2897,13 +4611,28 @@ type InlineQueryResultVideo struct { // // ThumbURL url of the thumbnail (jpeg only) for the video // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // Title for the result Title string `json:"title"` // Caption of the video to be sent, 0-1024 characters after entities parsing // // optional Caption string `json:"caption,omitempty"` + // CaptionEntities is a list of special entities that appear in the caption, + // which can be specified instead of parse_mode + // + // optional + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` + // ParseMode mode for parsing entities in the video caption. + // See formatting options for more details + // (https://core.telegram.org/bots/api#formatting-options). + // + // optional + ParseMode string `json:"parse_mode,omitempty"` // Width video width // // optional @@ -2946,7 +4675,7 @@ type InlineQueryResultVoice struct { // // optional Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. + // ParseMode mode for parsing entities in the voice caption. // See formatting options for more details // (https://core.telegram.org/bots/api#formatting-options). // @@ -3017,10 +4746,10 @@ type InputTextMessageContent struct { // // optional Entities []MessageEntity `json:"entities,omitempty"` - // DisableWebPagePreview disables link previews for links in the sent message + // LinkPreviewOptions used for link preview generation for the original message // - // optional - DisableWebPagePreview bool `json:"disable_web_page_preview,omitempty"` + // Optional + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` } // InputLocationMessageContent contains a location for displaying @@ -3109,9 +4838,11 @@ type InputInvoiceMessageContent struct { // Bot-defined invoice payload, 1-128 bytes. This will not be displayed to // the user, use for your internal processes. Payload string `json:"payload"` - // Payment provider token, obtained via Botfather + // Payment provider token, obtained via Botfather. Pass an empty string for payments in Telegram Stars. + // + // optional ProviderToken string `json:"provider_token"` - // Three-letter ISO 4217 currency code + // Three-letter ISO 4217 currency code. Pass “XTR” for payments in Telegram Stars. Currency string `json:"currency"` // Price breakdown, a JSON-serialized list of components (e.g. product // price, tax, discount, delivery cost, delivery tax, bonus, etc.) @@ -3203,7 +4934,7 @@ type Invoice struct { Description string `json:"description"` // StartParameter unique bot deep-linking parameter that can be used to generate this invoice StartParameter string `json:"start_parameter"` - // Currency three-letter ISO 4217 currency code + // Currency three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars // (see https://core.telegram.org/bots/payments#supported-currencies) Currency string `json:"currency"` // TotalAmount total price in the smallest units of the currency (integer, not float/double). @@ -3263,7 +4994,7 @@ type ShippingOption struct { // SuccessfulPayment contains basic information about a successful payment. type SuccessfulPayment struct { - // Currency three-letter ISO 4217 currency code + // Currency three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars // (see https://core.telegram.org/bots/payments#supported-currencies) Currency string `json:"currency"` // TotalAmount total price in the smallest units of the currency (integer, not float/double). @@ -3289,6 +5020,27 @@ type SuccessfulPayment struct { ProviderPaymentChargeID string `json:"provider_payment_charge_id"` } +// RefundPayment contains basic information about a refunded payment. +type RefundedPayment struct { + // Three-letter ISO 4217 currency code (https://core.telegram.org/bots/payments#supported-currencies), + // or “XTR” for payments in Telegram Stars. + // Currently, always “XTR” + Currency string `json:"currency"` + // Total refunded price in the smallest units of the currency (integer, not float/double). + // For example, for a price of US$ 1.45, total_amount = 145. + // See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, + // it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). + TotalAmount int64 `json:"total_amount"` + // Bot-specified invoice payload + InvoicePayload string `json:"invoice_payload"` + // Telegram payment identifier + TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` + // Provider payment identifier + // + // optional + ProviderPaymentChargeID string `json:"provider_payment_charge_id,omitempty"` +} + // ShippingQuery contains information about an incoming shipping query. type ShippingQuery struct { // ID unique query identifier @@ -3307,7 +5059,7 @@ type PreCheckoutQuery struct { ID string `json:"id"` // From user who sent the query From *User `json:"from"` - // Currency three-letter ISO 4217 currency code + // Currency three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars // // (see https://core.telegram.org/bots/payments#supported-currencies) Currency string `json:"currency"` // TotalAmount total price in the smallest units of the currency (integer, not float/double). @@ -3328,3 +5080,90 @@ type PreCheckoutQuery struct { // optional OrderInfo *OrderInfo `json:"order_info,omitempty"` } + +// PaidMediaPurchased contains information about a paid media purchase. +type PaidMediaPurchased struct { + // From is the user who purchased the media + From User `json:"from"` + // PaidMediaPayload bot-specified paid media payload + PaidMediaPayload string `json:"paid_media_payload"` +} + +// RevenueWithdrawalState describes the state of a revenue withdrawal operation. +// Currently, it can be one of +// - RevenueWithdrawalStatePending +// - RevenueWithdrawalStateSucceeded +// - RevenueWithdrawalStateFailed +type RevenueWithdrawalState struct { + // Type of the state. Must be one of: + // - pending + // - succeeded + // - failed + Type string `json:"type"` + // Date the withdrawal was completed in Unix time. Represents only in “succeeded” state + Date int64 `json:"date,omitempty"` + // An HTTPS URL that can be used to see transaction details. + // Represents only in “succeeded” state + URL string `json:"url,omitempty"` +} + +// TransactionPartner describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of +// - TransactionPartnerUser +// - TransactionPartnerFragment +// - TransactionPartnerTelegramAds +// - TransactionPartnerOther +type TransactionPartner struct { + //Type of the transaction partner. Must be one of: + // - fragment + // - user + // - other + // - telegram_ads + Type string `json:"type"` + // State of the transaction if the transaction is outgoing. + // Represent only in "fragment" state + // + // optional + WithdrawalState *RevenueWithdrawalState `json:"withdrawal_state,omitempty"` + // Information about the user. + // Represent only in "user" state + User *User `json:"user,omitempty"` + // TransactionPartnerUser only. + // Bot-specified invoice payload + // + // optional + InvoicePayload string `json:"invoice_payload,omitempty"` + // PaidMedia is the nformation about the paid media + // bought by the user + // Represent only in "user" state + // + // optional + PaidMedia []PaidMedia `json:"paid_media,omitempty"` +} + +// StarTransaction describes a Telegram Star transaction. +type StarTransaction struct { + // Unique identifier of the transaction. + // Coincides with the identifer of the original transaction for refund transactions. + // Coincides with SuccessfulPayment.telegram_payment_charge_id for successful incoming payments from users. + ID string `json:"id"` + // Number of Telegram Stars transferred by the transaction + Amount int64 `json:"amount"` + // Date the transaction was created in Unix time + Date int64 `json:"date"` + // Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). + // Only for incoming transactions + // + // optional + Source *TransactionPartner `json:"source,omitempty"` + // Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). + // Only for outgoing transactions + // + // optional + Reciever *TransactionPartner `json:"reciever,omitempty"` +} + +// StarTransactions contains a list of Telegram Star transactions. +type StarTransactions struct { + // The list of transactions + Transactions []StarTransaction `json:"transactions"` +} diff --git a/types_test.go b/types_test.go index 0c6ba4ab..f209f76b 100644 --- a/types_test.go +++ b/types_test.go @@ -293,6 +293,7 @@ var ( _ Chattable = ContactConfig{} _ Chattable = CopyMessageConfig{} _ Chattable = CreateChatInviteLinkConfig{} + _ Chattable = CreateChatSubscriptionLinkConfig{} _ Chattable = DeleteChatPhotoConfig{} _ Chattable = DeleteChatStickerSetConfig{} _ Chattable = DeleteMessageConfig{} @@ -300,6 +301,7 @@ var ( _ Chattable = DeleteWebhookConfig{} _ Chattable = DocumentConfig{} _ Chattable = EditChatInviteLinkConfig{} + _ Chattable = EditChatSubscriptionLinkConfig{} _ Chattable = EditMessageCaptionConfig{} _ Chattable = EditMessageLiveLocationConfig{} _ Chattable = EditMessageMediaConfig{} @@ -308,6 +310,7 @@ var ( _ Chattable = FileConfig{} _ Chattable = ForwardConfig{} _ Chattable = GameConfig{} + _ Chattable = GetBusinessConnectionConfig{} _ Chattable = GetChatMemberConfig{} _ Chattable = GetChatMenuButtonConfig{} _ Chattable = GetGameHighScoresConfig{} @@ -324,6 +327,7 @@ var ( _ Chattable = PinChatMessageConfig{} _ Chattable = PreCheckoutConfig{} _ Chattable = PromoteChatMemberConfig{} + _ Chattable = ReplaceStickerInSetConfig{} _ Chattable = RestrictChatMemberConfig{} _ Chattable = RevokeChatInviteLinkConfig{} _ Chattable = SendPollConfig{} @@ -341,12 +345,41 @@ var ( _ Chattable = UnbanChatSenderChatConfig{} _ Chattable = UnpinChatMessageConfig{} _ Chattable = UpdateConfig{} + _ Chattable = SetMessageReactionConfig{} _ Chattable = UserProfilePhotosConfig{} _ Chattable = VenueConfig{} _ Chattable = VideoConfig{} _ Chattable = VideoNoteConfig{} _ Chattable = VoiceConfig{} _ Chattable = WebhookConfig{} + _ Chattable = CreateForumTopicConfig{} + _ Chattable = EditForumTopicConfig{} + _ Chattable = CloseForumTopicConfig{} + _ Chattable = ReopenForumTopicConfig{} + _ Chattable = DeleteForumTopicConfig{} + _ Chattable = UnpinAllForumTopicMessagesConfig{} + _ Chattable = GetForumTopicIconStickersConfig{} + _ Chattable = EditGeneralForumTopicConfig{} + _ Chattable = CloseGeneralForumTopicConfig{} + _ Chattable = ReopenGeneralForumTopicConfig{} + _ Chattable = HideGeneralForumTopicConfig{} + _ Chattable = UnhideGeneralForumTopicConfig{} + _ Chattable = UnpinAllGeneralForumTopicMessagesConfig{} + _ Chattable = SetCustomEmojiStickerSetThumbnailConfig{} + _ Chattable = SetStickerSetTitleConfig{} + _ Chattable = DeleteStickerSetConfig{} + _ Chattable = SetStickerEmojiListConfig{} + _ Chattable = SetStickerKeywordsConfig{} + _ Chattable = SetStickerMaskPositionConfig{} + _ Chattable = GetMyDescriptionConfig{} + _ Chattable = SetMyDescriptionConfig{} + _ Chattable = GetMyShortDescriptionConfig{} + _ Chattable = SetMyShortDescriptionConfig{} + _ Chattable = GetMyNameConfig{} + _ Chattable = SetMyNameConfig{} + _ Chattable = RefundStarPaymentConfig{} + _ Chattable = GetStarTransactionsConfig{} + _ Chattable = PaidMediaConfig{} ) // Ensure all Fileable types are correct. @@ -368,6 +401,7 @@ var ( _ Fileable = (*MediaGroupConfig)(nil) _ Fileable = (*WebhookConfig)(nil) _ Fileable = (*SetStickerSetThumbConfig)(nil) + _ Fileable = (*PaidMediaConfig)(nil) ) // Ensure all RequestFileData types are correct.