-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
executable file
·194 lines (178 loc) · 7.85 KB
/
index.js
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
#!/usr/bin/env node
const Promise = require('bluebird');
const debug = require('debug')('pogono');
const fs = require('fs');
const path = require('path');
const request = require('request-promise');
const moment = require('moment');
const _ = require('lodash');
const errors = require('request-promise/errors');
const args = require('./args.js');
const config = _.assign({
filteredPokemonIds: null,
filteredAddressKeywords: null,
trustedUserId: null,
minLatitude: 24.783617562869416,
maxLatitude: 24.82740393838965,
minLongitude: 120.93629837036131,
maxLongitude: 121.0129451751709,
queryInterval: 10000,
telegramChatId: null,
telegramBotToken: null,
telegramBotEnable: false,
telegramTimeout: 30000,
source: 'pokeradar',
poGoMapAPI: null,
IVMoveEnable: true,
IVPokemonIds: null,
minIVPerfection: 0,
}, require(path.resolve(args.config)));
if (config.centerLatitude && config.centerLongitude && config.nearbyDistance) {
config.minLatitude = config.centerLatitude - config.nearbyDistance/110.574;
config.maxLatitude = config.centerLatitude + config.nearbyDistance/110.574;
config.minLongitude = config.centerLongitude - config.nearbyDistance/(111.32 * Math.cos(config.centerLatitude / 180 * Math.PI));
config.maxLongitude = config.centerLongitude + config.nearbyDistance/(111.32 * Math.cos(config.centerLatitude / 180 * Math.PI));
};
const retry = require('./retry');
const TelegramBot = require('./telegram_bot.js');
const pokemonNames = require('./pokemon_names.js');
const pokemonMoves = require('./pokemon_moves.js');
const pokemonStickers = require('./stickers.js');
const getReverseGeocode = require('./get_reverse_geocode.js');
const messageTemplate = fs.readFileSync('./templates/message.md.template', 'utf-8');
const ivMoveTemplate = fs.readFileSync('./templates/iv_move.md.template', 'utf-8');
retry.setDefaults({
max_tries: 5
}, {
timeout: config.telegramTimeout,
backoff: 1.5
});
let telegramBot = config.telegramBotEnable ? new TelegramBot(config) : null;
let sentPokemons = [];
const replace = function(template, replacements) {
for (let placeholder in replacements) {
template = template.replace(new RegExp(`{${placeholder}}`, 'g'), replacements[placeholder]);
}
return template;
}
const generateMessage = function(pokemon) {
let iv_move = '';
let should_display = _.reduce([
pokemon.individualAttack,
pokemon.individualDefense,
pokemon.individualStamina,
pokemon.move1,
pokemon.move2
], function(sum, c) {
return sum && !_.isNil(c) && !_.isNaN(c);
}, true);
if (config.IVMoveEnable && should_display) {
iv_move = replace(ivMoveTemplate, {
individual_attack: pokemon.individualAttack,
individual_defense: pokemon.individualDefense,
individual_stamina: pokemon.individualStamina,
iv_perfection: pokemon.IVPerfection,
move_1_en: pokemon.move1.en,
move_2_en: pokemon.move2.en,
move_1_zh: pokemon.move1.zh,
move_2_zh: pokemon.move2.zh
});
}
return replace(messageTemplate, {
pokemon_id: pokemon.pokemonId,
pokemon_name_zh: pokemon.pokemonName.zh,
pokemon_name_en: pokemon.pokemonName.en,
address_components: pokemon.reverseGeocode.components.map((x) => '#' + x).join(' '),
address: pokemon.reverseGeocode.formatted_address,
remaining_time: pokemon.remainingTime.format('mm:ss'),
direction: pokemon.direction,
until: pokemon.until.format('YYYY-MM-DD HH:mm:ss'),
iv_move: iv_move
});
}
const pushNotifications = function(pokemons) {
sentPokemons = _.filter(sentPokemons, (s) => s.until.isAfter(moment()));
// remove sent pokemons
debug('fetch', 'fetch pokemons from the provider:', pokemons.length, 'pokemons left');
let filteredPokemons = _.filter(pokemons, function (p) {
return !_.find(sentPokemons, (s) => p.uniqueId == s.uniqueId) && p.remainingTime.diff(moment.utc(0)) > 0;
});
debug('filter', 'filter by sent pokemons:', filteredPokemons.length, 'pokemons left');
if (config.IVPokemonIds !== null) {
filteredPokemons = _.filter(filteredPokemons, function(pokemon) {
if (config.IVPokemonIds === 'all') {
return pokemon.IVPerfection >= config.minIVPerfection;
} else {
return !_.includes(config.IVPokemonIds, pokemon.pokemonId) || pokemon.IVPerfection >= config.minIVPerfection;
}
});
}
debug('filter', 'filter by IV', filteredPokemons.length, 'pokemons left');
debug('get reverse geocode');
return Promise.each(filteredPokemons, function(p) {
return getReverseGeocode(p.latitude, p.longitude)
.then((reverseGeocode) => p.reverseGeocode = reverseGeocode);
})
.then(function filterByAddressKeywords() {
filteredPokemons = _.filter(filteredPokemons, function(p) {
if (config.filteredAddressKeywords) {
let keywords = _.isArray(config.filteredAddressKeywords) ? config.filteredAddressKeywords : [config.filteredAddressKeywords];
for (let keyword of keywords) {
if (p.reverseGeocode.formatted_address.includes(keyword) || p.reverseGeocode.components.join(',').includes(keyword)) {
return true;
}
}
sentPokemons.push(p);
return false;
}
return true;
});
debug('filter', 'filter by address keywords', config.filteredAddressKeywords, ':', filteredPokemons.length, 'pokemons left');
debug('notify', filteredPokemons.length, 'pokemons');
return filteredPokemons;
})
.each(function(p) {
let message = generateMessage(p);
console.log(moment().format(), 'message:', message);
if (config.telegramBotEnable && telegramBot && config.telegramChatId) {
// push a notification
return Promise.resolve()
.then(() => retry(() => telegramBot.sendSticker(config.telegramChatId, pokemonStickers[p.pokemonId], { disable_notification: true })))
.then(() => retry(() => telegramBot.sendLocation(config.telegramChatId, p.latitude, p.longitude, { disable_notification: true })))
.then(() => retry(() => telegramBot.sendMessage(config.telegramChatId, message, { parse_mode: 'Markdown' })))
.then(() => sentPokemons.push(p))
.catch(function(err) {
console.error(moment().format(), 'telegram bot error:', err.message);
})
} else {
sentPokemons.push(p);
}
});
}
let Provider = require('./providers/' + config.source);
let provider = new Provider(config);
debug('request loop starts');
provider
.init()
.then(function requestLoop() {
return provider
.getPokemons()
.then(pushNotifications)
.catch(errors.StatusCodeError, function (reason) {
console.error(moment().format(), 'status code error:', reason.message);
})
.catch(errors.RequestError, function (reason) {
console.error(moment().format(), 'request error:', reason.message);
})
.catch(SyntaxError, function(reason) {
console.error(moment().format(), 'syntax error:', reason.message);
})
.delay(config.queryInterval)
.then(requestLoop);
})
.catch(function(reason) {
console.error(moment().format(), reason);
// TODO: use TelegramBot#stopPolling instead
telegramBot._polling.abort = true;
console.error('the program has been terminated')
});