Last active
November 6, 2016 16:27
-
-
Save Barbayar/6c7c51a7807e7517d2a017f72df8b6b6 to your computer and use it in GitHub Desktop.
Мазаалай Bot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
String.prototype.clearFormat = function() { | |
return this.replace(/<br>/g, '\n').replace(/<i>/g, '').replace(/<\/i>/g, ''); | |
}; | |
String.prototype.wordWrap = function(length) { | |
var words = this.split(' '); | |
var result = []; | |
var current = words[0]; | |
for (var i = 1; i < words.length; i++) { | |
if (words[i].length === 0) { | |
continue; | |
} | |
if (current.length + words[i].length + 1 > length) { | |
result.push(current); | |
current = words[i]; | |
} else { | |
current += ' ' + words[i]; | |
} | |
} | |
result.push(current); | |
return result; | |
} | |
Array.prototype.chunk = function(n) { | |
if (this.length === 0) { | |
return []; | |
} | |
return [this.slice(0, n)].concat(this.slice(n).chunk(n)); | |
}; | |
const request = require('request'); | |
const AWS = require('aws-sdk'); | |
AWS.config.update({ | |
region: 'us-east-1' | |
}); | |
const dynamodb = new AWS.DynamoDB.DocumentClient(); | |
const snowball = new require('snowball')('English'); | |
const PAGE_ACCESS_TOKEN = 'XXXXXXXXX'; | |
function stemmer(word) { | |
snowball.setCurrent(word); | |
snowball.stem(); | |
return snowball.getCurrent(); | |
} | |
function find(stem, callback) { | |
dynamodb.query({ | |
TableName: 'Mazaalai', | |
ConsistentRead: false, | |
KeyConditionExpression: 'stem = :stem', | |
ExpressionAttributeValues: { | |
':stem': stem | |
} | |
}, function(error, data) { | |
if (!error) { | |
callback(data.Items); | |
} | |
}); | |
} | |
function get(word, callback) { | |
dynamodb.get({ | |
TableName: 'Mazaalai', | |
ConsistentRead: false, | |
Key: { | |
stem: stemmer(word), | |
word: word | |
} | |
}, function(error, data) { | |
if (!error) { | |
callback(data.Item); | |
} | |
}); | |
} | |
function createMessageElement(item) { | |
var title = item.word; | |
var subtitle = item.data.clearFormat(); | |
var buttons = null; | |
if (subtitle.length > 80) { | |
subtitle = subtitle.substr(0, 77) + '...'; | |
buttons = [{ | |
type: 'postback', | |
title: 'Дэлгэрэнгүй', | |
payload: JSON.stringify({ | |
command: 'detail', | |
parameter: item.word | |
}) | |
}]; | |
} | |
return { | |
title: title, | |
subtitle: subtitle, | |
buttons: buttons | |
} | |
} | |
function sendResult(recipientId, items) { | |
var data = { | |
recipient: { | |
id: recipientId | |
}, | |
message: { | |
attachment: { | |
type: 'template', | |
payload: { | |
template_type: 'generic', | |
elements: [] | |
} | |
} | |
} | |
} | |
items.forEach(function(item) { | |
data.message.attachment.payload.elements.push(createMessageElement(item)); | |
}); | |
request({ | |
uri: 'https://graph.facebook.com/v2.6/me/messages', | |
qs: { | |
access_token: PAGE_ACCESS_TOKEN | |
}, | |
method: 'POST', | |
json: data | |
}, function (error, response, body) { | |
// TODO: implement later | |
}); | |
} | |
function sendMessage(recipientId, message) { | |
request({ | |
uri: 'https://graph.facebook.com/v2.6/me/messages', | |
qs: { | |
access_token: PAGE_ACCESS_TOKEN | |
}, | |
method: 'POST', | |
json: { | |
recipient: { | |
id: recipientId | |
}, | |
message: { | |
text: message | |
} | |
} | |
}, function (error, response, body) { | |
// TODO: implement later | |
}); | |
} | |
exports.handler = (event, context, callback) => { | |
if (event['body-json'].object !== 'page') { | |
callback('forbidden'); | |
return; | |
} | |
event['body-json'].entry.forEach(function(pageEntry) { | |
pageEntry.messaging.forEach(function(messagingEvent) { | |
if (messagingEvent.message) { | |
find(stemmer(messagingEvent.message.text.split(' ')[0].toLowerCase()), function(items) { | |
if (items.length === 0) { | |
sendMessage(messagingEvent.sender.id, 'Уучлаарай, таны хайсан үг олдсонгүй.'); | |
return; | |
} | |
items.chunk(10).forEach(function (chunkedItems) { | |
sendResult(messagingEvent.sender.id, chunkedItems); | |
}); | |
}); | |
} | |
if (messagingEvent.postback) { | |
var payload = JSON.parse(messagingEvent.postback.payload); | |
var i = 0; | |
if (payload.command === 'detail') { | |
get(payload.parameter, function(item) { | |
item.data.clearFormat().wordWrap(320).forEach(function (chunkedData) { | |
setTimeout(function() { | |
sendMessage(messagingEvent.sender.id, chunkedData); | |
}, 200 * (i++)); // sleeps 200ms between messages to keep order | |
}); | |
}); | |
} | |
} | |
}); | |
}); | |
callback(null, 'success'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment