-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram_utils.go
69 lines (56 loc) · 1.5 KB
/
telegram_utils.go
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
package main
import (
"errors"
"fmt"
"image"
_ "image/jpeg"
"io"
"log"
"net/http"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func GetBot(token string, isDebug bool) (*tgbotapi.BotAPI, error) {
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
return nil, err
}
bot.Debug = isDebug
log.Printf("Authorized on account %s", bot.Self.UserName)
return bot, nil
}
var httpClient = &http.Client{
Timeout: 10 * time.Second,
}
func GetUserAvatar(bot *tgbotapi.BotAPI, userId int64) (*image.NRGBA, error) {
photos, err := bot.GetUserProfilePhotos(tgbotapi.UserProfilePhotosConfig{
UserID: userId,
Limit: 1,
})
if err != nil {
return nil, fmt.Errorf("error geting avatar: %s", err)
}
if len(photos.Photos) == 0 {
return nil, errors.New("you don't have avatars")
}
largestPhoto := photos.Photos[0][len(photos.Photos[0])-1]
fileConfig, err := bot.GetFileDirectURL(largestPhoto.FileID)
if err != nil {
return nil, fmt.Errorf("error loading avatar: %s", err)
}
resp, err := httpClient.Get(fileConfig)
if err != nil {
return nil, fmt.Errorf("network error loading avatar: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("network error loading avatar, status: %d, body: %s", resp.StatusCode, string(body))
}
img, _, err := image.Decode(resp.Body)
if err != nil {
println(err)
return nil, fmt.Errorf("error decoding avatar: %s", err)
}
return ImageToNRGBA(img), nil
}