Error while running slack-web api and express server - node.js

I am trying to integrate WhatsApp and Slack for developing a chatbot. I am using WATI as my WhatsApp API provider and Slack Web API in Node.js
For testing locally I am ngrok to generate a webhook URL. But I am unable to receive WhatsApp incoming messages as it gives the following error:
process.nextTick(function () { throw userError; });
Error: Slack request signing verification failed
server.js
require('dotenv').config('/.env')
const express = require("express")
const app = express()
const PORT = process.env.PORT || 8000
const token = process.env.SLACK_BOT_TOKEN
const eventsApi = require('#slack/events-api')
const slackEvents = eventsApi.createEventAdapter(process.env.SLACK_SIGNING_SECRET)
const { WebClient, LogLevel } = require("#slack/web-api");
const client = new WebClient(token, {
logLevel: LogLevel.DEBUG
});
app.use('/', slackEvents.expressMiddleware())
//Route for WhatsApp
app.post('/wa-slack', async (req, res) => {
console.log(req)
});
slackEvents.on("message", async (event) => {
console.log(event)
// if (!event.subtype && !event.bot_id)
// client.chat.postMessage({
// token,
// channel: event.channel,
// thread_ts: event.ts,
// text: "Hello World!"
// })
})
app.listen(PORT, () => {
console.log(`App listening at http://localhost:${PORT}`)
})
The signing secret for slack is correct because the server runs successfully if I remove the following block
app.post('/wa-slack', async (req, res) => {
console.log(req)
});
Is there a way I can use the express server for handling both Slack and WhatsApp incoming requests?
Or do I need to create separate servers?
Any help or advice is appreciated, Thank you!

Related

how can i print discord messages to express server?

I have been searching for a long time how I can send a discord message to my site.
then i found the express, i don't understand how to print data to site when discord message event is triggered can you help with this issue?
I just tried the following but it only works once and then it doesn't work again
const {Client} = require("discord.js")
const client = new Client({intents: ["GUILDS","GUILD_MEMBERS","GUILD_MESSAGES","GUILD_PRESENCES"]})
client.login("token")
client.on("ready", () => {
console.log("oks")
})
const express = require("express")
var app = express();
client.on("message", message => {
app.get("/",function(qu,res){
res.send(message.content)
})
})
})
let servers = app.listen(3000,function(){
})
Use messageCreate because the message event is depreciated. app.get() should be defined outside your message event listener. I'm not sure what you mean by "print data to site", but you can add every message sent to a database or maybe a JSON file if you'd like, and send that data through express. If you want messages on your site updated in real-time look into sockets.
Here's an example of what I mean:
const { Client } = require("discord.js")
const express = require("express")
const client = new Client({ intents: ["GUILD_MESSAGES"] })
const app = express();
const messages = []
app.get("/", (req, res) => {
res.status(200).json(messages)
})
client.on("ready", () => {
console.log("ready!")
})
client.on("message", message => {
messages.push(message)
})
client.login("token")
app.listen(3000, () => console.log("listening on port 3000")

textnow api with nodejs not working logging in

const express = require("express");
const app = express();
const textNow = require('textnow-api');
app.use(express.static("public"));
app.get("/", function(request, response) {
textNow.login("email", "'password").then(client => {
console.log(`Logged in as ${client.username}`);
textNow.fetchMessages(client.id, client.username).then(messages => {
console.log(messages.map(message => `ID: ${message.id} | Message: ${message.message} | Sender: ${message.contact_value}`).join('\n'));
});
});
});
const listener = app.listen("80", function() {
console.log("Your app is listening on port " + listener.address().port);
});
It only responds with a 400 error, even though I have the correct login. Can anyone please help me with this, or is it depricated and not working anymore?
textnow-api is deprecated you can use it textbelt or Twilio api

How get response from express server for ajax query in nuxtjs

I'm want to get data from the node/express server after send ajax query from any page of the nuxtjs app.
Usually, for getting and sending ajax query in PHP server, I'm do like this $_GET['var']; echo json_encode('Server got data');
Now I want to use node server express for saving data in mongodb.
When I trying to send a query, response return full code of file test.js.
File index.vue
methods: {
onServer() {
this.$axios.get('/server/test').then(res => {
console.log('res', res.data)
})
}
}
File test.js
var express = require('express');
var app = express();
app.get('*', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
File server/index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
I'm a new user node, please help me!
Your main issue is that you are targeting "test.js" in your axios url. This is why it responds with the file rather than what the get route should respond with.
So try with:
this.$axios.get('http://nuxt-profi/server/test').then(...
and see what you get. You should also be able to access that in the browser, just go to your url http://nuxt-profi/server/test and it should show your "Hello World" reponse.
However I can't be sure how you have set all this up. Are you running this as development? In which case maybe you should access it as http://localhost:3000/server/test but maybe you have virtual hosts configured like this. Also, is this a separate backend api or are you trying this as server middleware?
If this doesn't help please give us more info about your project setup and we'll go from there.

How to send and receive a reply to the bot

I have tried to understand the Microsoft SDK reference in how to communicate with the bot but there is simply no clear way shown of interacting with it.. From the documentation this is what I could put down so far:
const { BotFrameworkAdapter } = require('botbuilder');
const adapter = new BotFrameworkAdapter({
appId: '123',
appPassword: '123'
});
// Start a new conversation with the user
adapter.createConversation()
Any ideas ?
The Microsoft Bot Framework makes use of the restify server to create an API endpoint for the bot. A bot is simply a web service that will send and receive messages to and from the Bot Connector. You will have to use the following steps to communicate with the bot:
Install Restify
npm install --save restify
Include the restify module
const restify = require('restify');
Set up the restify server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978,
function () {
console.log(`\n${ server.name } listening to ${ server.url }`);
}
);
Create the main dialog (here the example uses Echo Bot)
const bot = new EchoBot();
Create a POST endpoint for your server and hook up the adapter to listen for incoming requests
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// route to main dialog.
await bot.run(context);
});
});
Hope this helps.

Viber Chatbot - Creating an echo bot

I was following the Viber Node.JS Bot Documentation and was creating an echo bot that would repeat the messages back to the user. But it does not work and the bot does not reply to my messages. Here is the code:
'use strict';
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const bot = new ViberBot({
authToken: "api-key",
name: "Override API",
avatar: "https://cdn3.iconfinder.com/data/icons/customer-support-7/32/40_robot_bot_customer_help_support_automatic_reply-512.png" // It is recommended to be 720x720, and no more than 100kb.
});
// Perfect! Now here's the key part:
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => {
// Echo's back the message to the client. Your bot logic should sit here.
response.send(message);
});
// Wasn't that easy? Let's create HTTPS server and set the webhook:
const https = require('https');
const port = process.env.PORT || 8080;
// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = "https://webhook.site/09f0b45e-1ad8-466c-9441-e5edb3d783e3";
https.createServer(bot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
try this :
const webhookUrl = "https://webhook.site/09f0b45e-1ad8-466c-9441-e5edb3d783e3";
app.use('/viber/webhook', bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${webhookUrl}/viber/webhook`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
instead of:
https.createServer(bot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
Source

Resources