Debian Codegraph @

pkg/services/chat/telegram/telegram_client.go

raw symbols SCIP
1 package telegram
2
3 import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7
8 "github.com/nicholas-fedor/shoutrrr/pkg/types"
9 "github.com/nicholas-fedor/shoutrrr/pkg/util/jsonclient"
10 )
11
12 // Client for Telegram API.
13 type Client struct {
14 token string
15 httpClient types.HTTPClient
16 }
17
18 // GetBotInfo returns the bot User info.
19 func (c *Client) GetBotInfo() (*User, error) {
20 response := &userResponse{}
21 jc := jsonclient.NewWithHTTPClient(c.httpClientOrDefault())
22 err := jc.Get(c.apiURL("getMe"), response)
23
24 if !response.OK {
25 return nil, GetErrorResponse(jsonclient.ErrorBody(err))
26 }
27
28 return &response.Result, nil
29 }
30
31 // GetUpdates retrieves the latest updates.
32 func (c *Client) GetUpdates(
33 offset int,
34 limit int,
35 timeout int,
36 allowedUpdates []string,
37 ) ([]Update, error) {
38 request := &updatesRequest{
39 Offset: offset,
40 Limit: limit,
41 Timeout: timeout,
42 AllowedUpdates: allowedUpdates,
43 }
44 response := &updatesResponse{}
45 jc := jsonclient.NewWithHTTPClient(c.httpClientOrDefault())
46 err := jc.Post(c.apiURL("getUpdates"), request, response)
47
48 if !response.OK {
49 return nil, GetErrorResponse(jsonclient.ErrorBody(err))
50 }
51
52 return response.Result, nil
53 }
54
55 // SendMessage sends the specified Message.
56 func (c *Client) SendMessage(message *SendMessagePayload) (*Message, error) {
57 response := &messageResponse{}
58 jc := jsonclient.NewWithHTTPClient(c.httpClientOrDefault())
59 err := jc.Post(c.apiURL("sendMessage"), message, response)
60
61 if !response.OK {
62 return nil, GetErrorResponse(jsonclient.ErrorBody(err))
63 }
64
65 return response.Result, nil
66 }
67
68 func (c *Client) apiURL(endpoint string) string {
69 return fmt.Sprintf(apiFormat, c.token, endpoint)
70 }
71
72 // httpClientOrDefault returns the injected client or a default Client.
73 func (c *Client) httpClientOrDefault() types.HTTPClient {
74 if c.httpClient != nil {
75 return c.httpClient
76 }
77
78 return &http.Client{Timeout: defaultHTTPTimeout}
79 }
80
81 // GetErrorResponse retrieves the error message from a failed request.
82 func GetErrorResponse(body string) error {
83 response := &responseError{}
84 if err := json.Unmarshal([]byte(body), response); err == nil {
85 return response
86 }
87
88 return nil
89 }