I'm building two telegram bots that need to have a real time connection with a server. I'm using Socket.io to build a way for them to communicate with each other through that server. The way I've set it up is that the buyer bot would emit an event to the server, which would then emit an event to the designated seller bot.
The problem is that the event emitter refuses to run if its in an event handler. It works if it's outside of the handler. But I need to have the "newOrder" event emitted after the "buy" event with data passed to it as an argument.
Here's the server code:
io.on("connection", socket => {
socket.on("start", (data) => {
socket.id = data.id
socket.name = data.name
socket.type = data.type
if(data.type == "buyer"){
buyers.push(socket.id)
} else if (data.type == "seller"){
sellers.push(socket.id)
}
socket.join(data.id)
})
socket.on("buy", (data) => {
io.to(data.sellerID).emit("newOrder", data)
})
socket.on("newOrder", (data) => {
let message = `Buyer: ${data.name} bought a product`
bot.telegram.sendMessage(data.sellerID, message)
})
})
Event handler for seller bot:
socket.on("newOrder", (data) => {
message = `Buyer: ${data.name} bought a product`
bot.telegram.sendMessage(data.sellerID, message)
})
Event emitter for buyer bot:
bot.command("buy", (ctx) => {
const data = {
id: ctx.chat.id,
name: ctx.chat.first_name,
sellerID: ----- // I put in my own id here to test the bots.
}
socket.emit("buy", data)
console.log(`${data.name} bought an item`)
})
I don't know if it's relevant to this problem but I'm using Telegraf as the framework for the bots.