File: telegram_client.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,432 kB
  • sloc: sh: 74; makefile: 5
file content (74 lines) | stat: -rw-r--r-- 1,663 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package telegram

import (
	"encoding/json"
	"fmt"

	"github.com/nicholas-fedor/shoutrrr/pkg/util/jsonclient"
)

// Client for Telegram API.
type Client struct {
	token string
}

func (c *Client) apiURL(endpoint string) string {
	return fmt.Sprintf(apiFormat, c.token, endpoint)
}

// GetBotInfo returns the bot User info.
func (c *Client) GetBotInfo() (*User, error) {
	response := &userResponse{}
	err := jsonclient.Get(c.apiURL("getMe"), response)

	if !response.OK {
		return nil, GetErrorResponse(jsonclient.ErrorBody(err))
	}

	return &response.Result, nil
}

// GetUpdates retrieves the latest updates.
func (c *Client) GetUpdates(
	offset int,
	limit int,
	timeout int,
	allowedUpdates []string,
) ([]Update, error) {
	request := &updatesRequest{
		Offset:         offset,
		Limit:          limit,
		Timeout:        timeout,
		AllowedUpdates: allowedUpdates,
	}
	response := &updatesResponse{}
	err := jsonclient.Post(c.apiURL("getUpdates"), request, response)

	if !response.OK {
		return nil, GetErrorResponse(jsonclient.ErrorBody(err))
	}

	return response.Result, nil
}

// SendMessage sends the specified Message.
func (c *Client) SendMessage(message *SendMessagePayload) (*Message, error) {
	response := &messageResponse{}
	err := jsonclient.Post(c.apiURL("sendMessage"), message, response)

	if !response.OK {
		return nil, GetErrorResponse(jsonclient.ErrorBody(err))
	}

	return response.Result, nil
}

// GetErrorResponse retrieves the error message from a failed request.
func GetErrorResponse(body string) error {
	response := &responseError{}
	if err := json.Unmarshal([]byte(body), response); err == nil {
		return response
	}

	return nil
}