-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathService.js
More file actions
331 lines (296 loc) · 12.5 KB
/
Service.js
File metadata and controls
331 lines (296 loc) · 12.5 KB
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
import axios from 'axios';
import csv from 'csv-parser'
import fs from 'fs'
import {City, User} from './Models.js'
class Service {
constructor() {
this.apiCityUrl = 'https://nominatim.openstreetmap.org/search/'
this.apiCityParams = '?format=json&addressdetails=1&limit=1&accept-language=ru&extratags=1'
this.redundantLetters = ['ь', 'ъ', 'ы']
this.currentGames = []
this.currentLetter = {}
this.usedWords = {}
this.usedWordsByUser = {}
}
async getAnswer(message) {
try {
const { chat, text } = message
const checkInputCommands = await this.checkInputCommands(message)
if (checkInputCommands) {
return checkInputCommands
}
this.checkExistingData(chat.id)
const city = text.toLowerCase()
const checkInputCity = this.checkInputCity(chat.id, city)
if (checkInputCity) {
return checkInputCity
}
const response = await City.findOne({name: {$regex: this.getRegex(`^${city}$`)}})
if (response) {
const name = response.name.toLowerCase()
this.usedWords[chat.id].push(name)
this.usedWordsByUser[chat.id].push(name)
const reverseName = name.split('').reverse().join('')
// бот отправляет свой город
for (let char of reverseName) {
if (!this.redundantLetters.includes(char)) {
return await this.findAndSendNewCity(chat.id, char)
}
}
}
return 'Такого города нет! Введите другой'
} catch (e) {
console.log(e)
}
}
async findAndSendNewCity(chatId, char) {
let cities = await City.find({name: {$nin: this.usedWords[chatId], $regex: this.getRegex(`^${char}`)}})
if (cities && cities.length > 0) {
const numbersOfCities = cities.length
const randomNumber = Math.floor(Math.random() * numbersOfCities)
const cityName = cities[randomNumber].name
const reverseCityName = cityName.split('').reverse().join('')
for (let char of reverseCityName) {
if (!this.redundantLetters.includes(char)) {
const remainCities = await City.find({name: {$nin: this.usedWords[chatId], $regex: this.getRegex(`^${char}`)}})
if (remainCities && remainCities.length === 0) {
this.currentGames = this.currentGames.filter(game => game !== chatId)
this.resetData(chatId)
return `${cityName}\nВы проиграли! Города на букву '${char.toUpperCase()}' закончились\nЧтобы начать новую игру, введите команду /go`
}
this.usedWords[chatId].push(cityName.toLowerCase())
this.currentLetter[chatId] = char
return cityName
}
}
}
this.currentGames = this.currentGames.filter(game => game !== chatId)
this.resetData(chatId)
return `Вы выиграли! Города на букву '${char.toUpperCase()}' закончились\nЧтобы начать новую игру, введите команду /start`
}
checkInputCity(chatId, city) {
if (this.currentLetter[chatId] && this.currentLetter[chatId] !== city.charAt(0)) {
return `Вам нужно ввести город на букву '${this.currentLetter[chatId].toUpperCase()}'`
}
if (this.usedWords[chatId].includes(city)) {
return 'Этот город уже был!'
}
return false
}
async checkInputCommands(message) {
let result
if (this.currentGames.includes(message.chat.id)) {
result = await this.checkGameCommands(message)
} else {
result = await this.checkOutGameCommands(message)
}
return result
}
async checkGameCommands({ chat, text }) {
let result = false
switch (text) {
case '/go':
result = 'Хотите начать игру заного? Введите команду /restart'
break
case '/restart':
await this.changeGamesCount(chat.id)
await this.changeWordsCount(chat.id)
this.resetData(chat.id)
result = 'Давай по новой:) Первый город?'
break
case '/stop':
await this.changeWordsCount(chat.id)
this.currentGames = this.currentGames.filter(game => game !== chat.id)
this.resetData(chat.id)
result = 'Я ушел отдохнуть... Зови, как будешь свободен'
break
case '/words':
if (this.usedWords[chat.id] && this.usedWords[chat.id].length > 0) {
let words = 'Список использованных городов:'
let arrWords = [...this.usedWords[chat.id]]
arrWords.sort().forEach((word, index) => words += `\n${index + 1}. ${this.capitalizeCity(word)}`)
result = words
} else {
result = 'Еще ни одного города не было упомянуто!'
}
break
case '/city':
let message = ''
if (this.usedWords[chat.id]) {
const numberOfWords = this.usedWords[chat.id].length
const info = await this.getCityInfo(this.usedWords[chat.id][numberOfWords - 1])
if (typeof info === 'object') {
Object.keys(info).forEach(key => {
message += `\n${info[key]}`
})
} else {
message = info
}
} else {
message = 'Еще ни одного города не было упомянуто!'
}
result = message
break
case '/watch':
let commands = 'Доступные команды:'
this.getCommands(true).forEach(command => commands += `\n${command.command} - ${command.description}`)
result = commands
break
case '':
result = 'Введите город или доступную команду! Список доступных команд /watch'
}
return result
}
async checkOutGameCommands({ from, chat, text }) {
let result
switch (text) {
case '/start':
await this.getUserInfo(chat.id)
result = 'Приветствую тебя в игре "Города"!\n/go - Начать игру \n/watch - Список доступных команд'
break
case '/go':
this.currentGames.push(chat.id)
await this.changeGamesCount(chat.id)
result = 'Да начнется игра! Скажи свой первый город'
break
case '/info':
const { first_name, last_name } = from
const user = await this.getUserInfo(chat.id)
result = this.showUserInfo(user, first_name, last_name)
break
case '/watch':
let commands = 'Доступные команды:'
this.getCommands(false).forEach(command => commands += `\n${command.command} - ${command.description}`)
result = commands
break
default:
result = 'Неизвестная команда. Список доступных команд /watch'
}
return result
}
async getCityInfo(city) {
const { data } = await axios.get(this.apiCityUrl + encodeURIComponent(city) + this.apiCityParams)
if (data && data.length) {
const { address, extratags, lat, lon } = data.shift()
const { city: cityName, country } = address
if (cityName && cityName.toLowerCase() !== city) {
return 'Не удалось получить информацию по городу ' + this.capitalizeCity(city)
}
return {
city: `Город: ${cityName || this.capitalizeCity(city)}`,
country: `Страна: ${country || 'Неизвестно'}`,
population: `Население: ${extratags.population ? Number(extratags.population).toLocaleString('ru-RU') : 'Неизвестно'}`,
lat: `Широта: ${lat || 'Неизвестно'}`,
lon: `Долгота: ${lon || 'Неизвестно'}`
}
}
return 'Не удалось получить информацию по городу ' + this.capitalizeCity(city)
}
async getUserInfo(id) {
let user = await User.findOne({user_id: String(id)})
if (!user) {
user = new User({
user_id: String(id),
games_count: 0,
words_count: 0
})
await user.save()
}
return user
}
showUserInfo(user, firstName, lastName) {
return `Данные профиля:\nИмя: ${firstName}\nФамилия: ${lastName}\nКоличество сыгранных игр: ${user['games_count']}\nКоличество сыгранных слов: ${user['words_count']}`
}
async changeGamesCount(id) {
if (this.usedWordsByUser[id]) {
await User.updateOne({
user_id: String(id)
}, {
$inc: {games_count: 1}
})
}
}
async changeWordsCount(id) {
if (this.usedWordsByUser[id]) {
await User.updateOne({
user_id: String(id)
}, {
$inc: {words_count: this.usedWordsByUser[id].length}
})
}
}
checkExistingData(chatId) {
if (!this.currentLetter.hasOwnProperty(chatId)) {
this.currentLetter[chatId] = ''
this.usedWords[chatId] = []
this.usedWordsByUser[chatId] = []
}
}
getRegex(rule) {
return new RegExp(rule, 'i');
}
resetData(chatId) {
delete this.currentLetter[chatId]
delete this.usedWords[chatId]
delete this.usedWordsByUser[chatId]
}
capitalizeCity(city) {
return city.charAt(0).toUpperCase() + city.slice(1)
}
getCommands(state) {
if (state) {
return [
{
command: '/restart',
description: 'Перезапустить игру'
},
{
command: '/stop',
description: 'Закончить игру'
},
{
command: '/words',
description: 'Использованные слова'
},
{
command: '/city',
description: 'Получить информацию о последнем городе'
}
]
}
return [
{
command: '/go',
description: 'Новая игра'
},
{
command: '/info',
description: 'Профиль'
}
]
}
// функция для записи информации из csv в базу данных
async writeToDB(data) {
for (let i = 0; i < data.length; i++) {
const city = new City({
name: data[i]
})
await city.save()
}
}
// функция для чтения csv
convertData() {
const key = 'city_id";"country_id";"region_id";"name'
const results = []
fs.createReadStream('data.csv', { encoding: 'utf-8' })
.pipe(csv())
.on('data', data => {
const value = data[key].split(';').pop().replace('"', '')
return results.push(value)
})
.on('end', async () => {
await this.writeToDB(results)
});
}
}
export default Service