I have a Kik bot that I am hosting on my computer. I setup the configureation with the following code:
let request = require('request')
request.post('https://api.kik.com/v1/config',
{
"auth":{
"user":"bhs************",
"pass":"*******-*****-*****-****"
},
"headers":{
"User-Agent":"request"
},
"form":{
"webhook":"https://(my public ip):8080",
"features":{
"manuallySendReadReceipts":false,
"receiveReadReceipts":false,
"receiveDeliveryReceipts":false,
"receiveIsTyping":false
}
}
});
And here is the code for my actual bot:
'use strict';
let util = require('util');
let https = require('https');
let Bot = require('#kikinteractive/kik');
// Configure the bot API endpoint, details for your bot
let bot = new Bot({
username: 'bhs************',
apiKey: '*******-*****-*****-****',
baseUrl: 'https://(my public ip):8080'
});
bot.updateBotConfiguration();
bot.onTextMessage((message) => {
console.log("New Message")
message.reply(message.body);
});
// Set up your server and start listening
let server = https
.createServer(bot.incoming())
.listen(8080);
console.log("Server Running on port 8080")
I have setup port forwarding on my router to redirect to my computer with the internal and external port of 8080. I also have the protocol set to both TCP and UDP. Here is a photo if that setup:
My bot has stopped telling me that I need to Finnish setting it up every time I text it, but now it never says anything. Is there something that I'm doing wrong here?
It sounds like its not hitting your endpoint properly. I would suggested using ngrok to give yourself a public URL and it will forward to your local IP.
https://ngrok.com/
Related
I’m a long term programmer, but haven’t used nodejs much in my code. Now I need to use it in my current code and I’ve ran into a problem that I can’t seem to figure out myself, I have googled a lot but nothing seem to fix it.
I am trying to get my website to connect to the nodejs server running on same host.
If I visit the url in my browser, it works fine (http://localhost:6857/socket.io/?EIO=4&transport=polling) and I see this respond
0{"sid":"s_v860SbNO4toknPAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
But when I try to connect thru the website, I just get
GET http://localhost:6857/socket.io/?EIO=3&transport=polling&t=N_gL_HZ net::ERR_CONNECTION_REFUSED
Can someone guide my in the right direction for how to fix this, so I can begin using nodejs inside my website?
This is my server.js
// use express
var express = require("express");
// create instance of express
var app = express();
// use http with instance of express
var http = require("http").createServer(app);
// start the server
var port = 6857;
http.listen(port, '0.0.0.0', function () {
console.log("Listening to port " + port);
});
// create socket instance with http
var io = require("socket.io")(http);
// add listener for new connection
io.on("connection", function (socket) {
// this is socket for each user
console.log("User connected", socket.id);
});
io.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
And this is my JS code inside my website
<script>
var server = "http://localhost:6857/";
var io = io(server);
</script>
Socket IO requires you to enable CORS explicitly - Thus why you get the error stated above.
To enable CORS, please see the following link
So I have this long confusion about creating webhook API for my local app. This project is for learning purpose only so I need to understand what is the difference between simple REST API and webhook, in terms of implementation. I know the difference in terms of working but I can't get the technical difference.
For example, when I use Firebase in my web app and use the real-time database to get the updated values on the client-side, it works seamlessly and I don't need to make the POST or GET call every second or minute. It gets updated instantaneously. I know they might not be using webhook as such but rather using web-socket to keep the connection open between a client web app.
Okay now back to the webhook on the local machine - How can I create my own webhook server where the client can hook to the endpoint and get updates automatically.
Let me share some code
WebHook NodeJS server
// Require express and body-parser
const express = require("express")
const bodyParser = require("body-parser")
// Initialize express and define a port
const app = express()
const PORT = 3000
// Tell express to use body-parser's JSON parsing
app.use(bodyParser.json())
// Start express on the defined port
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`))
app.use(bodyParser.json())
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
var headers = {};
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
res.writeHead(200, headers);
res.end();
} else {
next();
}
})
const processSomething = callback => {
setTimeout(callback, 1000);
}
app.post("/hook", (req, res) => {
console.log(req.body) // Call your action on the request here
processSomething(() => {
res.status(200).send({
id: "ABC123",
message: "New record added!"
});
});
})
Web client running
index.html -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webhook Test Client</title>
</head>
<body>
<h1>Hello World</h1>
<div class="result">Data</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$.post("http://localhost:3000/hook", function (data) {
console.log("data -- >",data);
$(".result").html("data -- > " + data);
});
</script>
</body>
</html>
nodejs to server the page -
const express = require('express'),
app = express(),
server = app.listen(1000);
app.use(express.static('public'));
console.log("server running...");
I have seen so many tutorials on Medium or other tech blogs but they mostly talk about connecting to webhook API hosted somewhere on a webserver that they have built as service or something.
So far I have understood and not understood is that.
I can't make webhook API call from the web client.
Only nodejs client-server can make webhook calls to the webhook endpoint. What I mean by this is - in my example webhook can't be called from HTML page but server serving that page can make the call. Maybe I am wrong.
Webhook is not so different from REST API.
Webhook is not made for the web client.
I will update this question as I get relevant replies and testing them.
Why I am interested in webhook because I wanted to create an API where the user doesn't have to make calls to an API to get an update but at the same time the API can be used from the web client, like firebase but avoid WebSocket at the same time. Or can I avoid WebSocket?
Edit: - So I got confirmation on webhooks are designed for server-to-server communication.
Most of the demos available online are using githud, discord, zapier, etc to create webhooks. Can you please share where we can just make custom webhooks without using third party libs ?
I'm trying to use NodeJS to connect my Raspberry Pi to AWS IoT and send some MQTT message. I am using the aws-iot-device-sdk library and this is actually my test code
var awsIot = require('aws-iot-device-sdk');
var device = awsIot.device({
keyPath: '../certs/*******-private.pem.key',
certPath: '../certs/*******-certificate.pem.crt',
caPath: '../certs/root-ca-certification.pem',
clientId: 'provola',
host: '*******-ats.iot.us-east-1.amazonaws.com',
});
device.on('connect', function () {
console.log('connect');
device.subscribe('topic_1');
device.publish('topic_2', JSON.stringify({ test_data: 1 }));
});
device.on('message', function (topic, payload) {
console.log('message', topic, payload.toString());
});
But when I run it, the only thing I get is the message connect printed continuously.
I tried to run the same code even on my laptop but I get the same result.
Moreover I would like to know where to get the CA certificate for the caPath parameter, because actually I don't know if it is correct.
I'm having some trouble connecting to the cube.js backend on AWS serverless and executing the /cubejs-api/v1/load request in the frontend dashboard. I keep getting {"error":"Continue wait"} instead of a result returned.
I am following the react-dashboard guide for authentication but deployed using the backend cube.js serverless AWS template.
This is what my main cube.js file looks like.:
const AWSHandlers = require('#cubejs-backend/serverless-aws');
const PostgresDriver = require('#cubejs-backend/postgres-driver');
const fs = require("fs");
const jwt = require("jsonwebtoken");
const jwkToPem = require("jwk-to-pem");
const jwks = JSON.parse(fs.readFileSync("jwks.json"));
const _ = require("lodash");
module.exports = new AWSHandlers({
checkAuth: async (req, auth) => {
const decoded = jwt.decode(auth, { complete: true });
const jwk = _.find(jwks.keys, x => x.kid === decoded.header.kid);
const pem = jwkToPem(jwk);
req.authInfo = jwt.verify(auth, pem);
},
externalDbType: 'postgres',
externalDriverFactory: () => new PostgresDriver({
host: process.env.CUBEJS_EXT_DB_HOST,
database: process.env.CUBEJS_EXT_DB_NAME,
port: process.env.CUBEJS_EXT_DB_PORT,
user: process.env.CUBEJS_EXT_DB_USER,
password: process.env.CUBEJS_EXT_DB_PASS,
})
});
I didn't have the redis URL set correctly initially and fixed the connection to redis after adding redis:// extension before the url to the serverless.yml file to fix that so I know it's not redis connection issue. I'm assuming there's some other problem.
The cubejs process function has no logs at all. I have setup a NAT gateway and subnets according to the guide on the deployment site so that i have 1 subnet for each zone just for the lambda and they have been added to the new NAT gateway that was created and to the 2 functions so they have internet access.
What could be the issue? Did I configure something wrong or do I need to make changes to something?
#cubejs-backend/serverless uses internet connection to access messaging API as well as Redis inside VPC for managing queue and cache.
Such continuous Continue wait messages usually mean that there's a problem with internet connection or with Redis connection. If it's Redis you'll usually see timeouts after 5 minutes or so in both cubejs and cubejsProcess functions. If it's internet connection you will never see any logs of query processing in cubejsProcess function.
I have a NodeWebkit client which connects to a nodejs server using the socket.io library (JavaScript).
The client launches the connect procedure on the application start but the server does not acknoledge any connections... Though the client's socket has the connected attribute to "true".
You should know that I am using socketio-jwt to authentificate the connection.
Github: https://github.com/auth0/socketio-jwt
I know that the connection does work in a way because if I add :
io.sockets.on('connection', function(){console.log("hello");})
It prints hello !
So it seems that event though the connection is somehow made it doesn't want to do the auth part with the library, resulting in... Well... Nothing.
But that's not all !!
Because if I reboot the app (not the server) then the auth works most of the time ! It acts like a race condition... But I dont see how it could possibly be one... Every line of code is geting executed appart of the success callback of authentification.
I tried connecting to a remote server and on my localhost.
I also tried with an other library of socket auth but I've got the same probleme.
This is the server code:
var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
io.sockets.on('connection', socketioJwt.authorize({
secret: 'some secret',
timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {
console.log('[Info]: A user connected to socket = ', socket.decoded_token);
});
});
http.listen(5000, function () {
console.log('listening on *:5000');
});
And now the client code:
this.socket = io.connect('http://' + that.hostName +':' + that.port);
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret);
this.socket.on('connect', function () {
that.socket.emit('authenticate', {token: token}) //send the jwt
.on('authenticated', function () {
console.log("[Info]: Socket login successfull");
})
.on('unauthorized', function (msg) {
console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
});
});
The server side log "A user connected to socket" is never shown.
If you have an idear ! Thanks for your time.
Why is there a 'that' on socket.emit (client)? I think you should handle it within the same instance of socket.io - using same 'this' as above