Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

72
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda