inline keyboard click doesnt call callback_query why? - javascript

bot.onText(/(.+)$/, function (msg, match) {
const opts = {
reply_markup: {
inline_keyboard: [
[
{
text: 'Edit Text',
callback_data: 'edit'
}
]
]
}
};
bot.sendMessage(msg.from.id, 'Original Text', opts);
});
bot.on("callback_query", function(callbackQuery) {
// 'callbackQuery' is of type CallbackQuery
console.log(callbackQuery);
});
I have looking for answer to this question, tried all the resources available on call_back. Such as
Telegram bot inline keyboard via Node.JS
Telegram inline keyboard and keyboard
How can create menu for telegram bot in bot father?

How about trying this like that?
bot.on('callback_query', function onCallbackQuery(callbackQuery) {
const action = callbackQuery.data;
const msg = callbackQuery.message;
// do your stuff
if (action === 'adress') {
// do something if callback data is "adress", you can have multiple if statements for various cases
}
});
That's how I got it working, hope it helps!

Related

Why do I get a 400 error when i'm trying to edit an inline keyboard (node-telegram-bot-api)?

I am making a message with a simple inline keyboard. The expected result would be that when I click on the button it changes together with the message text.
However the button doesn't change and i get this error:
TelegramError: ETELEGRAM: 400 Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message
I am using the node-telegram-bot-api package.
The code that has to change my keyboard is:
let info_message = {
text: "some info boi",
keyboard: {
reply_markup: {
inline_keyboard: [
[{ text: 'Start', callback_data: '!/start' }]
]
}
}
}
client.on("callback_query", async (cb) => {
if (cb.data === "!/info") {
const msg = cb.message;
const opts = {
chat_id: msg.chat.id,
message_id: msg.message_id,
};
await client.editMessageReplyMarkup(info_message.keyboard, opts);
await client.editMessageText(info_message.text, opts);
}
})
The error occurs because you are trying to edit a message without changing anything in it. If you need to use editMessageText or editMessageReplyMarkup but for some reason you don't change anything then wrap the code in a try catch block (you should always do that). And to remove the clock from the inline keyboard when you click, put some action in the catch block, for example answerCallbackQuery.
In the above example the user didn't pass the reply_markup parameter correctly, so the message didn't change in any way and the error 400 Bad Request: message is not modified appeared.
400 MESSAGE_NOT_MODIFIED
I found out the error.
The method editMessageReplyMarkup() requires the parameter
replyMarkup, A JSON-serialized object for an inline keyboard.
My mistake was that I gave the whole reply_markup while I was requested to give only the inline_keyboard. The code now looks like this:
client.on("callback_query", async (cb) => {
if (cb.data === "!/info") {
const msg = cb.message;
const opts = {
chat_id: msg.chat.id,
message_id: msg.message_id,
};
await client.editMessageReplyMarkup(info_message.keyboard.reply_markup, opts); // I gave info_message.keyboard.reply_markup as input, instead of info_message.keyboard
await client.editMessageText(info_message.text, opts);
}
})

Apollo Client is not refreshing data after mutation in NextJS?

Here is the page to create a User
const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query
const createUserClass = async (event) => {
event.preventDefault();
try {
const { data } = await createType({
variables: {
userClassName,
},
refetchQueries: [{ query: STACKINFO }],
options: {
awaitRefetchQueries: true,
},
});
setNotification({
message: 'User class created successfully',
code: 200,
});
handleClose();
} catch (e) {
setNotification({ message: e.message, code: 400 });
handleClose();
}
};
The thing is I can see inside the network tab the API is calling twice, which is not a good way, but I can see the newly added data , but the page is not refreshing. Kindly help me
I was also struggling with a similar problem and I stepped into your question. I don't know which version of Apollo Client you are using, but I think that instead of using refetchQueries() method, you can try to use update() to clear the cache. This way you will notify UI of the change. Something like this:
createType({
variables: {
userClassName,
},
update(cache) {
cache.modify({
fields: {
// Field you want to udpate
},
});
},
})
This is a link for reference from official documentation's page:
https://www.apollographql.com/docs/react/data/mutations/#:~:text=12-,update
I hope it helps!

PMA Service worker notification click isn't working

I am trying to show a notification and do something when it is clicked. The part that shows is working well, is receiving data from the server, however, the function of clicking on the notification does not work, I have done everything the documentation says, what I found on the web and here, everything points with the same functionality that I have implemented but it doesn't seem to work. I have made fictitious practices and as long as the data is not loaded from the server, the click is triggered, otherwise, with the data it does not.
Can anyone tell me what I am doing wrong? I'll really apreciate some help, I've two days with this.
self.addEventListener('push', (e) => {
let notification = e.data.json();
const title = 'My app ' + notification.title;
const options = {
body: notification.msg,
actions: [
{ action: 'yes', title: 'Aprobar' },
{ action: 'no', title: 'Rechazar' }
]
};
self.registration.showNotification(title, options);
}); //to show the notification with server info
self.addEventListener('notificationclick', function (event) {
console.log(event);
var noti = event.notification.data;
let r = event.notification.data.json();
console.log(noti); },
false); //handling the click
I've also tried with notificationclose to see if it catchs the click but it does not work either.
Important to note that it does not display any error or warning, it does simple do anything. Found the solution! See First Answer.
I found the solution! After playing around with the code and reading some others documents, it turns out that if my service on my server is a threading type, in my js has to be waiting for an answer. If someone needs it.
let notification = '';
self.addEventListener('push', (e) => {
notification = e.data.json();
const title = 'My app' + notification.title;
const options = {
body: notification.msg,
actions: [
{ action: 'yes', title: 'Aprobar' },
{ action: 'no', title: 'Rechazar' }
]
};
e.waitUntil(self.registration.showNotification(title, options)); }); //waitUntil to show the notification
self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
let response = event.action;
event.waitUntil(
fetch(`api/authorizations/processor?uuid=${notification.uuid}&response=${response}&account=${notification.user}`,
{
method: 'GET',
mode: 'cors',
cache: 'default'
}).then((result) => {
if (!result.ok)
throw result;
return result.json();
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.log(errow);
})
); }); // waitUntil to expect a action

Electron.js prevent windows close conditionally

I want to ask user if he really want to close an electron app.
Accordingly to docs - I've tried:
window.onbeforeunload = (e) => {
const answer = confirm('Do you want to close the application?');
e.returnValue = answer;
if (answer) { window.close(); }
};
But my app still closes no matter what user choose.
How to prevent close an Electron app conditionally?
I guess, I have an answer.
It shouldn't be called in renderer process.
Instead we should use mainWindow in main process for such operation and 'close' lifecycle method, which will be called right before closing.
this.mainWindow.on('close', (e) => {
const choice = this.dialog.showMessageBox(
this.mainWindow,
{
type: 'question',
buttons: ['Yes', 'No, hang on', 'third option'],
title: 'Confirm your actions',
message: 'Do you really want to close the application?'
}
);
console.log('CHOICE: ', choice);
if (choice > 0) e.preventDefault();
});
choice const will return an answer from buttons array, so 'Yes' will be as confirm and for other options we can prevent actions.
NOTE: I've pasted with this. from my code, but, obviously mainWindow is your BrowserWindow instance and this.dialog is electron.dialog that imported from import electron from 'electron';
To conditionally close window in Electron ^15, do:
win.on('close', async e => {
e.preventDefault()
const { response } = await dialog.showMessageBox(win, {
type: 'question',
title: ' Confirm ',
message: 'Are you sure that you want to close this window?',
buttons: ['Yes', 'No'],
})
response === 0 && win.destroy()
})

Telegram bot inline keyboard markup callback usage for channel messages

My Telegram bot needs to send messages to channel and provide inline keyboard for every message, it looks like this: inline message keyboard
I need to react on this keyboard button click event, but I can't find docs or examples showing how to do it. Here in docs I can only see that such buttons can open URL or switch chat, but it's not the functionality I need.
Currently my code for message sending looks like this (I use NodeJS Telegraf framework):
const Telegraf = require('telegraf');
const { Markup, Telegram } = Telegraf;
const telegram = new Telegram(process.env.BOT_TOKEN);
const inlineMessageRatingKeyboard = [[
{ text: '👍', callback_data: 'like' },
{ text: '👎', callback_data: 'dislike' }
]];
telegram.sendMessage(
process.env.TELEGRAM_CHANNEL,
'test',
{ reply_markup: JSON.stringify({ inline_keyboard: inlineMessageRatingKeyboard }) }
)
);
So, I need to know, how to make bot react on inline message keyboard interaction in channel messages.
you can use event action() or in TelegrafContext with callbackQuery() and answerCallbackQuery()
context methods on GitHubGist
it's work:
const Telegraf = require('telegraf')
const { Router, Markup } = Telegraf
const telegram = new Telegraf(process.env.BOT_TOKEN)
const inlineMessageRatingKeyboard = Markup.inlineKeyboard([
Markup.callbackButton('👍', 'like'),
Markup.callbackButton('👎', 'dislike')
]).extra()
telegram.on('message', (ctx) => ctx.telegram.sendMessage(
ctx.from.id,
'Like?',
inlineMessageRatingKeyboard)
)
telegram.action('like', (ctx) => ctx.editMessageText('🎉 Awesome! 🎉'))
telegram.action('dislike', (ctx) => ctx.editMessageText('okey'))
telegram.startPolling()
full example here

Categories

Resources