实时聊天中如何改变消息设计

我有一个实时聊天的项目,其中我有两种类型的用户:学生和教师。我想改变教师信息的设计。我试着改变consumer.py,并尝试与模板一起工作,但它没有工作,我想我们可以做到这一点,如果我们将与消费者.py一起工作。我认为我们可以做到这一点,如果我们将与消费者.py一起工作。谁知道如何实现?

models.py

class CustomUser(AbstractUser,mixins.GuardianUserMixin): 
    email =  models.EmailField(_('email_address'), unique=True, name='email')
    username =  models.CharField(_('username'), unique=True, max_length=128)
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()

消费者.py

class Consumer(WebsocketConsumer):
def connect(self):
    self.room_name=self.scope['url_route']['kwargs']['room_name']
    self.room_group_name='chat_%s' % self.room_name
    self.name = self.scope['user'].username
    if self.scope['user'].is_anonymous:
        self.send({'close':True})
    else:
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                "type":"chat_message",
                "message":self.name+" Joined Chat "
            }
        )
        self.accept()

def disconnect(self, code):
    async_to_sync(self.channel_layer.group_send)(
        self.room_group_name,
        {
            "type":"chat_message",
            "message":self.name+" Left Chat"
        }
    )
    async_to_sync(self.channel_layer.group_discard)(
        self.room_group_name,
        self.channel_name
    )
def receive(self, text_data=None, bytes_data=None):
    text_data_json=json.loads(text_data)
    message=text_data_json['message']

    async_to_sync(self.channel_layer.group_send)(
        self.room_group_name,
        {
            'type':'chat_message',
            'message':self.name+" : "+message 
        }
    )

def chat_message(self,event):
    message=event['message']

    self.send(text_data=json.dumps({
        'message':message
    }))

模板

<div class="ui form">
  <div style="height:400px;width:100%;overflow-y:scroll" id="div_data"></div>
  <input type="text" name="message" id="message" placeholder="Message" style="padding:10px;width:100%; border-radius: 0px;">

 <script>
    var roomName='{{ room_name }}';
    var personname='{{ request.user.username }}';
    var chatSocket=new WebSocket('ws://'+window.location.host+'/ws/chat/'+roomName+'/');
    {% if request.user.is_anonymous %}
        window.location.pathname = '{% url 'users:login' %}'
        {% endif %}
    chatSocket.onmessage=function(e){
        var data=JSON.parse(e.data)
        var message=data['message']
        var div=document.querySelector("#div_data");
        div.innerHTML+='<br><img class="ui avatar image" style="margin-left:2px;" src="{{user.profile.get_picture}}"><a style="padding:10px; margin-bottom:8px; " class="ui left pointing grey basic label">'+message+'</a>';
        console.log(e)

    }
    chatSocket.onclose=function(e){ 
        var data=JSON.parse(e.data)
        console.log(data)
        var message=data['message']
        var div=document.querySelector("#div_data");
        div.innerHTML+='<br><img class="ui avatar image" src="{% static "img/tom.jpg" %}"><a style="padding:10px; margin-bottom:8px;" class="ui right pointing teal basic label">'+message+'</a>';
    }
    document.addEventListener("keydown", function(event){
      if(event.which == 13){
        var message=document.querySelector("#message").value;
        if(message.length == 0){
          return false
        }else{
          chatSocket.send(JSON.stringify({'message':message}))
          document.querySelector("#message").value=''
        }

      }
      })
</script>

解决方案:

只要在老师发送消息时,在发送字典中添加一个键 “老师”:True或类似的东西。

def chat_message(self,event):
    message=event['message']
    dict_to_send = {'message':message}

    if self.name in teachers_list:
        dict_to_send['teacher'] = True
    self.send(text_data=json.dumps(
        dict_to_send
    ))

然后在js中。

const data = JSON.parse(e.data);
    if(data.teacher){
        //this style
    {
    else{
        //that style
    }

给TA打赏
共{{data.count}}人
人已打赏
未分类

在Chrome扩展中的UMD模块

2022-9-8 4:24:27

未分类

简单的Python登录网页抓取

2022-9-8 4:24:29

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索