client.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package telegrambot // import "miniflux.app/v2/internal/integration/telegrambot"
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "time"
  11. "miniflux.app/v2/internal/http/client"
  12. "miniflux.app/v2/internal/urllib"
  13. "miniflux.app/v2/internal/version"
  14. )
  15. const (
  16. defaultClientTimeout = 10 * time.Second
  17. telegramAPIEndpoint = "https://api.telegram.org"
  18. MarkdownFormatting = "Markdown"
  19. MarkdownV2Formatting = "MarkdownV2"
  20. HTMLFormatting = "HTML"
  21. )
  22. type Client struct {
  23. apiEndpoint string
  24. botToken string
  25. chatID string
  26. }
  27. func NewClient(botToken, chatID string) *Client {
  28. return &Client{
  29. apiEndpoint: telegramAPIEndpoint,
  30. botToken: botToken,
  31. chatID: chatID,
  32. }
  33. }
  34. // Specs: https://core.telegram.org/bots/api#getme
  35. func (c *Client) GetMe() (*User, error) {
  36. endpointURL, err := url.JoinPath(c.apiEndpoint, "/bot"+c.botToken, "/getMe")
  37. if err != nil {
  38. return nil, fmt.Errorf("telegram: unable to join base URL and path: %w", err)
  39. }
  40. request, err := http.NewRequest(http.MethodGet, endpointURL, nil)
  41. if err != nil {
  42. return nil, fmt.Errorf("telegram: unable to create request: %v", err)
  43. }
  44. request.Header.Set("Accept", "application/json")
  45. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  46. httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
  47. response, err := httpClient.Do(request)
  48. if err != nil {
  49. return nil, fmt.Errorf("telegram: unable to send request: %v", urllib.RedactSecretURLInError(err))
  50. }
  51. defer response.Body.Close()
  52. var userResponse UserResponse
  53. if err := json.NewDecoder(response.Body).Decode(&userResponse); err != nil {
  54. return nil, fmt.Errorf("telegram: unable to decode user response: %w", err)
  55. }
  56. if !userResponse.Ok {
  57. return nil, fmt.Errorf("telegram: unable to send message: %s (error code is %d)", userResponse.Description, userResponse.ErrorCode)
  58. }
  59. return &userResponse.Result, nil
  60. }
  61. // Specs: https://core.telegram.org/bots/api#sendmessage
  62. func (c *Client) SendMessage(message *MessageRequest) (*Message, error) {
  63. endpointURL, err := url.JoinPath(c.apiEndpoint, "/bot"+c.botToken, "/sendMessage")
  64. if err != nil {
  65. return nil, fmt.Errorf("telegram: unable to join base URL and path: %w", err)
  66. }
  67. requestBody, err := json.Marshal(message)
  68. if err != nil {
  69. return nil, fmt.Errorf("telegram: unable to encode request body: %v", err)
  70. }
  71. request, err := http.NewRequest(http.MethodPost, endpointURL, bytes.NewReader(requestBody))
  72. if err != nil {
  73. return nil, fmt.Errorf("telegram: unable to create request: %v", err)
  74. }
  75. request.Header.Set("Content-Type", "application/json")
  76. request.Header.Set("Accept", "application/json")
  77. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  78. httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
  79. response, err := httpClient.Do(request)
  80. if err != nil {
  81. return nil, fmt.Errorf("telegram: unable to send request: %v", urllib.RedactSecretURLInError(err))
  82. }
  83. defer response.Body.Close()
  84. var messageResponse MessageResponse
  85. if err := json.NewDecoder(response.Body).Decode(&messageResponse); err != nil {
  86. return nil, fmt.Errorf("telegram: unable to decode discovery response: %w", err)
  87. }
  88. if !messageResponse.Ok {
  89. return nil, fmt.Errorf("telegram: unable to send message: %s (error code is %d)", messageResponse.Description, messageResponse.ErrorCode)
  90. }
  91. return &messageResponse.Result, nil
  92. }
  93. type InlineKeyboard struct {
  94. InlineKeyboard []InlineKeyboardRow `json:"inline_keyboard"`
  95. }
  96. type InlineKeyboardRow []*InlineKeyboardButton
  97. type InlineKeyboardButton struct {
  98. Text string `json:"text"`
  99. URL string `json:"url,omitempty"`
  100. }
  101. type User struct {
  102. ID int64 `json:"id"`
  103. FirstName string `json:"first_name"`
  104. LastName string `json:"last_name"`
  105. Username string `json:"username"`
  106. LanguageCode string `json:"language_code"`
  107. IsBot bool `json:"is_bot"`
  108. IsPremium bool `json:"is_premium"`
  109. CanJoinGroups bool `json:"can_join_groups"`
  110. CanReadAllGroupMessages bool `json:"can_read_all_group_messages"`
  111. SupportsInlineQueries bool `json:"supports_inline_queries"`
  112. }
  113. type Chat struct {
  114. ID int64 `json:"id"`
  115. Type string `json:"type"`
  116. Title string `json:"title"`
  117. }
  118. type Message struct {
  119. MessageID int64 `json:"message_id"`
  120. From User `json:"from"`
  121. Chat Chat `json:"chat"`
  122. MessageThreadID int64 `json:"message_thread_id"`
  123. Date int64 `json:"date"`
  124. }
  125. type BaseResponse struct {
  126. Ok bool `json:"ok"`
  127. ErrorCode int `json:"error_code"`
  128. Description string `json:"description"`
  129. }
  130. type UserResponse struct {
  131. BaseResponse
  132. Result User `json:"result"`
  133. }
  134. type MessageRequest struct {
  135. ChatID string `json:"chat_id"`
  136. MessageThreadID int64 `json:"message_thread_id,omitempty"`
  137. Text string `json:"text"`
  138. ParseMode string `json:"parse_mode,omitempty"`
  139. DisableWebPagePreview bool `json:"disable_web_page_preview"`
  140. DisableNotification bool `json:"disable_notification"`
  141. ReplyMarkup *InlineKeyboard `json:"reply_markup,omitempty"`
  142. }
  143. type MessageResponse struct {
  144. BaseResponse
  145. Result Message `json:"result"`
  146. }