Full width home advertisement

Confira

Post Page Advertisement [Top]

"/>
Programmingpython

Python Socket.io Chat feature leave the room message

#Python #Scoketio #Chat #leavingRoom

Hello Minna!
Olá Pessoal.

No post de hoje quero trazer um projeto que estou desenvolvendo, ele está em Python e Flask. Para esse, em especial, vou construir um chat room.

Today's post is something that I`m working on. It is in Python and Flask. For this one, in special, I will build up a chat room.

Espero que esse mini tutorial possa ajudar vocês com alguma informação. Estou compartilhando meu código de forma a agregar algum valor para a comunidade dev. Please, se você tiver alguma dúvida na parte do código, deixe um comentário que vou tentar explicar.




I hope this mini-tutorial can help you with some information. I'm sharing it on a way to help out the dev community. Please, if you have any doubts about the code sample, leave a comment below and I will try to explain it.

Assim que o projeto sair vou montar um post com todas as partes, assim para os ansiosos de plantĂŁo um novo tutorial na mĂŁo!
As soon as the project is done I will bring up all the parts together, in that way you can easily handle this application!


Let's do it.

Adicionar botao para sair da sala de chat. Quando clicamos no botao Sing Out devemos mandar uma mensagem para o chat dizendo que aquele especifico usuario deixou o chat.

We need to add a button to log out of the room. When the click event on SingOut button is activated we need to send a message to the chat, showing the user that just left the chat room.

Para isso:




Em index.html adicione a funcao que vai chamar o javascript dentro do arquivo scripts.js 
In index.html add a function that will call a javascript inside the file called scripts.js


<button id="btnLogout" href="{{ url_for('leaveTheRoom', json=json )}}" >Sing Out</button>


em scripts.js adicione a funcao do click do botao de SingOut. Quando pressionado na index.htm, ele vai acionar essa funcao que chamar funcao LeaveRoom, e vai para o application.py na funcao ‘leave’.

In scripts.js add a click function for the singOut button. When pressed withing index.html it will add this function and call the LeaveRoom function, it will bring you to the application.py file on the Leave function.


//logout from chat active Leave function
btnLogout.onclick = function(){
   leaveRoom(room_name);
}


// leave the room
function leaveRoom(room){
   console.log(`leaveRoom func calling leave`)
   //sends to the server a request for the user to leave the room
   socket.emit('leave', {'user_name' : name, 'room': room_name})
}


em applicaton.py adicione a funcao leaveTheRoom para chamar outra.
In applciation.py add a function called leaveTheRoom to callback the other one.
@app.route('/chat-room')
def leaveTheRoom(json):


   on_leave(json)


@socketio.on('leave')
def on_leave(data):
   ''' Users leave the room '''
   username = str(data['user_name'])
   room = str(data["room"])


   print(username + " is leaving the " + room + " room ")
   socketio.emit('chat-message', {'message': username + " has left the " + room + " room"})


chat-message function em script.js

chat-message function is in script.js
Chat-message eh uma funcao que vai adicionar a mensagem no chat da sala. Se essa mensagem vier com o nome de um usuario, ela vem customizada, se nao, vai para um outra funcao chamada printSysMsg que vai adicionar a mensagem sem customizar

Chat-message is a function that will add a message to the chat room. If this message comes with a user name, it will be customized, otherwise, it will be called by another function called PrintSysMsg that will add a message normally.


socket.on('chat-message', data => {


 const p = document.createElement('p');
 const span_username = document.createElement('span');
 const span_timestamp = document.createElement('span');
 const br = document.createElement('br');


   if (data.user_name){


     p.setAttribute("class", "my-msg");
     span_username.setAttribute("class", "my-username");
     span_username.innerText = data.user_name;


     span_timestamp.setAttribute("class", "timestamp");
     span_timestamp.innerText = data.timestamp;


     p.innerHTML = span_username.innerText +
                   br.outerHTML + data.message
                   + br.innerText + br.outerHTML +
                   span_timestamp.innerText + br.innerText + br.outerHTML +data.room
   }else{
     printSysMsg(data.message)
   }


 messageContainer.append(p);


 })


//printing system message
function printSysMsg(msg){
   const p = document.createElement('p')
   p.innerHTML = msg;
   messageContainer.append(p)


   socket.emit('redirect-dashboard', { "message": "redirecting"})
}





Nenhum comentário:

Postar um comentário

Bottom Ad [Post Page]

"/>
| Designed by Colorlib