Skip to content

Instantly share code, notes, and snippets.

@edlvj
Last active June 29, 2017 08:53
Show Gist options
  • Save edlvj/3a1ae3e026286d45bae2faaf17f8db64 to your computer and use it in GitHub Desktop.
Save edlvj/3a1ae3e026286d45bae2faaf17f8db64 to your computer and use it in GitHub Desktop.
var request = require('sync-request');
var express = require('express');
var prequest = require('request-promise');
var urlencode = require('urlencode');
var TelegramBot = require('node-telegram-bot-api');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
global.lfktoken;
global.order_id;
global.adress;
global.chat_in_load = false;
global.chat_last_message_date = 0;
global.resp;
var bot = new TelegramBot('token', {polling: true});
var products_page;
const APIURL = 'your domain';
bot.onText(/\/vkorziny(.+)/, function (msg, match) {
var fromId = msg.from.id;
var resp = match[1];
if (global.goods == undefined) {
bot.sendMessage(fromId, "Ошибка авторизации попробуйте снова ввести команду /start");
}
global.goods.push(resp);
prequest.put(APIURL + '/order/0',
{ headers: {'Authorization': global.lfktoken }, body: { 'products_ids': global.goods , 'device_type': 3 }, json: true }).then(
function (feed) {
if (feed.status == true) {
bot.sendMessage(fromId, "Товар добавлен");
}
else
{
bot.sendMessage(fromId, "Ошибка авторизации или товар не найден"); }
}
).catch(function (err) {
bot.sendMessage(fromId, 'Ошибка авторизации попробуйте снова ввести команду /start');
console.error('Failed.', err.statusCode, ' >= 400');
});
});
bot.onText(/\/start/, function (msg) {
var fromId = msg.from.id;
global.goods = [];
global.adress = '';
var opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [
[' \u{1F50D} Поиск'],
[' \u{1F4E6} Корзина'],
[' \u{2753} Помощь']
]
})
};
prequest.post(APIURL + '/auth', { json: true, body: { 'apns_token': '12' } }).then(
function (res) {
if (res.status == true) {
bot.sendMessage(fromId, "Привет я LafkaBot.\nЗдесь ты можешь найти продукты и заказать себе доставку домой в Москве", opts);
global.lfktoken = res.data.token;
}
else { bot.sendMessage(fromId, "Ошибка авторизации. Попробуйте снова."); }
}
);
});
bot.onText(/ ? Поиск/, function (msg) {
var fromId = msg.from.id;
bot.sendMessage(fromId, "Что бы начать поиск введите слово Найди и название товара. Например: Найди огурцы");
});
bot.onText(/Найди (.+)|найди (.+)/, function (msg, match) {
var fromId = msg.from.id;
global.resp = match[1];
GetProducts(global.resp,fromId, products_page = 1 );
});
bot.onText(/\/search (.+)/, function (msg, match) {
var fromId = msg.chat.id;
global.resp = match[1];
GetProducts( global.resp, fromId, products_page = 1);
});
bot.onText(/\/page| ? Еще 3/, function (msg) {
var fromId = msg.from.id;
products_page++;
GetProducts(global.resp, fromId, products_page);
});
function GetProducts(resp, fromId, page) {
var opts = {
reply_markup: JSON.stringify({
keyboard: [
[' \u27A1 Еще 3'],
[' \u{1F4E6} Корзина'],
['Назад']
]
})
};
prequest.get(APIURL + '/catalog?page='+ page +'&limit=3&search='+ urlencode(resp), { json: true }).then(
function (feed) {
if(feed.status == true) {
if (feed.data.items.length != 0 ) {
for( var i = 0; i < feed.data.items.length; i++) {
bot.sendMessage(fromId, feed.data.items[i].fullimage_url + '\n' + feed.data.items[i].title + '\nЦена: ' + feed.data.items[i].price + 'руб. \nДобавить: /vkorziny' + feed.data.items[i].id //,
/* { reply_markup: JSON.stringify({ inline_keyboard: [ [{ text: 'Добавить' , callback_data: feed.data.items[i].id.toString() }] ]}) } */ ) ;
}
bot.sendMessage(fromId, 'Страница №' + page, opts);
if(feed.pagination == page - 1) {
bot.sendMessage(fromId, 'Больше нет страниц', { reply_markup: JSON.stringify({
keyboard: [ [' \u{1F4E6} Заказы'], ['Назад'] ] })} );
}
} else {
bot.sendMessage(fromId, 'Товар не найден. Попробуте снова.');
}
}
}).catch(function (err) {
bot.sendMessage(fromId, 'Ошибка авторизации попробуйте снова ввести команду /start');
console.error('Failed.', err.statusCode, ' >= 400');
});
}
bot.onText(/\/orders| ? Корзина/, function (msg) {
var fromId = msg.from.id;
var opts = {
reply_markup: JSON.stringify({
force_reply: true,
keyboard: [ ['Оформить Заказ'],
['Назад']
]
})
};
prequest.get(APIURL + '/order/0', {
headers: {'Content-Type': 'application/json', 'Authorization': global.lfktoken }, json: true }).then(
function (orders) {
if (orders.status == true) {
var products = showOrderData(orders.data.id);
CheckNewMsg(fromId);
for(var i = 0; i < products.length; i++) {
bot.sendMessage(fromId, products[i].title + '\nЦена: ' + products[i].price + 'руб.');
}
bot.sendMessage(fromId, "Подтвердите пожалуйста ваш телефон. Введите команду /phone <ваш номер телефона>");
bot.sendMessage(fromId, "Заказ №" + orders.data.id + '\nОбщая Цена: ' + orders.data.price + ' руб.', opts);
} else { bot.sendMessage(fromId, "Ошибка авторизации или у вас нет заказов"); }
}
).catch(function (err) {
bot.sendMessage(fromId, 'Ошибка авторизации попробуйте снова ввести команду /start');
console.error('Failed.', err.statusCode, ' >= 400');
});
});
bot.onText(/\/phone (.+)/, function (msg, match) {
var fromId = msg.from.id;
var resp = match[1];
setPhone(fromId ,resp);
});
function setPhone(fromId, phone) {
prequest.get(APIURL + '/me/phone?phone=' + phone, { headers: { 'Authorization': global.lfktoken }, json: true }).then(
function (res) {
if (res.status == true) {
bot.sendMessage(fromId, "Код активации был отправлен на ваш телефон. \nЧто бы подтвердить введите: /verify <код активации>\nНапример: /verify 8246 ");
}
else { bot.sendMessage(fromId, "Ошибка отправки. Попробуйте снова."); }
}
);
bot.onText(/\/verify (.+)/, function (msg, match) {
var resp = match[1];
var opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [
['Оформить Заказ'],
['Назад']
]
})
};
var fromId = msg.from.id;
prequest.post(APIURL + '/me/phone', { headers: { 'Authorization': global.lfktoken }, json: true, body: { 'phone': phone, 'code' : resp } }).then(
function (res) {
console.log(res);
if (res.data.status == true) {
console.log(resp);
bot.sendMessage(fromId, "Ваш телефон успешно добавлен.", opts);
}
else { bot.sendMessage(fromId, "Ошибка код или телефон не был принят. Но вы все также можете создавать заказы.", opts); }
}
);
});
}
bot.onText(/\/help| ? Помощь/, function (msg) {
console.log(msg.chat.id);
var fromId = msg.from.id;
bot.sendMessage(fromId, "/start Создать новый заказ\n/search <название товара> Поиск товаров\n/orders Корзина \n/status Статус Заказа\n/accept Оформить заказ\n/address <улица и номер> Установка адреса \n/phone <номер телефона> Установка телефона \n/chat написать сообщение оператору\n/promo <код> Добавить промокод\n/page Следущая страница товаров");
});
bot.onText(/\/status/, function (msg) {
var fromId = msg.from.id;
var ord_status = { 0: 'Создан', 1: 'Взят в работу шопером', 2: 'Куплен шопером' , 3: 'Отклонен', 4: 'В доставке', 5: 'Доставлен' };
var res = CheckStatus();
bot.sendMessage(fromId, 'Статус заказа : ' + ord_status[ res ] );
});
bot.onText(/\/accept|Оформить Заказ/, function (msg) {
var fromId = msg.from.id;
var opts = {
reply_markup: JSON.stringify({
force_reply: true,
keyboard: [
['Назад']
]
})
};
if (global.adress != '') {
prequest.post(APIURL + '/order' ,
{ headers: {'Authorization': global.lfktoken },
body: {'address': global.adress, 'products_ids': global.goods , 'device_type': 3 } , json: true }).then(
function (feed) {
//console.log(feed);
if (feed.status == true) {
global.order_id = feed.data.id;
bot.sendMessage(fromId, "Заказ создан. Хотите создать новый заказ введите /start\nЧто бы написать в сообщение оператору введите комманду /chat текст.", opts);
//
} else { bot.sendMessage(fromId, "Ошибка авторизации"); }
}).catch(function (err) {
bot.sendMessage(fromId, 'Ошибка авторизации попробуйте снова ввести команду /start');
console.error('Failed.', err.statusCode, ' >= 400');
});
} else {
bot.sendMessage(fromId, "Установите пожалуйста адрес доставки с помощью коман��ы \n/address адрес заказа. Например:/address Гагарина 77");
}
});
bot.onText(/\/address (.+)/, function (msg, match) {
var fromId = msg.from.id;
var resp = match[1];
global.adress = resp;
bot.sendMessage(fromId, "Адрес добавлен. Что бы подтвердить заказ введите комманду /accept .");
});
bot.onText(/\/promo (.+)/, function (msg, match) {
var fromId = msg.from.id;
var resp = match[1];
prequest.get(APIURL + '/promo-code/' + resp, {
headers: {'Content-Type': 'application/json', 'Authorization': global.lfktoken }, json: true }).then(
function (promo) {
if (promo.data.is_used == false) {
bot.sendMessage(fromId, "Промокод добавлен.");
} else { bot.sendMessage(fromId, "Ошибка этот промокод уже был использован."); }
}
).catch(function (err) {
bot.sendMessage(fromId, 'Ошибка авторизации попробуйте снова ввести команду /start');
console.error('Failed.', err.statusCode, ' >= 400');
});
});
bot.onText(/Назад/, function (msg) {
var fromId = msg.from.id;
var opts = {
// reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [
[' \u{1F50D} Поиск'],
[' \u{1F4E6} Корзина'],
[' \u{2753} Помощь']
]
})
};
bot.sendMessage(fromId, "Главное меню", opts);
});
function showOrderData(order) {
var element = [];
var res = request('GET', APIURL + '/shopper/order/' + order, {
'headers': {
'Authorization': 'W-fBLcVzhocPL3VGY7Z2YHQPjenlts-0Qe9Qv-eu2Y6sI4QSlJ'
}
});
var ed = res.getBody('utf-8');
var feed = JSON.parse(ed);
if (feed.status == true) {
for( var i = 0; i < feed.data.products.length; i++)
{
element.push({title: feed.data.products[i].title, image_url: feed.data.products[i].fullimage_url, price: feed.data.products[i].price});
}
}
return element;
}
function CheckNewMsg(fromId) {
var timerId = setInterval(function() {
ConChat(fromId);
}, 10000);
if (CheckStatus() == 5) {
clearInterval(timerId)
}
}
//Соединение к чату
function ConChat(fromId) {
if(global.chat_in_load)
return false;
global.chat_in_load = true;
var res = request('GET', APIURL + '/room/0', {
'headers': {
'Content-Type': 'application/json',
'Authorization': global.lfktoken
}
});
var feed = JSON.parse(res.getBody('utf-8'));
global.chat_in_load = false;
if (feed.status == true) {
for(i in feed.data.items)
{
if (global.chat_last_message_date < Date.parse(feed.data.items[i].date) && feed.data.items[i].is_current_user == false)
{
bot.sendMessage(fromId, feed.data.items[i].text);
global.chat_last_message_date = Date.parse(feed.data.items[i].date);
}
}
} else {
return false;
}
}
function CheckStatus() {
var res = request('GET', APIURL + '/order/0', {
'headers': {
'Content-Type': 'application/json',
'Authorization': 'W-fBLcVzhocPL3VGY7Z2YHQPjenlts-0Qe9Qv-eu2Y6sI4QSlJ'
}
});
var feed = JSON.parse(res.getBody('utf-8'));
if (feed.status == true) {
return feed.data.status;
} else {
return false;
}
}
bot.onText(/\/chat (.+)/, function (msg, match) {
var fromId = msg.from.id;
var resp = match[1];
prequest.post(APIURL + '/room/0', {
headers: { 'Authorization': global.lfktoken }, body:{ text: resp } , json: true }).then(
function (orders) {
if (orders.status == true) {
bot.sendMessage(fromId, "Сообщение отправленно оператору. ");
}
else { bot.sendMessage(fromId, "Нужно создать заказ. Что бы начать чат"); }
}
).catch(function (err) { // Any HTTP status >= 400 falls here
bot.sendMessage(fromId, 'Что бы связаться с оператором, нужно оформить заказ');
console.error('Failed.', err.statusCode, ' >= 400');
});
});
app.use(express.static(__dirname + 'public'))
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.post('/', function (req, res) {
bot.sendMessage(205082226, req.body.mess);
console.log(req.body.mess);
res.end('done');
});
app.get('/users', function(req, res) {
res.sendFile(__dirname + "/public/users.html");
});
app.listen(process.env.PORT, process.env.IP,function(){
console.log("Working");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment