Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 150071

send my response for 2 groups via self.channel_layer.group_send()

$
0
0

I'm using django channels 2 , for making a one to one private chat. And after spending a LOT OF TIME i'm just out of any other solution for my problem I have two html files: inbox.html shows list of all user history that i had chat with them and it is ordered by last updated time(last chat with each user) and if you click on one of them then you see the other file showing the chat room. I want to use my ChatConsumer for two urls.

I send my_response in websocket_receive function and then receive it in socket.onmessage in template

THE PROBLEM IS I can't do it for both urls.

I want to send it into my inbox too because I want to reOrder the chat user lists every time I send a message.so I made a group for inbox in my consumers as I did for my chat_room in websocket_connect function:

    inbox_room = f"inbox_{me.id}"
    self.inbox_room=inbox_room
    await self.channel_layer.group_add(
        inbox_room,
        self.channel_name
    )

and then I tried two ways: 1- just use channel_layer.group_send for both of them:

await self.channel_layer.group_send(
    self.chat_room,
    self.inbox_room,
    {
        "type": "chat_message",
        "text": json.dumps(my_response)
    }
)

and then using :

async def chat_message(self,event):
    await self.send({
        "type": "websocket.send",
        "text":event['text'] 
    })

it gives me error:

  group_send() takes 3 positional arguments but 4 were given

2-If code it twice for each of the groups like this:

    await self.channel_layer.group_send(
        self.chat_room,
        {
            "type": "chat_message",
            "text": json.dumps(my_response)
        }
    )

  await self.channel_layer.group_send(
        self.inbox_room,
        {
            "type": "inbox_messages",
            "text": json.dumps(my_response)
        }
    )

and then later two functions for sending both of them:

async def chat_message(self,event):
    await self.send({
        "type": "websocket.send",
        "text":event['text'] 
    })

async def inbox_messages(self, event):    
    await self.send({
        "type": "websocket.send",
        "text": event['text']
    })

the result is having a duplicated message in my chat and again I can't use it for my inbox.

my script in inbox.html is :

{% block more_js %}
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"> //for Using moment.js </script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js'>
// for using reconnectingWebsocket 
</script>
<script>
var loc = window.location
var wsStart = 'ws://'
if(loc.protocol == 'https:'){
    wsStart ='wss://'
}
var endpoint = wsStart + loc.host + loc.pathname
var socket = new ReconnectingWebSocket(endpoint) {# Reconnecting #}
//message i recieve
socket.onmessage = function(e){
    console.log("message",e)
    var chatDataMsg = JSON.parse(e.data)
    {############# INBOX UPDATE  ###########}


    {####change time####}
    $(`#chatter-${chatDataMsg.thread_id}`)[0].innerHTML=(moment(chatDataMsg.timestamp).format('MMM. D, Y, h:mm a') )
    console.log(chatDataMsg.thread_id)

    var chatters = $(".chatter");
    console.log(chatters)
    var cc = chatters.sort(function(a,b){
         var  a_time =  new Date(( moment($(`#chatter-${a.attributes.id.value}`)[0].innerHTML,'MMM. D, Y, h:mm a').format('YYYY/MM/DD hh:mm:ss')))
         var   b_time = new Date(( moment($(`#chatter-${b.attributes.id.value}`)[0].innerHTML,'MMM. D, Y, h:mm a').format('YYYY/MM/DD hh:mm:ss')))
        return a_time < b_time
    })
    console.log(cc)
    cc.detach()
    $("#inbox-items").append(chatters)


}
socket.onopen = function(e) {
    console.log("open", e)
}
socket.onerror = function(e){
    console.log("error",e)}
socket.onclose = function(e){
    console.log("close",e)}
</script>
{% endblock %}

I copied them from the parts of my messaging.html that was needed for updating inbox but in messaging there are other codes for append the chat and other things.

I want to know how to really use my consumer for both urls because the documentation says I can have routing.py like this:

URLRouter([
    url(r"^longpoll/$", LongPollConsumer),
    url(r"^notifications/(?P<stream>\w+)/$", LongPollConsumer),
    url(r"", AsgiHandler),
])

the documentation link for routing is : https://channels.readthedocs.io/en/latest/topics/routing.html

and my routing.py

application = ProtocolTypeRouter({
    'websocket':AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [   url(r"^messages/$", ChatConsumer),
                    url(r"^messages/(?P<username>[\w.@+-]+)/$",ChatConsumer),

                 ]
            )
        )
    )
})

so there must be a correct way to use it and maybe I don't know because i'm new to channels and i really have problem with the javascript parts in templates that i just copied them :))

or is there any other way to update other template when I send a new message in my chat room?


Viewing all articles
Browse latest Browse all 150071

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>