forked from craftlion/communautofinder_telegrambot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
305 lines (229 loc) · 8.34 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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/joho/godotenv"
"github.com/mguaylam/communautofinder"
)
// Possible states in conversation with the bot
const (
NotSearching = iota
AskingType
AskingMargin
AskingPosition
AskingDateStart
AskingDateEnd
Searching
EndSearch
)
const (
Flex = iota
Station
)
type UserContext struct {
chatId int64
state int
searchType int
kmMargin float64
latitude float64
longitude float64
dateStart time.Time
dateEnd time.Time
}
var cityId int
var userContexts = make(map[int64]UserContext)
var resultChannel = make(map[int64]chan int)
var cancelSearchingMethod = make(map[int64]context.CancelFunc)
const layoutDate = "2006-01-02 15:04"
const dateExample = "2023-11-21 20:12"
var authorizedUserIdSlice []string
var authorizedUserId string
var bot *tgbotapi.BotAPI
var mutex = sync.Mutex{}
func main() {
var err error
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
})
go http.ListenAndServe(":8444", nil)
// Find TOKEN env if exist
godotenv.Load()
bot, err = tgbotapi.NewBotAPI(os.Getenv("TOKEN_COMMUNAUTOSEARCH_BOT"))
authorizedUserId = os.Getenv("AUTHORIZED_USERS_ID")
cityId, err = strconv.Atoi(os.Getenv("CITY_ID"))
authorizedUserIdSlice = strings.Split(authorizedUserId, ";")
if err != nil {
log.Fatal(err)
}
log.Printf("Authorized on Telegram account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
if err != nil {
log.Fatal(err)
}
for update := range updates {
if update.Message == nil {
continue
}
userID := update.Message.From.ID
message := update.Message
mutex.Lock()
userCtx, found := userContexts[int64(userID)]
userCtx.chatId = update.Message.Chat.ID
if !found {
resultChannel[userCtx.chatId] = make(chan int, 1)
}
response := generateResponse(&userCtx, message)
userContexts[int64(userID)] = userCtx
mutex.Unlock()
msg := tgbotapi.NewMessage(userCtx.chatId, response)
bot.Send(msg)
}
}
func generateResponse(userCtx *UserContext, message *tgbotapi.Message) string {
messageText := message.Text
userAuthorized := false
// check if user is authorized with to chat from AUTHORIZED_USERS_ID
for _, element := range authorizedUserIdSlice {
userIdInt64, err := strconv.ParseInt(element, 10, 64)
if err != nil {
log.Fatal(err)
}
if userCtx.chatId == userIdInt64 {
userAuthorized = true
}
}
if userAuthorized != true {
log.Printf("User not authorized : " + strconv.FormatInt(userCtx.chatId, 10))
return "Vous n'êtes pas autorisé à utiliser ce rebot."
}
if strings.ToLower(messageText) == "/aide" {
return "Écrire:\n/chercher pour initier une nouvelle recherche.\n/recommencer pour redémarrer une recherche avec les mêmes paramètres que la recherche précédente."
} else if strings.ToLower(messageText) == "/chercher" {
if userCtx.state == Searching {
log.Printf("Cancelling searching for user " + strconv.FormatInt(userCtx.chatId, 10))
cancelSearchingMethod[userCtx.chatId]()
}
userCtx.state = AskingType
log.Printf("Asking user " + strconv.FormatInt(userCtx.chatId, 10) + " vehicule type")
return "Bonjour ! Tapez :\n- station pour rechercher une Communauto en station.\n- flex pour rechercher un véhicule Communauto Flex."
} else if userCtx.state == AskingType {
if strings.ToLower(messageText) == "station" {
userCtx.searchType = Station
userCtx.state = AskingMargin
log.Printf("Asking user " + strconv.FormatInt(userCtx.chatId, 10) + " station radius search")
return "Quelle est votre distance de recherche en kilomètres ?"
} else if strings.ToLower(messageText) == "flex" {
userCtx.searchType = Flex
userCtx.state = AskingMargin
log.Printf("Asking user " + strconv.FormatInt(userCtx.chatId, 10) + " flex radius search")
return "Quelle est votre distance de recherche en kilomètres ?"
}
} else if userCtx.state == AskingMargin {
margin, err := strconv.ParseFloat(messageText, 64)
if err == nil {
if margin > 0 {
userCtx.kmMargin = margin
userCtx.state = AskingPosition
log.Printf("Asking user " + strconv.FormatInt(userCtx.chatId, 10) + " location")
return "Veuillez partager votre position pour votre recherche."
}
}
return "Veuillez entrer un rayon de recherche correct."
} else if userCtx.state == AskingPosition {
if message.Location != nil {
userCtx.latitude = message.Location.Latitude
userCtx.longitude = message.Location.Longitude
if userCtx.searchType == Flex {
userCtx.state = Searching
go launchSearch(*userCtx)
return generateMessageResearch(*userCtx)
} else if userCtx.searchType == Station {
userCtx.state = AskingDateStart
log.Printf("Asking user " + strconv.FormatInt(userCtx.chatId, 10) + " start date and time for station")
return fmt.Sprintf("Quelle est la date et l'heure de début de la location au format %s ?", dateExample)
}
}
} else if userCtx.state == AskingDateStart {
t, err := time.Parse(layoutDate, messageText)
if err == nil {
userCtx.dateStart = t
userCtx.state = AskingDateEnd
log.Printf("Asking user " + strconv.FormatInt(userCtx.chatId, 10) + " end date and time for station")
return fmt.Sprintf("Quelle est la date et l'heure de fin de la location au format %s ?", dateExample)
}
} else if userCtx.state == AskingDateEnd {
t, err := time.Parse(layoutDate, messageText)
if err == nil {
userCtx.dateEnd = t
userCtx.state = Searching
go launchSearch(*userCtx)
return generateMessageResearch(*userCtx)
}
} else if strings.ToLower(messageText) == "/recommencer" {
if userCtx.state == EndSearch {
userCtx.state = Searching
go launchSearch(*userCtx)
return generateMessageResearch(*userCtx)
} else {
return "Veuillez initier une nouvelle recherche avant de la redémarrer."
}
}
log.Printf("Invalid input from user " + strconv.FormatInt(userCtx.chatId, 10))
return "Je n'ai pas bien compris. 😕"
}
func generateMessageResearch(userCtx UserContext) string {
var typeSearch string
if userCtx.searchType == Flex {
typeSearch = "flex"
} else if userCtx.searchType == Station {
typeSearch = "station"
}
roundedKmMargin := int(userCtx.kmMargin)
message := fmt.Sprintf("🔍 Recherche d'un véhicule %s dans un rayon de %dkm autour de la position que vous avez entrée. Vous recevrez un message lorsque l'un sera trouvé.", typeSearch, roundedKmMargin)
if userCtx.searchType == Station {
message += fmt.Sprintf(" de %s a %s", userCtx.dateStart.Format(layoutDate), userCtx.dateEnd.Format(layoutDate))
}
return message
}
func launchSearch(userCtx UserContext) {
var currentCoordinate communautofinder.Coordinate = communautofinder.New(userCtx.latitude, userCtx.longitude)
ctx, cancel := context.WithCancel(context.Background())
cancelSearchingMethod[userCtx.chatId] = cancel
if userCtx.searchType == Flex {
go communautofinder.SearchFlexCarForGoRoutine(cityId, currentCoordinate, userCtx.kmMargin, resultChannel[userCtx.chatId], ctx, cancel)
log.Printf("Searching a flex vehicule for user " + strconv.FormatInt(userCtx.chatId, 10))
} else if userCtx.searchType == Station {
go communautofinder.SearchStationCarForGoRoutine(cityId, currentCoordinate, userCtx.kmMargin, userCtx.dateStart, userCtx.dateEnd, resultChannel[userCtx.chatId], ctx, cancel)
log.Printf("Searching a station vehicule for user " + strconv.FormatInt(userCtx.chatId, 10))
}
nbCarFound := <-resultChannel[userCtx.chatId]
var msg tgbotapi.MessageConfig
if nbCarFound != -1 {
msg = tgbotapi.NewMessage(userCtx.chatId, fmt.Sprintf("💡 Trouvé ! %d véhicule(s) disponible(s) selon vos critères de recherche.", nbCarFound))
log.Printf("Found vehicule(s) for user " + strconv.FormatInt(userCtx.chatId, 10))
} else {
msg = tgbotapi.NewMessage(userCtx.chatId, "😞 Une erreur est survenue dans vos critères de recherche. Veuillez lancer une nouvelle recherche.")
log.Printf("Search failure for user " + strconv.FormatInt(userCtx.chatId, 10))
}
bot.Send(msg)
mutex.Lock()
newUserCtx := userContexts[userCtx.chatId]
newUserCtx.state = EndSearch
userContexts[newUserCtx.chatId] = newUserCtx
mutex.Unlock()
delete(cancelSearchingMethod, userCtx.chatId)
}