Answer the question
In order to leave comments, you need to log in
How to index WebSocket connections of the ws library?
hello, I'm making a simple chat, but with one feature that you can reply to messages to people through the telegram bot, so the problem is that when I write a response from a telegram, the message is sent to all users who are connected, and I have already tried a lot, but here's what I got
bot.start((ctx) => {
console.log(ctx.update.message.chat)
ctx.reply('Welcome')
})
wss.on('error', err => {
console.log(err)
})
wss.on('connection', async ws => {
const newConnection = {
uid: uid(16),
connection: ws
}
clients.add(newConnection)
bot.command('send', (ctx) => {
const telegramMessage = ctx.message.text.replace('/send', '')
const queryConnectionUID = telegramMessage.substr(telegramMessage.indexOf('uid: ') + 5, telegramMessage.indexOf(';') - 6)
ctx.reply(queryConnectionUID)
clients.forEach(client => {
if (client.uid === queryConnectionUID) {
client.connection.send(JSON.stringify({
action: 'sendMessage',
agent: 'telegram',
data: {
result: true,
phoneNumber: '+7(777)-777-77-77',
userName: 'Administrator',
message: telegramMessage.substr(telegramMessage.indexOf(';') + 2)
}
}))
} else {
ctx.reply(`uid is wrong; ${client.uid} != ${queryConnectionUID}`)
}
})
})
bot.launch()
ws.on('message', async msg => {
msg = JSON.parse(msg)
const data = msg.data
if (msg.action === 'check') {
bot.telegram.sendMessage('-32432344',
`new message sended from\nuid: ${newConnection.uid}\nname: ${data.userName}\nphone: ${data.phoneNumber}\nmessage:\n ${data.message}`
)
}
else if (msg.action === 'message') {
const result = await mongoMessages.updateOne({ phoneNumber: data.phoneNumber }, {$push: { messages: data.message }})
ws.send(JSON.stringify({
action: 'sendMessage',
agent: 'server',
data: {
result: result,
phoneNumber: data.phoneNumber,
userName: data.userName,
message: data.message
}
}))
}
})
ws.on('close', () => {
clients.delete(ws)
console.log(`deleted: ${ws}`, clients)
})
})
bot.launch()
Answer the question
In order to leave comments, you need to log in
If I understand the problem correctly
wss.on('connection', async ws => {
const newConnection = {
uid: uid(16),
connection: ws
}
clients.add(newConnection)
ws.on('disconnect', () => {
//clients похоже на Set, тогда так. Или отфильтровать через newConnection.uid если простой массив.
//newConnection доступна нам тут вследствии замыкание.
clients.delete(newConnection);
});
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question