使用Django频道向其他用户/群组发送消息

时间:2019-12-17 16:26:12

标签: python django django-channels

我正在尝试向除我自己(或已连接用户)以外的所有其他已连接用户发送通知。我有三个单独的用户帐户,并且我希望根据帐户类型向每个用户发送不同的消息。 “帐户类型1”,“类型2”和无授权用户”。         所有用户都位于单独的域上,并通过不同的路由连接到Web套接字。我希望能够让每个用户知道对方何时加入了连接/页面。但是,它当前正在显示已连接用户的消息。例如         当我以“帐户1”身份访问该页面时,得到“帐户1已加入该组”。但是,我不希望看到其他连接的用户何时加入。

在这里我可能会忽略一些简单的事情,因此请寻求一些建议。如果我尝试根据用户ID创建一个组。然后,仅当我正在访问该页面的帐户类型时,我才能看到正在发送的消息。

我有一个“预订”对象,正在使用ID来创建房间。连接后,我会将用户添加到组中,然后向该组发送消息。传递消息后显示带有jquery的消息。

 async def connect (self):

        Join room group and
        announce connection.


    account = self.scope["user"]

    self.booking_id = self.scope['url_route']['kwargs']['booking_id']
    #self.user_id = self.scope['url_route']['kwargs']['user_id']

    self.room_group_name = 'booking_%(booking_id)s' % { 
        'booking_id': self.booking_id,
    }


    await self.channel_layer.group_add (
        self.room_group_name,
        self.channel_name,
    )

    account_type = 'Account 1' ## Get account type from scope?

    await self.channel_layer.group_send (
        self.room_group_name,
        {
            'type': 'booking_message',
            'message': {
                # 'display_to': 'all',
                'level': 'success',
                'account': str(account),
                'account_type': str(account_type),
                'message': _ ('Welcome to the page!'),
                'join_message': _('{account_type} has joined the booking.'.format (account_type = account_type)),
            },
        },
    )
    await self.accept ()

0 个答案:

没有答案