【发布时间】:2018-05-04 05:24:14
【问题描述】:
使用 Django Channels 2.1.1 和 Django 2.0,我正在构建一个网站,在该网站上,客户按下按钮并被带到一个有一名员工的聊天室。我从 Andrew Godwin 的 multichat 示例开始。
简而言之:我不知道如何正确地将员工添加到群组中,以便他可以在聊天室中接收和发送消息。
我已经阅读了关于层、组和通道的documentation。我不能说我对这些概念非常清楚,但我认为频道与单个用户有关,群组与聊天室或用户以某种方式分组在一起的等价物有关,并且层是沟通的媒介发生。
使用这种理解,我能做的最好的事情就是像这样添加到 join_room(self, room_id) 函数中,这可能是完全错误的事情:
async def join_room_client(self, room_id):
...
# Added to find all staff who are logged in
authenticated_staff = get_all_logged_in_users()
# Added to list staff who are in less than 3 chatrooms
available_staff = []
if len(authenticated_staff) > 0:
for staff in authenticated_staff:
if staff in users_and_rooms and len(users_and_rooms[staff]) in range(3):
available_staff.append(staff)
random_available_staff = random.choice(available_staff)
# I thought receive_json() would look for "content", but I was wrong
content = {
"command": "join",
"join": room_id,
"type": "chat.join",
"room_id": room_id,
"text": "Hello there!",
"username": random_available_staff,
"title": room.title,
}
# Helps to open room in conjunction with chat_join()?
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
await channel_layer.send(users_and_channels[random_available_staff], content)
# This allows staff to receive messages in the chatroom but not to reply.
await self.channel_layer.group_add(
room.group_name,
# The line below is staff's channel name, eg: specific.PhCvZeuI!aCOgcyvgDanT
# I got it by accessing self.channel_name in connect(self)
users_and_channels[random_available_staff],
)
else:
print("Staff are not yet ready.")
else:
print("There are no staff available.")
使用此代码,房间会自动在员工的浏览器上打开。他可以看到客户的消息,但尝试回复会提高"ROOM_ACCESS_DENIED",这意味着他还没有被添加到房间。但我想我已经用group.add(room.group_name, users_and_channels[random_available_staff]) 做到了。
无论如何,大概最有效的方法是在客户按下按钮时将有关聊天室的数据发送到工作人员的receive_json(self, content) 实例,对吧?但是该函数通过以下方式从template 中的Javascript 接收数据:
socket.send(JSON.stringify({
"command": "join",
"room": roomId
})
如果可能,我如何使用消费者.py 本身中的消费者将有关客户聊天室的数据发送到员工的receive_json()?如果不是,我应该使用哪些其他方法?
【问题讨论】: