Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

71
Views
Emitting to specific client not working within event handler - Socket.IO

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!