-
Notifications
You must be signed in to change notification settings - Fork 1
/
emulator.go
132 lines (108 loc) · 2.5 KB
/
emulator.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
package main
import (
"encoding/json"
"net/http"
"github.com/gorilla/websocket"
log "gopkg.in/inconshreveable/log15.v2"
"github.com/pavel-paulau/howdy/telegram"
)
var (
updateID int
)
func init() {
messages = make(chan botResponse, 10)
}
type chatMessage struct {
Text string `json:"text"`
FirstName string `json:"firstName"`
UserName string `json:"userName"`
UserID int `json:"userId"`
Phone string `json:"phone"`
Webhook string `json:"webhook"`
}
type telegramResponse struct {
OK bool `json:"ok"`
}
type botResponse struct {
ChatID int `json:"chat_id"` // Unique identifier for the target chat
Text string `json:"text"` // Text of the message to be sent
ReplyMarkup interface{} `json:"reply_markup"` // Additional interface options.
}
func forwardMessages(rw http.ResponseWriter, req *http.Request) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(rw, req, nil)
if err != nil {
log.Error("failed to upgrade to websockets", "err", err)
return
}
isOpen := true
var myUser int
go func() {
defer func() {
isOpen = false
conn.Close()
}()
for {
var message chatMessage
if err := conn.ReadJSON(&message); err != nil {
log.Error("failed to read data", "err", err)
break
}
myUser = message.UserID
sendUpdateToBot(message)
}
}()
go func() {
defer conn.Close()
for {
response := <-messages
if !isOpen {
messages <- response
break
}
if response.ChatID != myUser {
messages <- response
continue
}
if err := conn.WriteJSON(&response); err != nil {
log.Error("failed to write data", "err", err)
break
}
}
}()
}
func sendUpdateToBot(message chatMessage) {
updateID++
update := telegram.Update{
Message: telegram.Message{
Text: message.Text,
From: telegram.User{
FirstName: message.FirstName,
ID: message.UserID,
},
Contact: telegram.Contact{
FirstName: message.FirstName,
PhoneNumber: message.Phone,
},
},
UpdateID: updateID,
}
if err := SendJSON(message.Webhook, &update); err != nil {
log.Error("failed to send update", "err", err)
}
}
func mockTelegram(rw http.ResponseWriter, req *http.Request) {
var br botResponse
var tr telegramResponse
if err := ReadJSON(req, &br); err != nil {
log.Error(err.Error())
tr = telegramResponse{OK: false}
} else {
messages <- br
tr = telegramResponse{OK: true}
}
json.NewEncoder(rw).Encode(&tr)
}