Allright we are trying to make a chatbot, but we need it to recognize dutch language, this is the code we have so far, but we don't know how to add dutch language support. We already tried alot but we dont seem to get it working!
const builder = require('botbuilder');
const express = require('express');
const fs = require('fs');
const { Recognizer,LangNl } = require('node-nlp');
const modelName = './smalltalk.nlp';
const excelName = './smalltalk.xls';
// Creates a connector for the chatbot
const connector = new builder.ChatConnector({
appId: null,
appPassword: null,
});
// Creates a node-nlp recognizer for the bot
const recognizer = new Recognizer();
if (fs.existsSync(modelName)) {
recognizer.load(modelName);
} else {
recognizer.loadExcel(excelName);
recognizer.save(modelName);
}
// Creates the bot using a memory storage, with a main dialog that
// use the node-nlp recognizer to calculate the answer.
const bot = new builder.UniversalBot(connector, (session) => {
recognizer.nlpManager.addLanguage("nl","Nl","NL")
recognizer.recognize(session, (err, data) => {
session.send(data.answer || 'I don\'t understand');
session.endDialog();
});
}).set('storage', new builder.MemoryBotStorage());
recognizer.setBot(bot, false);
// Creates the express application
const app = express();
const port = process.env.PORT || 3000;
app.post('/api/messages', connector.listen());
app.listen(port);
console.log(`Chatbot listening on port ${port}`);
Related
So I'm rewriting my app for it to be cleaner and instead of 800 lines of code in my index.js, I moved all my functions to separate individual files in my "Text Functions" folder. The question I have is, now that I moved all my functions into separate files in the functions folder, how would I run them now in my index.js? The app monitors for new, incoming discord message embeds and sends you a text to your phone notifying you that you just got an embed. Originally, I had all the functions in my index.js to where it'll just go down the list of functions one by one, but now I'm wanting it to call that function that's stored in another folder in my index.js when a new discord message embed comes in. Below I attached my current index.js and one of the function files.
index.js
require('dotenv').config();
require('events').EventEmitter.defaultMaxListeners = 25;
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, , GatewayIntentBits.GuildMembers] });
const twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
const { sendCyberSuccess } = require("./Text Functions/personalSMS");
const express = require('express')
const app = express();
app.use(express.urlencoded({
extended: true
}));
app.listen(3000, () => {
console.log('Listening on port 3000');
});
client.login(process.env.BOT_TOKEN);
personalSMS.js
require('dotenv').config();
require('events').EventEmitter.defaultMaxListeners = 25;
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, , GatewayIntentBits.GuildMembers] });
const twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
function sendCyberSuccess(sms) {
twilio.messages.create({
body: sms,
to: process.env.PERSONAL_NUMBER,
from: process.env.TWILIO_NUMBER,
});
}
client.on("messageCreate", function(message) {
if (message.channel.id == cyberSuccessID && message.author.id != myUserId) {
let author = message.author.username.toString()
message.embeds.forEach((embed) => {
let description = embed.description
let title = embed.title.toString()
if (author.includes('Cybersole') && title.includes("Successfully checked out!")) {
let updatedAuthor = author.replace("Cybersole", 'Senpai Notifier')
let updatedTitle = title.replace("Successfully checked out!", "Checked Out! ๐งช")
const sms6 = `Status: ${updatedTitle}\n\nDescription: ${description}\n\nHey Brandon, it looks like you checked out something on Cybersole. Amazing job! Onto the next drop ๐งช\n\nNotified By ${updatedAuthor}`;
sendCyberSuccess(sms6);
} else if (author.includes('Cybersole') && title.includes("Your card was declined!")) {
let updatedAuthor = author.replace("Cybersole", 'Senpai Notifier')
let updatedTitle = title.replace("Your card was declined!", "Declined โ")
const sms7 = `Status: ${updatedTitle}\n\nHey you just got a decline.That's not 4PF ๐\n\nNotified By ${updatedAuthor}`
sendCyberSuccess(sms7);
}
}
)}
})
I am trying to upload my NodeJS project on Heroku. The project is a multiplayer game, locally the code works for me and both players enter the same map. But, in Heroku I don't get both players on the same map.
I leave the NODEJS code
const express = require("express")
const cors = require("cors")
const app = express()
app.use(express.static('public'))
app.use(cors())
app.use(express.json())
const jugadores = []
const PORT = process.env.PORT || 8080
class Jugador {
constructor(id) {
this.id = id
}
asignarMokepon(mokepon) {
this.mokepon = mokepon
}
actualizarPosicion(x, y) {
this.x = x
this.y = y
}
asignarAtaques(ataques) {
this.ataques = ataques
}
}
class Mokepon {
constructor(nombre) {
this.nombre = nombre
}
}
app.get("/unirse", (req, res) => {
const id = `${Math.random()}`
const jugador = new Jugador(id)
jugadores.push(jugador)
res.setHeader("Access-Control-Allow-Origin", "*")
res.send(id)
})
app.post("/mokepon/:jugadorId", (req, res) => {
const jugadorId = req.params.jugadorId || ""
const nombre = req.body.mokepon || ""
const mokepon = new Mokepon(nombre)
const jugadorIndex = jugadores.findIndex((jugador) => jugadorId === jugador.id)
if (jugadorIndex >= 0) {
jugadores[jugadorIndex].asignarMokepon(mokepon)
}
console.log(jugadores)
console.log(jugadorId)
res.end()
})
app.listen(PORT, () => {
console.log("Servidor funcionando", PORT)
})
I leave a small part of the code here because it is not possible to publish so much code. But I leave a link to the repository on GitHub
Link of the page hosted on Heroku:https://proyecto-mokepon.herokuapp.com/
Code link on GitHub: https://github.com/IamMatiasBazan/proyecto-mokepon
Locally it generates the random number for each player
enter image description here
Deployed in Heroku I see this:
enter image description here
The requests you are sending is pointed to localhost in your js file (multiple places, but this is one). Here you should consider changing it to be the heroku domain or just /mokepon/${jugadorId}/ataques (or something else).
It also looks like the app is sending a new request every 50ms, even if nothing happens. In this case I would then suggest you to look into socket.io to prevent the application to send useless request everytime.
I'm actually trying to make a real-time connection between two different apps. I've found a bunch of tutorials about how to make a chat using socket.io, but that doesn't really help me since it's just the same app duplicated in multiple windows.
I'm making a pick & ban overlay for League of Legends in local development. My first thought was to display the empty overlay on one hand and create an interface to manually update it on the other hand. Socket.io seems to be the right thing to use in my case since it can provide new data without having to reload the component.
This is what I wrote in both apps :
const express = require('express');
const socket = require('socket.io');
// App setup
const app = express();
const server = app.listen(4200, function () {
console.log('Listening to requests on port 4200')
});
// Static files
app.use(express.static('public'));
// Socket setup
const io = socket(server);
io.on('connection', function (socket) {
console.log('Made socket connection', socket.id);
socket.on('change', function (data) {
io.sockets.emit('change', data);
});
});
But I fail to connect them as they have to listen to the same port. What am I doing wrong?
(Forgive my bad English and lack of syntax, I'm doing my best here. :p)
I am certainly not an expert on network programming, but as far as I know you need to have one listening app (backend) and another one to connect to it (client). And you define what happens with all the data (messages) that backend recieves (for example sending the messages it recieves to all the clients in the same chat room).
If I am correct to assume you are trying to connect two listening apps?
simple google search of "nodejs socket server client example" revealed this https://www.dev2qa.com/node-js-tcp-socket-client-server-example/ might wanna take your research in this direction
u can try something like this way
var express = require('express');
var socket = require('socket.io');
// App setup
var app = express();
var server = app.listen(8080, () => {
console.log('App started')
})
// Static file
app.use(express.static('public'))
// Socket SetUp
var io = socket(server);
io.on('connection', socket => {
console.log('made the connection')
socket.on('chat',data => {
io.sockets.emit('chat',data)
});
socket.on('typing',data => {
socket.broadcast.emit('typing',data);
});
})
create another file and
var socket = io.connect('http://localhost:8080')
// Elenment
var message = document.getElementById('message');
handle = document.getElementById('handle');
btn = document.getElementById('send');
output = document.getElementById('output');
feedback = document.getElementById('feedback');
// Emit Events
btn.addEventListener('click', () => {
socket.emit('chat', {
message: message.value,
handle: handle.value
})
})
message.addEventListener('keypress', () => {
socket.emit('typing', handle.value)
})
socket.on('chat',data => {
feedback.innerHTML = '';
output.innerHTML += '<p><strong>' + data.handle +': </strong>' +
data.message + '</p>'
})
socket.on('typing', data => {
feedback.innerHTML = '<p><emp>' + data + ' is typing a message... </emp></p>'
})
details are given here node socket chat app
Ok, figured it out. Here's how it works using express and vue together :
First, setup socket.io in your express server js file :
const express = require('express')
const { Server } = require('socket.io')
const http = require('http')
const app = express()
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST', 'REMOVE']
}
})
const PORT = process.env.PORT || 8080
io.on('connection', (socket) => {
console.log('New socket user')
socket.on('SEND_MESSAGE', data => {
console.log('received message in back')
io.emit('MESSAGE', data)
})
})
server.listen(PORT, () => { console.log(`Server started on port : ${PORT}`)})
As you can see we received from the client "SEND_MESSAGE" and we trigger MESSAGE from the server to forward the information to all the clients. The point I was missing is that we bind SEND_MESSAGE on the socked created from the connection but we emit from the io server.
Now you vue part :
import io from 'socket.io-client'
export default {
data() {
return {
messages: [],
inputMessage: null,
socket: io('http://localhost:8080')
}
},
mounted() {
this.socket.on('MESSAGE', data => {
this.messages.push(data)
})
},
methods: {
sendMessage() {
const message = {
senderID: this.myID,
message: this.inputMessage,
sendAt: new Date()
}
this.socket.emit('SEND_MESSAGE', message)
this.inputMessage = null
},
},
}
I'm new in nodejs and I'm writing Viber-bot right now.
Viber-bot documentations is very bad and I really don't understand how to use some functions.
For example: I want to see some user's data, save that data on mobile device etc.
How can I use function:
bot.getUserDetails(userProfile)
I want to get name, id, phone number if it's possible and save it to some variables.
I have this code:
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const TextMessage = require('viber-bot').Message.Text;
const express = require('express');
const app = express();
if (!process.env.BOT_ACCOUNT_TOKEN) {
console.log('Could not find bot account token key.');
return;
}
if (!process.env.EXPOSE_URL) {
console.log('Could not find exposing url');
return;
}
const bot = new ViberBot({
authToken: process.env.BOT_ACCOUNT_TOKEN,
name: "I'm your bot",
avatar: ""
});
const port = process.env.PORT || 3000;
app.use("/viber/webhook", bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${process.env.EXPOSE_URL}/viber/webhook`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
Sorry if it's stupid questions.
Many thanks.
You can get the user profile data from the response triggered in these following events.
"conversation_started"
"message_received"
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const bot = new ViberBot(logger, {
authToken: process.env.VB_API_KEY,
name: "Bot Name",
avatar: ""
});
bot.on(BotEvents.CONVERSATION_STARTED, (response) => {
const roomname = response.userProfile.id;
const username = response.userProfile.name;
const profile_pic = response.userProfile.avatar;
const country_origin = response.userProfile.country;
const language_origin = response.userProfile.language;
//Do something with user data
})
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => {
//Same as conversation started
});
If you want to fetch user info specifically, you can use this endpoint describe here in viber NodeJS developer documentation.
https://developers.viber.com/docs/all/#get_user_details
If you want to get bot info, try this endpoint.
https://developers.viber.com/docs/all/#get_account_info
I am setting up a peer to peer server for a blockchain project which leverages the Node JS ws websocket client. For whatever reason, the arrow function in my server.on(...) call does not execute. When I change the keyword to 'listen' however, the function executes. Please help :P.
p2p-server.js:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.peers ? process.env.PEERS.split(',') : [];
// HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001,ws://localhost:5002 npm run dev
// HTTP_PORT=3002 P2P_PORT=5002 PEERS=ws://localhost:5001 npm run dev
class P2pServer {
constructor (Blockchain) {
this.blockchain = Blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
// server.on('connection', socket => this.connectSocket(socket));
server.on('connection', socket => this.connectSocket(socket));
// this.connectToPeers();
console.log(`Listening for peer-to-peer connections on: ${P2P_PORT}`);
}
// connectToPeers() {
// peers.forEach(peer => {
// const socket = new Websocket(peer);
// socket.on('open', () => this.connectSocket(socket));
// });
// }
connectSocket(socket) {
this.sockets.push(socket);
console.log('Socket connected.')
}
}
module.exports = P2pServer;
index.js:
// REST API
const express = require('express');
const bodyParser = require('body-parser');
const BlockChain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new BlockChain();
const p2pServer = new P2pServer(bc)
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New block added: ${block.toString()}`);
res.redirect('/blocks');
})
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
simple syntax error messed me up in line 3.
This...
const peers = process.env.peers ? process.env.PEERS.split(',') : [];
should have been this...
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];