-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
156 lines (99 loc) · 2.43 KB
/
handlers.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
//"log"
"fmt"
//tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"bytes"
"encoding/json"
"errors"
"strconv"
)
type Link struct {
Url string
ChatID int64
}
type webhookReqBody struct {
Message struct {
Text string `json:"text"`
Chat struct {
ID int64 `json:"id"`
} `json:"chat"`
} `json:"message"`
}
func LinkHandler( c *gin.Context) {
var link Link
if err := c.ShouldBindJSON(&link); err != nil {
c.JSON(http.StatusBadRequest, gin.H {"error": err.Error()})
return
}
if err := linkSender(link.Url, link.ChatID); err != nil {
fmt.Println("error in sending reply:", err)
return
}
c.JSON(http.StatusOK, link)
}
type sendMessageReqBody struct {
ChatID int64 `json:"chat_id"`
Text string `json:"text"`
}
func ResponseBot(chatID int64) error {
viper.SetConfigFile("ENV")
viper.ReadInConfig()
viper.AutomaticEnv()
token := fmt.Sprint(viper.Get("TOKEN"))
strChatId :=strconv.FormatInt(chatID, 10)
reqBody := &sendMessageReqBody{
ChatID: chatID,
Text: strChatId,
}
reqBytes, err := json.Marshal(reqBody)
if err != nil {
return err
}
res, err := http.Post("https://api.telegram.org/bot"+token+"/sendMessage", "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return errors.New("unexpected status" + res.Status)
}
return nil
}
func Handler(c *gin.Context) {
body := &webhookReqBody{}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H {"error": err.Error()})
return
}
if err := ResponseBot(body.Message.Chat.ID); err != nil {
fmt.Println("error in sending reply:", err)
return
}
// log a confirmation message if the message is sent successfully
fmt.Println("reply sent")
}
func linkSender(url string, chatID int64) error {
viper.SetConfigFile("ENV")
viper.ReadInConfig()
viper.AutomaticEnv()
token := fmt.Sprint(viper.Get("TOKEN"))
reqBody := &sendMessageReqBody{
ChatID: chatID,
Text: url,
}
reqBytes, err := json.Marshal(reqBody)
if err != nil {
return err
}
res, err := http.Post("https://api.telegram.org/bot"+token+"/sendMessage", "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return errors.New("unexpected status" + res.Status)
}
return nil
}