Why telegram does not send message to webhook? - node.js

Using node-telegram-bot-api on my VPS, I'm trying to get message from a telegram channel.
Here is the code:
var TelegramBot = require ( 'node-telegram-bot-api');
var token = '1793xxxxxxxxxxxxxxxxxxxxx';
var __dirname ='/etc/nginx/ssl'
var options = {
webHook: {
port: 443,
key: __dirname+'/key.pem',
cert: __dirname+'/crt.pem'
}
};
var bot = new TelegramBot(token, options);
bot.setWebHook('1.3.4.5:443/bot1793xxxxxxxxxxxxxxxxxxxxx', __dirname+'/crt.pem');
bot.on ( 'message', function (msg) {
var chatId = msg.chat.id;
console.log (msg);
bot.sendMessage (chatId, "Hello!", {caption: "I'm a bot!"});
});
When I get this link the browser:
https://telegram.me/MyExampleBot?start=abcd
I expect the bot to receive a message from the channel containing abcd when user clicks on start button, but I receive nothing in the bot's console.
The problem occured when I added bot.setWebHook to the code. Without that, I could receive a message whenever user typed something in the channel.
My code is following the the example here so I really have no idea what is wrong with it. Really appreciate your hints.

I had the same problem. Telegram didn't send anything to my bot...
Because of incorrect certificate. Generate your cert according to this:
https://core.telegram.org/bots/self-signed
just replace "YOURDOMAIN.EXAMPLE" with valid for you value. I used just my IP, after that it works.
Additionaly you can see debug info from node-telegram-bot-api to understand what happening:
npm install debug
DEBUG=node-telegram-bot-api node bot.js
It will produce debug output for you.
Hope it helps.

Related

Posting message to slack get TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["User-Agent"]

I have a working slack app running as an Azure Function using NodeJS. It is posting payloads fine to my channel. I would also like the Function to post a message to the channel via client.chat.postMessage. As far as I can see I have set everything up correctly but whenever I attempt to post the message I get an error:
TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["User-Agent"]
The code to post the message is:
const { WebClient, LogLevel } = require("#slack/web-api");
const client = new WebClient(process.env['BOT_USER_OAUTH_TOKEN'], {
// LogLevel can be imported and used to make debugging simpler
logLevel: LogLevel.DEBUG
});
const channelId = "C0319MTLHB8";
try {
// Call the chat.postMessage method using the WebClient
const result = await client.chat.postMessage({
channel: channelId,
text: "Hello world"
});
console.log(result);
} catch (error) {
context.res = {
// status: 200, /* Defaults to 200 */
body: "error: " + error
};
}
and this piece of code sits within module.exports.
I guess something doesn't like the contents of BOT_USER_OAUTH_TOKEN but this is a direct copy of the xoxb bot user oauth token. And is of the form:
xoxb-999999999999999-9999999999999-aBunchOfUpperAndLowerCaseCharacters
Any suggestions as to what I am doing wrong?
Thank you I'm Joe Too for your valuable discussed resolution. Posting as an answer to help other community members:
You missed an open bracket in const result = await client.chat.postMessage(
Glad #JimBurke, that you have solved yourself by correcting the syntax/transcription.
Isn't it Node.js 16 LTS?
I had a similar problem, But I made Node.js 14 LTS and it worked

Botkit Slackbot responds with 401 error every time

I'm trying to create a very simple Slack bot using botkit and Google App Engine, but for some reason I keep getting 401 errors any time I message the bot. The weird thing is that the Slack Event Subscription URL (the one ending in /api/messages) validates correctly, and I get a 200 response in GAE logs and validation within Slack.
But whenever I actually message the bot it always gets a 401 error with no message explaining the error at all. I've tried various combinations of the code below, and have now stripped it down to the bare minimum as found here. Aside from dependencies and a code to decrypt credentials (which I've verified is working as expected), this is my full code at the moment:
botInit();
async function botInit () {
const credentialsRaw = await getCredentials();
const credentials = JSON.parse(credentialsRaw);
const adapter = new SlackAdapter(credentials);
const controller = new Botkit({
adapter: adapter
});
controller.on('message', async(bot, message) => {
await bot.reply(message, 'I heard a message!');
});
}
I have also tried this for the messaging function:
controller.ready(() => {
controller.hears(['hello', 'hi'], ['message', 'direct_message'],
async (bot, message) => {
await bot.reply(message, 'Meow. :smile_cat:')
})
})
and this for setting up the controller:
const controller = new Botkit({
webhook_uri: '/api/messages',
adapter: adapter
});
And everything gives back the same exact 401 error, despite all of them working with the Event Subscription URL verification on Slack.
I had same issue but figured out the problem.
I had been using Client Secret as clientSigningSecret
But I should use Signing Secret !

Chaining with Telegram Bot API (like TriviaBot)

I am creating a TriviaBot style bot for telegram and am using Node.js to do so. At the moment I am having trouble capturing the users response to my quiz to determine whether the user got the question right or wrong. Below is some code:
bot.onText(/\/quiz/, function (msg) {
var chatId = msg.chat.id;
var text = quizdata.one.msgtxt;
var opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: quizdata.one.keyboard,
one_time_keyboard: true
})
};
bot.sendMessage(chatId, text, opts);
//NEED TO CAPTURE THE USER RESPONSE AND REPLY TO THEIR MESSAGE ACCORDINGLY
});
NOTE : Telegram would cut of any asynchronous function, you should make separated module for listening any incoming interaction with button. You could use global Array for to store small data to be able getting returned for other module you need.
Putting all of your command in the index js not good idea tho.
if you want to listen the from keyboard callback_data. Just create a new line to listen any incoming clicked button.
bot.on("callback_query", (msg) => {
if (msg.data === "your_keyboard_callback_data") {
// do whatever you want
}
})
For more clearance node telegram api
Sorry if my answer is too late for this but hope mine can help other people 🙂

Node.js send message to GCM server

I'm trying to send a message to GCM server to forward to another phone. The request keeps saying 400. I've checked the code close to a hundred times, but I'll put it up just in case. I also have changed the registration token parameter to registration_id and various others, along with changing the data to arrays etc. Just to be clear that the API key and Registration ID work, I can get a push notification from this Web site:
http://demo.androidhive.info/gcm_chat/push_test.php
Here's the code:
var gcm = require('node-gcm');
var gcmSender = new gcm.Sender('A......1234568AAA'); //my api key
var GCMmessage = new gcm.Message();
GCMmessage.addData("message", message);
GCMmessage.addData("from", from);
GCMmessage.addNotification('title', 'Alert!!!');
GCMmessage.addNotification('body', 'Abnormal data access');
GCMmessage.addNotification('icon', 'ic_launcher');
var regtoken = response.GCM.RegID; //data returned from another function
//Gives the RegID for a specific user
gcmSender.send(GCMmessage, {"to" : regtoken}, function(err, gcmResponse) {
if(err){
console.log(err);
} else {
console.log(gcmResponse);
console.log("message sent");
}
});
Ok it seems that it is best to send your gcm message directly using an npm module like 'request' or something similar. When I sent a message using that I received a very detailed error message telling me that 'from' is a reserved word. I'm not sure if that was the whole issue, but having a detailed error message made the code modification pretty easy.

Connecting to Conference over node-xmpp on Node.js

How to connect to a Jabber conference? Send and receive messages. Get a list of online users.
Did some testing from localhost using prosody.im. I had two clients:
alfred1: Just normally XMPP client
alfred2: My bot
I created MUC alfred#conference.localhost.
When I first connect to channel from XMPP client(alfred1) and next run the bot, I receive test message from bot(alfred2). And I will also receive chat message from alfred1 in console when I sent message from XMPP-client.
var xmpp = require('node-xmpp'),
sys = require('sys'),
jid = 'alfred2#localhost',
password = '1234',
room_jid = 'alfred#conference.localhost',
room_nick = 'alfred2',
conn = new xmpp.Client({
jid : jid,
password : password,
});
conn.on('online', function () {
console.log('online');
//var elm2 = new xmpp.Element('presence', { from: jid, to: 'alfred#conference.localhost'}).c('x', {'xmlns': 'http://jabber.org/protocol/muc' }).up();
conn.send(new xmpp.Element('presence', { to: room_jid +'/' + room_nick }).
c('x', { xmlns: 'http://jabber.org/protocol/muc' })
);
conn.send(new xmpp.Element('message', { to: room_jid, type: 'groupchat' }).
c('body').t('test')
);
});
conn.on('stanza', function(stanza) {
sys.puts(stanza);
});
conn.on('error', function(e) {
sys.puts(e);
});
Maybe later I try to improve code a bit, but I guess this gets you going...
From jabber.org:
but as always feel free to join the
jabber#conference.jabber.org chatroom
via XMPP or HTTP if you have questions
or comments.
You mean connecting to jabber#conference.jabber.org?
I believe that should look up MUC specifications for that. I think it is possible using only node-xmpp, but node-xmpp is pretty low-level library. I used npmjs.org's search to look for modules supporting MUC, but could not get any of them working yet.. I think MetaJack's source-code about MUC could help you out. This could be a fun project to implement over the weekend I guess.
When you like to get started immediately you should probably(maybe somebody has MUC in node-xmpp?) have a look at Smack(Java) for example which does support MUC.

Resources