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
Related
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")
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!
I have problem of setting up web hook for my chat bot i made using nodejs. Which is deployed on Heroku.
The app uses the following architecture :
const http = require('http');
const port = process.env.PORT || 8080;
// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = process.env.WEBHOOK_URL;
// I have used this as Heroku app name with https://dyno-125-92.herokuapp.com
http.createServer(ot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
Please, help me to setup a webhook using express or anything that can work with my bot?
I'm stuck.
Try this:
const express = require('express');
const app = express();
// contains relative URL path, like: "/viber/webhook"
const webhookUrl = process.env.WEBHOOK_URL;
// ...
app.use(webhookUrl, bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${process.env.EXPOSE_URL}${webhookUrl}`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
If it doesn't work, use - full code example to check.
I'm trying to host the default MS Bot Framework echo bot using Node.js via IIS. However, it does not seem to be working. Do I need to change anything in the code to make it work?
I've tried changing the port from 3987 to 80, but it doesn't start. I'm new to node so I don't exactly know what the problem is.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');
// This bot's main dialog.
const { MyBot } = require('./bot');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
console.log(`\nTo test your bot, see: https://aka.ms/debug-with-emulator`);
});
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
console.error(`\n [onTurnError]: ${ error }`);
// Send a message to the user
await context.sendActivity(`Oops. Something went wrong!`);
};
// Create the main dialog.
const myBot = new MyBot();
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
I already have HTTPS setup on my IIS and I should be able to test it once I get it to work.
Thank you very much.
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.