"""注释""" import pydash from channels.generic.websocket import AsyncJsonWebsocketConsumer class websocket(AsyncJsonWebsocketConsumer): async def connect(self) -> None: """ 前端请求: wss://wecom.fujugongxiang.com/web/room_name_value/ room_name_value 来自 URL 路径: path("web//", websocket.as_asgi()) """ # 获取 URL 参数 user_openid = self.scope["url_route"]["kwargs"].get("room_name", "") if not user_openid: await self.close(code=4001) # 关闭连接(可选) return # 接受连接 await self.accept() # 将用户加入组(异步直接 await) await self.channel_layer.group_add(group=user_openid, channel=self.channel_name, ) # 返回 channel_name 给前端(可选) await self.send_json(content={"channel_name": self.channel_name}) async def disconnect(self, close_code) -> None: """ 断开连接时触发 """ user_openid = self.scope["url_route"]["kwargs"].get("room_name", "") if user_openid: # 从组中移除(异步) await self.channel_layer.group_discard(group=user_openid, channel=self.channel_name, ) # 自动清理,无需 raise StopConsumer() async def receive_json(self, content, **kwargs) -> None: """ 收到前端发来的 JSON 消息 """ print("收到消息:", content) # 回显 await self.send_json(content=content) # 自定义事件处理器(会被 group_send 触发) async def chat_messages(self, event) -> None: """ 处理 chat_messages 事件 """ data = pydash.get(event, "message") print("chat_messages 收到数据:", data) await self.send_json(content=data) async def chat_subMsg(self, event): """ 处理 subMsg 回调 """ pass async def chat_hongBao(self, event): """ 处理红包事件 """ print(event, "========== chat_hongBao 被触发 ============") channel_id = pydash.get(event, "message.channelID") await self.receive_json(content={"demo": "text"}) async def commandsSendStr(self, event): """ 发送命令 """ await self.send_json(content={"commands": "demo这是个测试的数据", "type": "commands"}) async def chat_demo(self, event): """ demo 测试事件 """ print("chat_demo 被调用:", event) await self.receive_json(content={"demo": "demo_test"})