I would like to be able to send a message to the room group on disconnect of the user so that it updates the player list. It seems that it is not possible once disconnected, which would make sense in a way, but how would I be able to send a message to the channel before it disconnects the user.
I have the following code:
async def disconnect(self, close_code):
#Remove the disconnected player
player = players.get_player(self.scope['session']['id'])
players.remove_player(player.id)
room = rooms.get_room(player.room)
if room:
#Sending messages on disconnect doesn't seem to work
players_left = room.leave_room(player)
if players_left < 1:
rooms.remove_room(room.name)
await self.channel_layer.group_send(
'all_users',
{
'type': 'room_list',
}
)
await self.channel_layer.group_discard(
room.name,
self.channel_name
)
else:
await self.send_room(room,'list_players')
async def send_room(self,room,type):
await self.channel_layer.group_send(
room.name,
{
'type': type,
'data': room.name
}
)
async def list_players(self,event):
# Send message to WebSocket
room = rooms.get_room(event['data'])
players = room.get_players()
await self.send(text_data=json.dumps({
'action': 'room_list_players',
'payload' : {
'players' : players,
'owner' : room.owner.id
}
}))