"use strict";

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const requireAll = require('require-all');
const TelegramBot = require('node-telegram-bot-api');
const GitHubNotifications = require('./services/GitHubNotifications');
const User = require('./models/User');
const BOT_COMMANDS = requireAll({dirname: `${__dirname}/commands`});
const app = express();

if (!process.env.TELEGRAM_BOT_TOKEN) throw new Error('You must provide TELEGRAM_BOT_TOKEN');
if (!process.env.MONGODB_URI) throw new Error('You must provide MONGODB_URI');
if (!process.env.PORT) throw new Error('You must provide PORT');

const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, {polling: process.env.NODE_ENV !== 'production'});
if (process.env.NODE_ENV === 'production') bot.setWebHook(`https://telegram-bot-github.herokuapp.com/${bot.token}`);

Object.keys(BOT_COMMANDS).forEach(command => BOT_COMMANDS[command](bot));

app.use(bodyParser.json());
app.get(`/`, (req, res) => res.redirect('http://telegram.me/GitHubNotificationsBot'));
app.post(`/${process.env.TELEGRAM_BOT_TOKEN}`, (req, res) => {
  bot.processUpdate(req.body);
  res.sendStatus(200);
});
app.listen(process.env.PORT);

mongoose.connect(process.env.MONGODB_URI);

User.find({}, (error, users) => {
  if (error) throw new Error(error);

  users.forEach(user => {
    new GitHubNotifications(user.username, user.token).on('notification', data => {
      bot.sendMessage(user.telegramId, `${data}`);
    });
  });
});

@@ -328,24 +328,71 @@
 els/User');%0A
+const MESSAGES = require('./common/messages');%0A
 const BOT_CO
@@ -448,16 +448,16 @@
 nds%60%7D);%0A
-
 const ap
@@ -863,16 +863,20 @@
 uction')
+ %7B%0A 
  bot.set
@@ -940,17 +940,49 @@
 token%7D%60)
-;
+%0A%7D else %7B%0A  bot.setWebHook('');%0A%7D
 %0A%0AObject
@@ -1463,20 +1463,16 @@
 %3E %7B%0A    
-new 
 GitHubNo
@@ -1482,16 +1482,26 @@
 ications
+.subscribe
 (user.us
@@ -1519,16 +1519,23 @@
 r.token)
+%0A      
 .on('not
@@ -1550,23 +1550,23 @@
 n', 
-data =%3E %7B%0A     
+notification =%3E
  bot
@@ -1602,22 +1602,114 @@
  %60$%7B
-data%7D%60);
+notification%7D%60))
 %0A    
-%7D
+  .once('unauthorized', () =%3E bot.sendMessage(user.telegramId, MESSAGES.UNAUTHORIZED)
 );%0A 

Fix issue with setting webhook