how to collect data from user with the facebook messenger bot api in node js - chat

I am building a messenger bot in node. I want it to collect user input data and have a conversation or ask questions, but the code I have doesn't work. the part that does not work is it only continues to the next else if block if i type the same code. and second the array is not capturing the text after the first if statement. Is there a better way to do it? Could someone provide code?
My code is below. what i want is like in this iimage:
var currentbot = 0;
var awnswers = [];
app.post('/webhook', function(req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
var text = event.message.text;
if (text == "hi") {
start(event.message.text, event.sender.id);
}
}
}
res.sendStatus(200);
});
var awnswers = [];
function start(text, id) {
if (count == 0) {
sendTextMessage('hello lets order!', id);
arr.push(text);
console.log(awnswers);
count = 1;
} else if (count == 1) {
sendTextMessage('what size do you want?', id);
arr.push(text);
console.log(awnswers);
count = 2;
} else if (count == 2) {
sendTextMessage('its on its way!', id);
arr.push(text);
console.log(awnswers);
count = 0;
}
}
function sendTextMessage(messageText, recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: process.env.access_token
},
method: 'POST',
json: messageData
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}

The main issues I think I see are:
Start() is only called when text == hi
Count is not defined
You're pushing to the array 'arr' not, awnswers
You can fix these by:
Calling start() on every message
Defining count like var count = 0; at the top of your file, next to var currentbot
awnswers.push(text);

Related

Limit size of entered data in tinyMCE 5

I use tinyMCE 5 in my web site to enter data stored in a database. Therefore I need to limit the entered size, including format information, to the size of the data field. How can I prohibit the user to enter more then the allowed number of bytes, say 2000?
Best of all if I could add some information like "42/2000" on the status bar.
We had a similar requirement in our project (difference: the output should be <entered_chars>/<chars_left> instead of <entered_chars>/<max_chars>), and it ended up being a custom plugin, based on the wordcount plugin. There is some hacks in there, which could make it fail whenever tinyMCE changes, since there is no API for the statusbar in version 5 at this point of time.
But maybe you will still find it useful:
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var maxChars = function (editor) {
return editor.getParam('number_max_chars', 3600);
};
var applyMaxChars = function (editor) {
return editor.getParam('restrict_to_max_chars', true);
};
var Settings = {
maxChars: maxChars,
applyMaxChars: applyMaxChars
};
var global$1 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
var getText = function (node, schema) {
var blockElements = schema.getBlockElements();
var shortEndedElements = schema.getShortEndedElements();
var isNewline = function (node) {
return blockElements[node.nodeName] || shortEndedElements[node.nodeName];
};
var textBlocks = [];
var txt = '';
var treeWalker = new global$1(node, node);
while (node = treeWalker.next()) {
if (node.nodeType === 3) {
txt += node.data;
} else if (isNewline(node) && txt.length) {
textBlocks.push(txt);
txt = '';
}
}
if (txt.length) {
textBlocks.push(txt);
}
return textBlocks;
};
var strLen = function (str) {
return str.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '_').length;
};
var countCharacters = function (node, schema) {
var text = getText(node, schema).join('');
return strLen(text);
};
var createBodyCounter = function (editor, count) {
return function () {
return count(editor.getBody(), editor.schema);
};
};
var createMaxCount = function (editor) {
return function () {
return Settings.maxChars(editor);
}
}
var createRestrictToMaxCount = function (editor) {
return function () {
return Settings.applyMaxChars(editor);
}
}
var get = function (editor) {
return {
getCount: createBodyCounter(editor, countCharacters),
getMaxCount: createMaxCount(editor),
getRestrictToMaxCount: createRestrictToMaxCount(editor)
};
};
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
function isAllowedKeycode(event) {
// allow arrow keys, backspace and delete
const key = event.keyCode;
return key === 37 || key === 38 || key === 39 || key === 40 || key === 8
|| key === 46;
}
var updateCount = function (editor, api) {
editor.getContainer().getElementsByClassName(
'tox-statusbar__text-container')[0].textContent = String(
api.getCount()) + " / " + String(
Settings.maxChars(editor) - api.getCount());
};
var setup = function (editor, api, delay) {
var debouncedUpdate = global$2.debounce(function () {
return updateCount(editor, api);
}, delay);
editor.on('init', function () {
updateCount(editor, api);
global$2.setEditorTimeout(editor, function () {
editor.on('SetContent BeforeAddUndo Undo Redo keyup', debouncedUpdate);
editor.on('SetContent BeforeAddUndo Undo Redo keydown', function (e) {
if (!isAllowedKeycode(e) && Settings.applyMaxChars(editor) &&
api.getCount() >= Settings.maxChars(editor)) {
e.preventDefault();
e.stopPropagation();
}
});
}, 0);
});
};
function Plugin(delay) {
if (delay === void 0) {
delay = 300;
}
global.add('charactercount', function (editor) {
var api = get(editor);
setup(editor, api, delay);
return api;
});
}
Plugin();
}());
Currently I'm working on a preprocessor for the paste plugin, so that the max_length effects also pasted text. That's why you see the charactercount API in the code.

Find and Replace Header/Footer text Office JS

I'm having trouble with office js and processing a list of items with lookup codes and replacement values for the header and footer. I've got the body working just not the header/footer. I'm getting this error:0x800a139e - JavaScript runtime error: The property 'items' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context. As you can see I do call load and sync before trying to access the results.
function mergeHeader(documentFieldKeys) {
if (documentFieldKeys.length > 0)
Word.run(function(context) {
var key = documentFieldKeys.shift();
var mySections = context.document.sections;
context.load(mySections, 'body/style');
return context.sync().then(function() {
for (var i = 0; i < mySections.items.length; i++ ) {
findAndReplace(key, context, mySections.items[i].getHeader("primary"));
}
return context.sync().then(function() {
return mergeHeader(documentFieldKeys);
})
.then(context.sync);
});
});
}
function findAndReplace(key, context, body) {
var results = body.search(key.Code, { matchWholeWord: false, matchCase: false });
context.load(results);
return context.sync().then(function() {
if (results.items.length > 0 && key.Value === "") {
missingFields.push(key.Description);
} else {
for (var i = 0; i < results.items.length; i++) {
results.items[i].insertText(key.Value, "replace");
}
}
})
.then(context.sync);
}
Any help would be appreciated.
Add
context.load(mySections, 'items');
or
mySections.load('items');

Github api get last Users that committed

I want to get the last users exe. last 100 users that committed on github regardless of repo. I've looked around the github api but can't find the specific api call.
You can use Github Events API and filter PushEvent :
https://api.github.com/events?per_page=100
User(s) who have made the last 100 commits on Github
As a PushEvent may have multiple commits, you will have to sum the size for each PushEvent until you reach 100. Note that you also need to exclude PushEvent with 0 commit. You will also have to manage pagination as you can request 100 events max at once (if one request is not enough to get 100 commits).
An example using nodeJS :
var request = require("request");
const maxCommit = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var commitCount = 0;
var page = 1;
var users = [];
while (commitCount < maxCommit) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
commitCount += pushEvents.reduce((it1, it2) => it1 + it2.payload.size, 0);
users = users.concat(pushEvents.map(event => ({
login: event.actor.login,
commitCount: event.payload.size
})));
page++;
}
var count = 0;
for (var i = 0; i < users.length; i++) {
count += users[i].commitCount;
if (count >= maxCommit){
users = users.slice(0, i + 1);
break;
}
}
console.log(users);
}
getEvents();
Last 100 Users who have pushed commits on Github
The only things that changes is that we only check that size field is > 0 and build a map for distinct user.
An example using nodeJS :
var request = require("request");
const maxUser = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var page = 1;
var users = {};
while (Object.keys(users).length < maxUser) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
for (var i = 0; i < pushEvents.length; i++) {
users[pushEvents[i].actor.login] = pushEvents[i].payload.size;
if (Object.keys(users).length == maxUser) { 
break;
}
}
page++;
}
console.log(users);
}
getEvents();

How to pass a test if expect fails

I have this code
it('This should pass anyway', function (done) {
testObj.testIt(regStr);
});
testObj
this.testIt = function (regStr) {
selector.count().then(function (orgCount) {
for (var curr = 0; curr < count; curr++) {
checkField(curr, regStr);
}
});
};
function checkField(curr, regStr) {
selector.get(curr).all(by.tagName('li')).get(0).getInnerHtml().then(function (text) {
expect(text).to.match(regStr, curr + '#ERR');
});
}
If one of these expects get a failure, test fails. How can i handle this? I mean - can i somehow count passed and failed expect()ations and return it? or, at least, dont let test break on first error.
I've tried try-catch, but nothing good happened.
it('This should pass anyway', function (done) {
try {
testObj.testIt(regStr);
} catch (e) {
console.log('#err' + e);
}
});
And then i wanted to use done(), but havent found any examples to do the similar. Can u please help me?
Sry for my english
UPD
You can return either null or a string from checkField(), join them up, and expect the array to be empty:
this.testIt = function (regStr) {
selector.count().then(function (orgCount) {
var errors = [];
for (var curr = 0; curr < orgCount; curr++) {
var e = checkField(curr, regStr);
if (e) { errors.push(e); }
}
assert.equal(0, errors.length, errors);
});
};
A cleaner approach would be to use map() to collect the data into an array:
var data = selector.map(function (elm) {
return elm.element(by.tagName('li')).getText();
});
expect(data).toEqual(["test1", "test2", "test3"]);

jQuery/Ajax form success message

I have a couple of forms on a site I'm working on and the script that controls them doesn't include a success message, so when they're submitted the input data just disappears and the user doesn't know if it's been actually sent or not. I've looked around a bit for answers, but because this file controls an email submission form, a contact form, and a twitter feed, it's a bit much for me to see what's what.
Here's the code, I'd just like to let users know that their message has been sent for both the email input form and the contact form. I appreciate any help that's out there!
$(document).ready(function() {
//Set default hint if nothing is entered
setHints();
//Bind JavaScript event on SignUp Button
$('#signUp').click(function(){
signUp($('#subscribe').val());
});
//Bind JavaScript event on Send Message Button
$('#sendMessage').click(function(){
if(validateInput()){
sendMail();
}else
{
alert('Please fill all fields to send us message.');
}
});
//Load initial site state (countdown, twitts)
initialize();
});
var setHints = function()
{
$('#subscribe').attachHint('Enter your email to be notified when more info is available');
$('[name=contact_name]').attachHint('Name');
$('[name=contact_email]').attachHint('Email');
$('[name=contact_subject]').attachHint('Subject');
$('[name=contact_message]').attachHint('Message');
};
var signUp = function(inputEmail)
{
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputEmail)){
isValid = false;
alert('Your email is not in valid format');
}
if(isValid){
var params = {
'action' : 'SingUp',
'email' : inputEmail
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
}
}
}
});
}
};
var initialize = function()
{
var params = {
'action' : 'Initialize'
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('ul.twitts').empty();
if(responseObj.ResponseData.Twitts){
$('a.followUsURL').attr('href','http://twitter.com/#!/'+responseObj.ResponseData.Twitts[0].Name);
$.each(responseObj.ResponseData.Twitts, function(index, twitt){
var twitterTemplate = '<li>'
+ '#{0}'
+ '{2}'
+ '<span class="time">{3}</span>'
+ '</li>';
$('ul.twitts').append(StringFormat(twitterTemplate, twitt.Name, twitt.StatusID, twitt.Text, twitt.Date));
});
}
if(responseObj.ResponseData.Start_Date)
{
setInterval(function(){
var countDownObj = calculateTimeDifference(responseObj.ResponseData.Start_Date);
if(countDownObj){
$('#days').text(countDownObj.Days);
$('#hours').text(countDownObj.Hours);
$('#minutes').text(countDownObj.Minutes);
$('#seconds').text(countDownObj.Seconds);
}
}, 1000);
}
}
}
}
});
};
var validateInput = function(){
var isValid = true;
$('input, textarea').each(function(){
if($(this).hasClass('required'))
{
if($(this).val()!=''){
if($(this).hasClass('email'))
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())){
isValid = false;
alert('Your email is not in valid format');
}
}
}else
{
isValid = false;
}
}
});
return isValid;
};
var resetInput = function(){
$('input, textarea').each(function() {
$(this).val('').text('');
});
};
var sendMail = function(){
var params = {
'action' : 'SendMessage',
'name' : $('[name=contact_name]').val(),
'email' : $('[name=contact_email]').val(),
'subject' : $('[name=contact_subject]').val(),
'message' : $('[name=contact_message]').val()
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
$('label.sendingStatus').text(responseObj.ResponseData);
}
resetInput();
$('#sendMail').removeAttr('disabled');
},
error: function (xhr, ajaxOptions, thrownError){
//xhr.status : 404, 303, 501...
var error = null;
switch(xhr.status)
{
case "301":
error = "Redirection Error!";
break;
case "307":
error = "Error, temporary server redirection!";
break;
case "400":
error = "Bad request!";
break;
case "404":
error = "Page not found!";
break;
case "500":
error = "Server is currently unavailable!";
break;
default:
error ="Unespected error, please try again later.";
}
if(error){
$('label.sendingStatus').text(error);
}
}
});
};
var calculateTimeDifference = function(startDate) {
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var currentDate = new Date();
startDate = new Date(startDate);
var timeCounter = startDate - currentDate;
if (isNaN(timeCounter))
{
return NaN;
}
else
{
days = Math.floor(timeCounter / day);
timeCounter = timeCounter % day;
hours = Math.floor(timeCounter / hour);
timeCounter = timeCounter % hour;
minutes = Math.floor(timeCounter / minute);
timeCounter = timeCounter % minute;
seconds = Math.floor(timeCounter / second);
}
var tDiffObj = {
"Days" : days,
"Hours" : hours,
"Minutes" : minutes,
"Seconds" : seconds
};
return tDiffObj;
};
var StringFormat = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var regExpression = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(regExpression, arguments[i + 1]);
}
return s;
}
You need to hook into the success callbacks of each of the $.ajax calls. You can create a method that will show a message for those:
For example, your signUp function's success callback could look like:
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
showMessage('Your subscription was received. Thank you!');
}
}
}
And you just create a method that will show the message to the user
var showMessage = function (msg) {
// of course, you wouldn't use alert,
// but would inject the message into the dom somewhere
alert(msg);
}
You would call showMessage anywhere the success callback was fired.
You can add your success notifing code in each of the $.ajax success handlers.