-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
346 lines (304 loc) · 11.8 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main
import (
"encoding/base64"
"fmt"
sentry "github.com/getsentry/sentry-go"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/rredkovich/amazingMafiaBotTG/game"
"github.com/rredkovich/amazingMafiaBotTG/types"
"io/ioutil"
"log"
"os"
"strconv"
"time"
)
func main() {
release := os.Getenv("RELEASE_VERSION")
envConfig := os.Getenv("ENV_CONFIG")
botLink := ""
if envConfig == "production" {
botLink = "https://t.me/amafia_bot"
} else {
botLink = "https://t.me/alpha_amafia_bot"
}
if sentryDSN := os.Getenv("SENTRY_DSN"); sentryDSN != "" {
sentry.Init(sentry.ClientOptions{
Dsn: sentryDSN,
Release: release,
Environment: envConfig,
})
defer sentry.Recover()
defer sentry.Flush(time.Second * 5)
}
note, err := ioutil.ReadFile("templates/release_notes.txt")
games := make(map[int64]*game.Game)
votes := make(map[string]*Vote)
tgVotes := make(map[string]*TGVoteValue)
messagesFromGames := make(chan game.GameMessage)
voteCommandsFromGames := make(chan *game.VoteCommand)
bot, err := tgbotapi.NewBotAPI(os.Getenv("TG_API_TOKEN"))
if err != nil {
panic(err) // You should add better error handling than this!
}
bot.Debug = false // Has the library display every request and response.
log.Printf("Mafia bot has been started, ver: %+v, env: %+v\n", release, envConfig)
log.Printf("Authorized on account: %+v\n", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 10
updatesCh, err := bot.GetUpdatesChan(u)
for {
select {
case cmd := <-voteCommandsFromGames:
voteKey := fmt.Sprintf("%+v_%v", cmd.GameChatID, cmd.VoteAvailability)
log.Printf("Got vote command %+v\n", cmd)
switch cmd.Action {
case game.StartVoteAction:
vote := NewVoteFromVoteCommand(cmd, voteKey, botLink)
votes[voteKey] = vote
voteMsgs := vote.StartVote(tgVotes)
for _, voteMsg := range voteMsgs {
_, err := bot.Send(voteMsg)
if err != nil {
msg := fmt.Sprintf("Cannot send vote message! \n%+v\n%+v\n", voteMsg, err)
log.Print(msg)
sentry.CaptureMessage(msg)
}
}
case game.StopVoteAction:
vote := votes[voteKey]
result := vote.EndVote()
log.Printf("Setting result '%+v' for vote %+v:'%+v'", result, voteKey, vote.VoteText)
// TODO make a better solution to handle votes without final decision - when two options-Values have same votes amount
if result == nil && vote.VoteAvailability == game.VoteAvailabilityEnum.Lynch {
msg := tgbotapi.NewMessage(vote.GameChatID, "Жители-недожители не смогли определиться, мафия сможет, ночь уже близко")
bot.Send(msg)
}
cmd.SetResult(result, true)
delete(votes, voteKey)
}
case msg := <-messagesFromGames:
//log.Printf("Games: %+v\n", games)
//log.Printf("Got GameMessage %+v\n", msg)
tgMsg := tgbotapi.NewMessage(msg.ChatID, msg.Message)
tgMsg.ParseMode = "html"
_, err = bot.Send(tgMsg)
if err != nil {
msg := fmt.Sprintf("Got error on send! %+v\n", err)
log.Print(msg)
sentry.CaptureException(err)
}
// handling case when game for chat has been stopped and we received last message with results
game, ok := games[msg.ChatID]
if !ok {
continue
}
if game.State.IsStopped() {
delete(games, msg.ChatID)
}
case update := <-updatesCh:
//log.Printf("Games: %+v\n", games)
// command execution from voting
if update.CallbackQuery != nil {
//log.Printf("VOTE ENUM %s", game.VoteActionEnum.Start)
//log.Printf("%+v\n", update.CallbackQuery)
tgVote, ok := tgVotes[update.CallbackQuery.Data]
if !ok {
fmt.Printf("Cannot get vote by callback query '%+v'", update.CallbackQuery.Data)
bot.AnswerCallbackQuery(tgbotapi.NewCallback(update.CallbackQuery.ID, "😱"))
toDelete := tgbotapi.NewDeleteMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Message.MessageID)
bot.DeleteMessage(toDelete)
bot.Send(tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, "Вы попробовали проголосовать в уже несуществующем голосовании, но слишком поздно!"))
continue
}
vote := votes[tgVote.VoteID]
delete(tgVotes, update.CallbackQuery.Data)
// user tries to access old vote, already deleted from game
if vote == nil {
bot.AnswerCallbackQuery(tgbotapi.NewCallback(update.CallbackQuery.ID, "😱"))
toDelete := tgbotapi.NewDeleteMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Message.MessageID)
bot.DeleteMessage(toDelete)
bot.Send(tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, "Вы попробовали проголосовать в уже несуществующем голосовании, но слишком поздно!"))
continue
}
var answerText string
err := vote.RegisterVote(update.CallbackQuery.From, tgVote.Value)
if err != nil {
answerText = fmt.Sprintf("%+v", err)
} else {
answerText = fmt.Sprintf("Вы выбрали @%+v", tgVote.Value)
}
bot.AnswerCallbackQuery(tgbotapi.NewCallback(update.CallbackQuery.ID, "👌"))
bot.Send(tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, answerText))
switch vote.VoteAvailability {
case game.VoteAvailabilityEnum.Mafia:
if !vote.EveryBodyVoted() {
continue
}
msg := tgbotapi.NewMessage(vote.GameChatID, "<b>Мафия</b> выбрала жертву")
msg.ParseMode = "html"
bot.Send(msg)
case game.VoteAvailabilityEnum.Doctor:
msg := tgbotapi.NewMessage(vote.GameChatID, "<b>Доктор</b> достал бинты и мазь")
msg.ParseMode = "html"
bot.Send(msg)
case game.VoteAvailabilityEnum.Commissar:
msg := tgbotapi.NewMessage(vote.GameChatID, "<b>Комиссар Каттани</b> притворился петуньей в горшке у дома подозреваемого...")
msg.ParseMode = "html"
bot.Send(msg)
case game.VoteAvailabilityEnum.Lynch:
msg := tgbotapi.NewMessage(vote.GameChatID, fmt.Sprintf("%+v выбрал @%+v", InlineName(update.CallbackQuery.From), tgVote.Value))
msg.ParseMode = "html"
bot.Send(msg)
}
toDelete := tgbotapi.NewDeleteMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Message.MessageID)
_, _ = bot.DeleteMessage(toDelete)
continue
}
// ignore any non-Message Updates
if update.Message == nil {
continue
}
//log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
switch update.Message.IsCommand() {
case true:
switch game.CommandType(update.Message.Command()) {
case game.LaunchNewGame:
gameID := update.Message.Chat.ID
// TODO test cannot start game if started
// TODO /notify "game already started" if '/game' received again
g, ok := games[gameID]
if ok && !g.State.IsStopped() {
tgMsg := tgbotapi.NewMessage(g.ChatID, "Уже есть активная игра")
_, err = bot.Send(tgMsg)
continue
}
if ok && g.State.IsStopped() {
delete(games, gameID)
}
gameIDStr := strconv.AppendInt([]byte(""), gameID, 10)
encodedGameID := base64.StdEncoding.EncodeToString([]byte(gameIDStr))
kbd := tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonURL(
"Присоединиться",
fmt.Sprintf(botLink+"?start=%+v", encodedGameID),
),
),
)
from := update.Message.From
starter := types.NewTGUser(from.ID, from.UserName, from.FirstName, from.LastName)
prepareTime := uint32(45)
game := game.NewGame(update.Message.Chat.ID, update.Message.Chat.Title, starter,
&messagesFromGames, voteCommandsFromGames)
games[game.ChatID] = game
go game.Play(prepareTime)
log.Printf("Created game: %+v\n", game)
msg := tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("Ведется набор в игру, старт через <b>%+v</b> секунд\n\nВерсия бота: <b>%+v</b>\n\n%s", prepareTime, release, note))
msg.ParseMode = "html"
msg.ReplyMarkup = kbd
_, err = bot.Send(msg)
if err != nil {
sentry.CaptureException(err)
}
case game.EndGame:
game, ok := games[update.Message.Chat.ID]
if !ok {
continue
}
// TODO test game removed from games when '/endGame' received
delete(games, game.ChatID)
game.Stop()
log.Printf("Stopped game: %+v\n", game)
tgMsg := tgbotapi.NewMessage(game.ChatID, "Игра остановлена")
_, err = bot.Send(tgMsg)
if err != nil {
log.Printf("Got error on send! %+v\n", err)
sentry.CaptureException(err)
}
case game.Start:
// Expecting new user trying to add himself to the game
//"/start -1001256382007"
if update.Message.Text == "/start" {
continue
}
receivedEncodedGameID := update.Message.Text[7:]
var decodedByte, _ = base64.StdEncoding.DecodeString(receivedEncodedGameID)
decodedGameID, err := strconv.ParseInt(string(decodedByte), 10, 64)
if err != nil {
fmt.Printf("Cannot parce game ID on start: %+v\n", err)
sentry.CaptureException(err)
continue
}
fmt.Printf("Got game id %+v\n", decodedGameID)
startedGame, ok := games[decodedGameID]
if !ok {
gameDead := tgbotapi.NewMessage(update.Message.Chat.ID, "Игры нет, возможно закончилась?..")
_, err = bot.Send(gameDead)
if err != nil {
sentry.CaptureException(err)
}
continue
}
from := update.Message.From
err = startedGame.AddMember(types.NewTGUser(from.ID, from.UserName, from.FirstName, from.LastName))
var answer tgbotapi.MessageConfig
if err != nil {
answer = tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("%+v", err))
} else {
answer = tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("Вы присоединились к игре в <b>%+v</b>", startedGame.ChatTitle))
answer.ParseMode = "html"
text := fmt.Sprintf("[%+v %+v](tg://user?id=%+v) в игре, всего %+v", from.FirstName, from.LastName, from.ID, startedGame.MembersCount())
announcement := tgbotapi.NewMessage(startedGame.ChatID, text)
announcement.ParseMode = "markdown"
_, err = bot.Send(announcement)
if err != nil {
sentry.CaptureException(err)
}
}
_, err = bot.Send(answer)
if err != nil {
sentry.CaptureException(err)
}
case game.ExtendRegistrationTime:
game, ok := games[update.Message.Chat.ID]
if !ok {
continue
}
toStart, err := game.ExtendRegistration(30)
if err != nil {
bot.Send(tgbotapi.NewMessage(game.ChatID, fmt.Sprintf("%+v", err)))
} else {
bot.Send(tgbotapi.NewMessage(game.ChatID, fmt.Sprintf("Игра начнется через %+v секунд", toStart)))
}
}
toDelete := tgbotapi.NewDeleteMessage(update.Message.Chat.ID, update.Message.MessageID)
_, err = bot.DeleteMessage(toDelete)
if err != nil {
sentry.CaptureException(err)
}
case false:
game, ok := games[update.Message.Chat.ID]
if !ok {
for _, g := range games {
g.ProcessInGameDirectMessage(update.Message.From.UserName, update.Message.Text)
}
continue
}
if !game.UserCouldTalk(update.Message.From.UserName) {
dcfg := tgbotapi.NewDeleteMessage(update.Message.Chat.ID, update.Message.MessageID)
bot.DeleteMessage(dcfg)
if err != nil {
sentry.CaptureException(err)
}
}
}
}
}
}
func InlineName(u *tgbotapi.User) string {
if u.FirstName != "" && u.LastName != "" {
return fmt.Sprintf("<a href=\"tg://user?id=%+v\">%+v %+v</a>", u.ID, u.FirstName, u.LastName)
} else {
return fmt.Sprintf("<a href=\"tg://user?id=%+v\">%+v</a>", u.ID, u.FirstName)
}
}