Debian Codegraph @

pkg/services/chat/telegram/telegram_client.go

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