Answer the question
In order to leave comments, you need to log in
Error in running nodejs application?
Tell me what could be wrong, before everything worked fine?
Bot has been started ....
MongoDB has started ...
/home/bot/node_modules/bluebird/js/release/async.js:49
fn = function () { throw arg; };
^
TypeError: Cannot read property '0' of undefined
at Geocoder.<anonymous> (/home/bot/src/index.js:178:11)
at Geocoder.tryCatcher (/home/bot/node_modules/bluebird/js/release/util.js:16:23)
at Promise.errorAdapter [as _rejectionHandler0] (/home/bot/node_modules/bluebird/js/release/nodeify.js:35:34)
at Promise._settlePromise (/home/bot/node_modules/bluebird/js/release/promise.js:601:21)
at Promise._settlePromise0 (/home/bot/node_modules/bluebird/js/release/promise.js:649:10)
at Promise._settlePromises (/home/bot/node_modules/bluebird/js/release/promise.js:725:18)
at _drainQueueStep (/home/bot/node_modules/bluebird/js/release/async.js:93:12)
at _drainQueue (/home/bot/node_modules/bluebird/js/release/async.js:86:9)
at Async._drainQueues (/home/bot/node_modules/bluebird/js/release/async.js:102:5)
at Immediate.Async.drainQueues (/home/bot/node_modules/bluebird/js/release/async.js:15:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node ./src/index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2019-10-17T16_42_24_540Z-debug.log
[[email protected] bot]# cat /root/.npm/_logs/2019-10-17T16_42_24_540Z-debug.log
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle [email protected]~prestart: [email protected]
6 info lifecycle [email protected]~start: [email protected]
7 verbose lifecycle [email protected]~start: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~start: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/bot/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
9 verbose lifecycle [email protected]~start: CWD: /home/bot
10 silly lifecycle [email protected]~start: Args: [ '-c', 'node ./src/index.js' ]
11 silly lifecycle [email protected]~start: Returned: code: 1 signal: null
12 info lifecycle [email protected]~start: Failed to exec start script
13 verbose stack Error: [email protected] start: `node ./src/index.js`
13 verbose stack Exit status 1
13 verbose stack at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack at EventEmitter.emit (events.js:198:13)
13 verbose stack at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:198:13)
13 verbose stack at maybeClose (internal/child_process.js:982:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid [email protected]
15 verbose cwd /home/bot
16 verbose Linux 3.10.0-1062.1.2.el7.x86_64
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
18 verbose node v10.16.2
19 verbose npm v6.9.0
20 error code ELIFECYCLE
21 error errno 1
22 error [email protected] start: `node ./src/index.js`
22 error Exit status 1
23 error Failed at the [email protected] start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
bot.onText(/\/gorod (.+)/, (msg, match) => {
//подключаем пакеты
const TelegramBot= require('node-telegram-bot-api')
const request = require('sync-request')
const config = require('./config')
const helper = require('./helpers')
const keyboard= require('./keyboard')
const kb = require('./keyboard-buttons')
const NodeGeocoder = require('node-geocoder');
const mongoose = require('mongoose');
var Forecast = require('forecast');
var options = {
provider: 'yandex',
// Optional depending on the providers
httpAdapter: 'request', // Default
apiKey: '16de7ae3-9f88-483e-a465-5efebe3kkkkb', // for Mapquest, OpenCage, Google Premier
formatter: null // 'gpx', 'string', ...
};
var geocoder = NodeGeocoder(options);
require('./user.models')
const users = mongoose.model('users')
helper.logStart()
var forecast = new Forecast({
service: 'darksky.net',
key: 'e1b9cb108a1e022d5cfd8jjjjjjjj0e81e0',
units: 'celcius',
lang: 'ru',
cache: true,
ttl: {
minutes: 5
}
});
const bot=new TelegramBot(config.TOKEN,{
polling:{
interval:300,
autoStart:true,
params:{
timeout:10
}
}
})
//Подключаемся к бд
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost/bot', { useNewUrlParser: true ,useUnifiedTopology: true } )
.then(() => console.log('MongoDB has started ...'))
.catch(e => console.log(e))
//Инлайн клавиатура
const inline_keyboard = [
[
{
text: 'Да',
callback_data: 'yes'
},
{
text: 'Нет',
callback_data: 'no'
}
]
]
bot.onText(/\/gorod (.+)/, (msg, match) => {
var resp = match[1];
//пытаемся получить координаты и адрес
var ids= msg.chat.id;
let lat;
let long;
let fullAddress;
let coord;
// Using callback
geocoder.geocode(`${resp}`, function(err, res) {
lat = res[0].latitude;
long = res[0].longitude;
fullAddress = res[0].formattedAddress;
coord = lat + ',' + long;
//Спрашиваем пользователя верно ли мы определели город
//Передаем ему координаты
bot.sendVenue(ids, lat, long,`Верно ли мы определили ваш город?`,`Ваш город: ${fullAddress}`,{
reply_markup:{inline_keyboard}
})
})
//var coor = GetCoords(`${resp}`,ids);
//обрабатываем инлайн клавиатуру
bot.on('callback_query', query => {
const { chat, message_id, text } = query.message
// console.log(chat)
// console.log(coor)
switch (query.data) {
case 'yes':
users.update({ids: `${msg.from.id}`},{$set:{login: `${chat.first_name}`,coords: `${coord}`,fullAddress:`${fullAddress}`}},{upsert:true})
.then(users => {
//проверяем наличие юзера в бд если его нет заносим, иначе обновляем данные
bot.sendMessage(chat.id, 'Ваш город успешно сохранен/изменен',{
reply_markup:{keyboard:keyboard.home,resize_keyboard: true}
})
})
.catch(e => bot.sendMessage(chat.id, 'Неизвестная ошибка, повторите ваш запрос позже'))
break
case 'no':
bot.sendMessage(chat.id, 'Хорошо попробуйте ввести город еще раз\nНапример /gorod Самара,Россия')
break
}
bot.answerCallbackQuery({
callback_query_id: query.id
})
})
});
bot.onText(/\/start/,msg=>{
var text=`Здавствуйте, ${msg.from.first_name} Я покажу погоду в твоем городе.
Пожалуйста, для указания города введите команду /gorod и имя города (например /gorod Самара).
Для точности определения координат можно указать название страны (напр., Россия Москва).
Если по вашему запросу ничего не найдено, попробуйте задать его на английском языке.`;
bot.sendMessage(helper.getChatId(msg), text)
})
//конвертируем дату unix в читаемый вид
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Января','Февраля','Марта','Апреля','Мая','Июня','Июля','Августа','Сентября','Октября','Ноября','Декабря']
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date + ' '+ month + ' ' + year;
// time = date + ':' + month + ':' + year + ' ' + hour + ':' + min + ':' + sec ;
return time;
}
/**
* Получить название текущего дня недели
* @return {String}
*/
function getWeekDay(UNIX_timestamp) {
date = new Date(UNIX_timestamp * 1000);
var days = ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'];
var day = date.getDay();
return days[day];
}
//Convert seconds to time string (hh:mm:ss).
function time(s) {
return new Date(s * 1e3).toISOString().slice(-13, -5);
}
//фильтруем массив на нужные значения
function filterProps(obj) {
let props = ["time","sunriseTime","sunsetTime", "summary", "pressure", "windSpeed", "temperatureHigh", "temperatureLow","humidity"];
let result = {};
for (const p in obj)
{
if (props.indexOf(p) > -1)
{
result[p] = obj[p];
}
}
return result;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question