This repository was archived by the owner on Nov 28, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (63 loc) · 1.69 KB
/
main.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/buger/jsonparser"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
func setWebhook(url string, botURL string) {
response, err := http.Get(url + "setWebhook?url=" + botURL)
if err != nil {
fmt.Println("webhook error", err)
}
fmt.Println("webhook response", response)
}
func sendMessage(baseURL string, chatID string, message string) {
jsonString := fmt.Sprintf(`{"chat_id" : 184935795, "text": "%s"}`, message)
jsonStr := []byte(jsonString)
req, err := http.NewRequest("POST", baseURL+"sendMessage", bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("error", err)
}
defer resp.Body.Close()
// _, _ := ioutil.ReadAll(resp.Body)
}
func main() {
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env file")
}
botURL := os.Getenv("BOT_URL")
telegramKey := os.Getenv("TELEGRAM_BOT_KEY")
baseURL := "https://api.telegram.org/bot" + telegramKey + "/"
setWebhook(baseURL, botURL)
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/", func(c *gin.Context) {
fmt.Println(c.Request.Body)
c.JSON(200, gin.H{})
})
r.POST("/", func(c *gin.Context) {
data, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
fmt.Println(err)
}
chatID, _, _, err := jsonparser.Get(data, "message", "from", "id")
message, _, _, err := jsonparser.Get(data, "message", "text")
sendMessage(baseURL, string(chatID), string(message))
c.JSON(200, gin.H{})
})
r.Run() // listen and serve on 0.0.0.0:8080
}