get data from webhook telegram bot with node js - node.js

I set the server address for the bot with /setwebhook, now how can I get the data with only node js and https package to access {message :{...} }? (like /getupdates method) but by webhook , probably I mean like the php code but in node js: file_get_contents("php://input") .
Should I use async or https.createServer ? If yes, how and please explain a little

You have to create a server that will handle receiving the data. You can do this by using http.createServer or, more conveniently, using a library such as Express. Simple implementation using Express would look like this:
const app = express();
app.post(`/api/telegram${process.env.TELEGRAM_BOT_TOKEN}`, async (req, res) => {
const message = req.body.message || req.body.edited_message;
...
});
In this example, I use bot token in the webhook url (since I and Telegram are the only entities that know the bot token, I can be sure that the requests to the url come from Telegram). There are better ways to make the webhook secure, such as using secret_token as specified in the docs for setWebhook method.
For development purposes, you can use a service like ngrok to redirect requests from the bot webhook to localhost.
To get an idea of a fully functioning example of implementing webhook with node.js and Express, you can check my open-source project on Github.

Related

Listening webhook for discord bot's top.gg page using heroku

I have my bot hosted on heroku and I have a top.gg page for the bot. Top.gg uses webhooks to send post requests regarding bot votes but I can not figure out how to receive these posts using heroku.
The code for the node js is this:
const webhook = new Topgg.Webhook("my auth code");
app.post("/dblwebhook", webhook.middleware(), (req, res) => {
console.log(req.vote.user);
});
app.listen(process.env.PORT);
And the top.gg page looks like this:
https://i.stack.imgur.com/KiSxS.png
How can I connect them together on heroku?
Any help at all on the matter would be appreciated because I have been trying for 17h straight
It sends a Post request to the URL that's provided.
here's a example one github
You can refer that for help.

Difference between express.js and axios.js in Node

We use axios for http requests such as get, post, etc.
We use express for the same purpose also.
However according to what I read, they are for different purposes.
Please explain how.
PS: If you explain it by giving an example, it would be great!
You can think of express.js as a warehouse:
app.get('/item/:name', async function (req, res) {
res.send(await findItemByName(req.params.name));
});
If you want to get an item, for example a pencil, from this warehouse, you can use axios.js.
axios.get('/item/pencil')
Axios is used to send a web request whereas express is used to listen and serve these web requests.
In simple words, express is used to respond to the web requests sent by axios.
If you know about the fetch() method in javascript, axios is just an alternative to fetch().
I would say that express is used to create HTTP servers. So the server runs somewhere and responds to a request.
Axios is an HTTP client. It creates requests!
In very simple words axios is just passing the web request to the server-side (express). They basically work together (axios -> express -> DB)

What does http and https module do in Node?

Can someone help me in understanding what does http and https module do in Express?
I was going through the following docs on w3schools
From definition it says
Node.js has a built-in module called HTTP, which allows Node.js to
transfer data over the Hyper Text Transfer Protocol (HTTP).
With following example
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
This is the example to live demo
First, I am unable to comprehend their example like Where are they making (route) request so that they are receiving response?
Second by the definition, to make a request, using libraries like axios can be alternative?
third, when we make an api request, isn't the data transferred over http/https?
app.post("/", (req, res) => {
In short, Can someone please explain me in more human words the use of http package in express?
Update: I might be confusing this with express, I am used to using express and here we aren't using express
1- They aren't defining any route. That piece of code only creates a server running on port 8080 that when it's created or accessed on the home route (/) returns "Hello World". If you want to define routes you should take a closer look to a module called express that it's used by most of node users due to its simplicity and documentation (https://expressjs.com/en/starter/hello-world.html) In that link you have an example for creating the server and a basic route
2- Yes it can and should be because they are way better than the default from nodeJs. Take a look at axios or superagent, superagent it's better if you want to use formdata to send images or attachments.
3- By default, all servers created using http or express are http servers (don't have a certificate to encrypt the data so they aren't secure). If you want a https server, you can buy certificates or use https://letsencrypt.org/ this module that generates free SSL certificates with 1 month validation.
http module has multiple functions, it can be used to create a server, to make http requests and so on. It's up to you to decide which submodule from the package you want to use. Express is built over the http module making everything easier.
If you need more explanation, tell me and I will try to explain a little better.

In an Express.js server, how can I send an HTML (with style and js) acquired from a HTTP request, as a response?

This is an Express.js server. I'm trying to authenticate my Instagram API.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const axios = require('axios');
const ejs = require('ejs');
var app = express();
// bodyparser middleware setup
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var instagramClientId = '123123';
app.get('/instagram', (req, res) => {
axios({
method: 'post',
url: `https://api.instagram.com/oauth/authorize/?client_id=${instagramClientId}&redirect_uri=REDIRECT-URI&response_type=code`,
}).then((response) => {
res.send(response.data);
console.log(response.data);
}).catch((e) => {
console.log(e);
});
});
// port set-up
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`app fired up on port ${port}`);
});
This is the error I got. Looks like the html file was sent just fine, but the css and js weren't executed. You can see the error messages were all about style and js not being excuted.
Is this because I need to enable some options in my res.send() code?
I'm going to answer two questions here, the first is what I think you're actually having problems with and the second is what would technically be the answer to this question.
What I think your actual problem is: A misunderstanding of OAuth2.0
Looking at your code, it looks like you're trying to get a user to authenticate with Instagram. This is great, OAuth2.0 is fantastic and a good way to authenticate at the moment, but you've got the wrong end of the stick with how to implement it. OAuth2.0 is about redirects, not proxying HTML to the user. In this case it looks like you're using axios to make a server side call to the instagram OAuth endpoint and then sending the user that HTML. What you should actually be doing is redirecting the user to the Instagram URL you've built.
A high level of the "dance" you go through is the following.
The user requests to login with instagram by pressing a button on your website.
You send the user to an instagram URL, that URL contains your applications token plus an "approved" redirect url. Once the user has logged in with Instagram, Instagram will redirect the user to your approved redirect url.
The users browser has now been redirected to a second endpoint on your server, this endpoint recieves a one-time token from Instagram. You take that token on your server side and use axios (or similar) to make a server side request to fetch some user information such as their profile. Once you have that data, you can then create a user in your the database if needed and issue a new session token to them. Along with the profile call on this, you'll also get a token given directly to you (different from the one the users browser gave you) which will allow you to make requests to the Instagram API for the privileges you requested from the user originally.
This means you have 2 endpoints on your service, the "hello, I'd like to log in with instagram, please redirect me to the instagram login page" and then "hello, instagram said I'm all good and gave me this token to prove it, you can now check with them directly" (this is the callback endpoint).
You can manage this whole process manually which is great for understanding OAuth, or you can use something like Passport.js to abstract this for you. This lets you inject your own logic in a few places and handles a lot of the back and forth dance for you. In this instance, I'd probably suggest handling it yourself to learn how it all works.
Ultimately, you are not sending the user any HTML via res.send or anything similar. Instead your first endpoint simply uses a res.redirect(instagramUrl). You also thus do not make any HTTP requests during this portion, you do that on the "callback" after they've entered their username and password with Instagram.
Technically the correct answer to this question: proxy the JS and CSS calls, but this is really bad for security!
You're sending some HTML from a 3rd party in this case. So you will need to also allow the user access to the HTML and CSS. Security wise, this is quite iffy and you should really consider not doing this as it's bad practice. All of the JS and CSS links in the page are most likely relative links, meaning they're asking you for some JS and CSS which you are not hosting. Your best bet is to find these exact paths (ie: /js/app.min.js) and to then proxy these requests. So you'll create a new endpoint on your service which will make a request to instagrams /js/app.min.js and then send that back down with res.send.
Again, please do not do this, pretending to be another service is a really bad idea. If you need something from instagram, use OAuth2.0 to authenticate the user and then make requests using their tokens and the official instagram API.

Twilio $_REQUEST['From'] equivalent for node.js

I'm trying to use 'twilio' to grab the caller ID from an incoming phone call. I managed to do this easily in my call.php file using the following:
$callerId=($_REQUEST['From']);
I have now redirected my twilio phone number to access a different URL so that I can use it with node.js (ie call.php is now call.js). However, I cannot seem to request the ['From'] field in a similar manner as with the .php file. Is this possible? What is the easiest way to grab a caller Id and store it in a variable using node.js?
Any thoughts appreciated.
For the sake of completeness, here's a full example of getting Twilio request parameters using Express. Before running, make sure to install dependencies with npm install twilio express. You might also benefit from reading this blog post introducing the Twilio node.js module.
This code is an example of responding to an inbound phone call:
// Module dependencies
var twilio = require('twilio'),
express = require('express');
// Create an Express webapp, and use a middleware
// that parses incoming POST parameters
var app = express();
app.use(express.urlencoded());
// Create a route that responds to a phone call by saying
// the caller's number
app.post('/call', function(request, response) {
var twiml = new twilio.TwimlResponse();
twiml.say('Hello, you called from ' + request.param('From'));
response.type('text/xml');
response.send(twiml.toString());
});
// Start the app on port 3000
app.listen(3000);

Resources