Buttons and bold text in bot.sendMessage - node.js

help me understand what the problem is.
Why are the buttons (menuOptions) not displayed?
if (text === '/start') {
ust[chatId] = 0;
bot.sendMessage(chatId, `${msg.from.first_name}, <b>Добро пожаловать</b> ✌️\n\nДоступные возможности:`, {
parse_mode: "HTML",
menuOptions
})
}
Code menuOptions:
module.exports = {
menuOptions: {
reply_markup: JSON.stringify({
inline_keyboard: [
[{text: 'Списки', callback_data: '/list'}],
[{text: 'Частые вопросы', callback_data: '/quests'}, {text: 'Распространенные проблемы', callback_data: '/problems'}]
]
})
}
node-telegram-bot-api on Node JS
I tried many ways, remade the menuOptions structure, as soon as I did not insert it.

Your code specifies menuOptions key-value pair in the options parameter of the sendMessage method. What you need to do is directly use reply_markup key.
const { menuOptions } = require('./path/to/menu_options');
if (text === '/start') {
ust[chatId] = 0;
bot.sendMessage(chatId, `${msg.from.first_name}, <b>Добро пожаловать</b> ✌️\n\nДоступные возможности:`, {
parse_mode: "HTML",
reply_markup: menuOptions.reply_markup
})
}
If you want to use other properties than just reply_markup in the menuOptions object, javascript spread operator might help:
{
parse_mode: 'HTML',
...menuOptions
}

Related

Update Dialogflow "Transfer Call" field from backend ( Node.js )

I try to update phone number in "Transfer Call" field under "Responses" tab ("TELEPHONY" -> "ADD RESPONSES" button ) for given intent using Node.js but I cannot.
New update removes old "Transfer Call" field with the old phone number (which I created by hand in console for testing purposes)
Please help
Here is example code:
const dialogflow = require('dialogflow')
const intentsClient = new dialogflow.IntentsClient({ keyFilename: 'key.json' })
const fulfillmentMessages = [ { platform: 'TELEPHONY',
telephonySynthesizeSpeech: { text: 'Hello World' } },
{ platform: 'TELEPHONY',
telephonyTransferCall: { phoneNumber: '+12132954242' } },
{ text: { text: [ '' ] } } ]
const intent = {
name: 'projects/example/agent/intents/2ef3e0b6-6cd7-4d5b-a8ca-ce11111125e019',
displayName: 'Test',
fulfillmentMessages: fulfillmentMessages
}
const updateIntentRequest = { intent: intent }
intentsClient.updateIntent(updateIntentRequest).then((data) =>{ console.log(data)}, (e) => {
console.log(e) })
Detailed response can be found here however heres the correct code sample (tested and working)
const dialogflow = require('dialogflow');
const intentsClient = new dialogflow.v2beta1.IntentsClient({ keyFilename: 'key.json' }) //Note that dialogflow will be using v2beta1 api
const message_to_set = [
{
platform: 10,
telephonySynthesizeSpeech: {
text : 'Hello World'
},
telephonyTransferCall: {
phoneNumber: '+12132954242'
}
}
]
const intent = {
name: 'projects/example/agent/intents/2ef3e0b6-6cd7-4d5b-a8ca-ce11111125e019',
displayName: 'Forward',
messages: message_to_set //Note parameter was switched from fulfillmentMessages to messages
}
const updateIntentRequest = { intent: intent }
intentsClient.updateIntent(updateIntentRequest).then((data) =>{ console.log(data)}, (e) => { console.log(e) })

Alexa Two Intents; Second Intent not triggering

I am having trouble making two intents to work in hello world demo in alexa. I added in AboutSarawakIntent to trigger another lambda function.
{
"interactionModel": {
"languageModel": {
"invocationName": "greet chief minister",
"intents": [
...,
{
"name": "HelloWorldIntent",
"slots": [],
"samples": [
"Ok",
"Awesome",
"Good",
"Great",
"Okay",
"Yes",
"Good Afternoon",
"Good Morning",
"Hello",
"Say Hello",
"Say hi",
"Tell Me More"
]
},
{
"name": "AboutSarawakIntent",
"slots": [],
"samples": [
"how do you do",
"I am fine",
"how are you"
]
},
...
],
"types": []
}
}
}
so the following codes are from lambda functions where i add AboutSarawakIntentHandler to listen to AboutSarawakIntent.
....
const HelloWorldIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'HelloWorldIntent';
},
handle(handlerInput) {
const randomNumber = Math.floor(Math.random() * speeches.length);
const speechText = speeches[randomNumber];
const continueSpeech = continues[randomNumber];
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(continueSpeech)
.getResponse();
}
};
const AboutSarawakIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'AboutSarawakIntent';
},
handle(handlerInput) {
const speechText = 'Welcome to Sarawak'
const continueText = 'I am honored to be here.';
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(continueText)
.WithStandardCard('Greeting from Sarawak', 'Welcome Everybody', 'https://s1.bukalapak.com/img/6425275433/w-1000/banner_selamat_datang_di_pernikahan.jpg', 'https://s1.bukalapak.com/img/6425275433/w-1000/banner_selamat_datang_di_pernikahan.jpg')
.getResponse();
}
};
....
// This handler acts as the entry point for your skill, routing all request and response
// payloads to the handlers above. Make sure any new handlers or interceptors you've
// defined are included below. The order matters - they're processed top to bottom.
exports.handler = Alexa.SkillBuilders.custom()
.addRequestHandlers(
LaunchRequestHandler,
HelloWorldIntentHandler,
AboutSarawakIntentHandler,
HelpIntentHandler,
CancelAndStopIntentHandler,
SessionEndedRequestHandler,
IntentReflectorHandler) // make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
.addErrorHandlers(
ErrorHandler)
.lambda();
I can trigger HelloWorldIntent successfully everytime when I use the utterances for it but the other one always give me back 'Sorry, I couldn't understand what you said. Please try again.' Can someone advise me where could go wrong?
I can finally trigger because my alexa device can't support Picture Output. so WithStandardCard always give me errors. so i change it to WithSimpleCard and it worked.
"https://ask-sdk-for-nodejs.readthedocs.io/en/latest/Building-Response.html"

How to export and import functions for telegrams bot?

I'm create a bot telegram with two buttons. On each button I want to hang the action. I want to transfer these actions to another file. How can I do that?
const Telegraf = require("telegraf");
const session = require("telegraf/session");
const Composer = require('telegraf/composer');
const bot = new Telegraf('Token')
const first = require('./command/first');
bot.command('start', (ctx) => {
const markdown = `
Hi! Click on the button 1 or 2!`;
ctx.telegram.sendMessage(ctx.message.chat.id, markdown, {
parse_mode: 'Markdown',
reply_markup: {
keyboard: [
['1', '2'],
],
resize_keyboard: true
},
disable_notification: false
});
});
bot.use(session());
bot.use(Telegraf.log())
bot.on('1', first.hears()) ///myfunction command
bot.startPolling();
console.log(Telegraf.log());
and file ./command/first
module.exports = {
hears: function () {
console.log("debug 1");
bot.action('1', (ctx) => {
const markdown = ` Type some text...`;
ctx.telegram.sendMessage(ctx.message.chat.id, markdown, {
parse_mode: 'Markdown',
reply_markup: {
keyboard: [
['🔙 Back'],
],
resize_keyboard: true
},
disable_notification: false
});
})
}
};
but nothing works. When starting the bot writes immediately debug 1
And nothing.. Help me please!
Firstly Change:
bot.on('1', first.hears()) // on is for events
to
bot.hears('1', first.hears()) // hears listens for the specified string from bot
Then rewrite the module in /command/first to:
module.exports = {
hears: function (ctx) {
console.log("debug 1");
// Added markdown formatting
const message = `*Bold text* and _italic text_`;
ctx.telegram.sendMessage(ctx.message.chat.id, message, {
parse_mode: 'Markdown',
reply_markup: JSON.stringify({ // You also missed JSON.stringify()
keyboard: [
['🔙 Back'],
],
resize_keyboard: true
}),
disable_notification: false
});
}
}
This should work. I hope this helps.

Array full of regex, match to string, return path

Still very much a beginner, Just editing to make a little more sense
Here is an example payload.
{
"Status":
{
"result":[
{
"LastUpdate":"2017-09-07 06:47:09",
"Type":"2",
"Value":"' s the inside temperature",
"idx":"4"
}
],
"status":"OK",
"title":"GetUserVariable"
},
"Devices":
{
"28":
{
"rid":"28",
"regex":"(the )?(AC|(Air( )?(Con)?(ditioner)?))( Power)?( )?$/i"
},
"71":
{
"rid":"71",
"regex":"(the )?inside temp/i"
}
}
}
I want to filter the "Devices" array down to entires that match Status.result[0].Value.
I have the follow code working, but it is in working in reverse, it returns the matching string, not the filtered array, just not sure how to reverse it.
var devices = msg.payload.Devices;
var request = [ msg.payload.Status.result[0].Value ];
var matches = request.filter(function (text) {
return devices.some(function (regex) {
var realregex = new RegExp(regex, "i");
return realregex.test(text);
});
});
msg = { topic:"Inputs", payload: { devices:devices, request:request } };
msg2 = { topic:"Output", payload: { matches:matches } };
return [ [ msg, msg2 ] ];
Thanks,
Wob

How to create pagination with inline keyboard in telegram

I am creating a Telegram bot wit Node.js and I am using node-telegram-bot-api module.
My current issue is:
To create pagination with inline keyboard.
In documentation here, has an interesting example of what I need.
For appearances, I must use method editMessageText but for update inline keyboard I need to transfer param inline_message_id. Unfortunately I could not understand how to do it.
I will be very much appreciate for any example to update inline keyboard and how it release in this example.
You need pass updated pagination with editMessageText:
var bookPages = 100;
function getPagination( current, maxpage ) {
var keys = [];
if (current>1) keys.push({ text: `«1`, callback_data: '1' });
if (current>2) keys.push({ text: `‹${current-1}`, callback_data: (current-1).toString() });
keys.push({ text: `-${current}-`, callback_data: current.toString() });
if (current<maxpage-1) keys.push({ text: `${current+1}›`, callback_data: (current+1).toString() })
if (current<maxpage) keys.push({ text: `${maxpage}»`, callback_data: maxpage.toString() });
return {
reply_markup: JSON.stringify({
inline_keyboard: [ keys ]
})
};
}
bot.onText(/\/book/, function(msg) {
bot.sendMessage(msg.chat.id, 'Page: 25', getPagination(25,bookPages));
});
bot.on('callback_query', function (message) {
var msg = message.message;
var editOptions = Object.assign({}, getPagination(parseInt(message.data), bookPages), { chat_id: msg.chat.id, message_id: msg.message_id});
bot.editMessageText('Page: ' + message.data, editOptions);
});

Resources