如何使用pubnub chatengine添加私人一对一聊天?

时间:2019-01-08 10:09:48

标签: javascript chat pubnub

实际上

  1. 我使用PubNub的聊天引擎创建了聊天应用程序,但无法在同一频道上实现两个用户的私人聊天。这意味着我有一个管理员和多个其他用户,因此他们可以与admin聊天,而admin可以与其他用户聊天,但是,同一频道的其他用户不应看到一个用户和admin聊天,即我要在两个用户之间实现的私人聊天同一频道。 因此,请任何人参考或使用聊天引擎示例私人聊天源代码。

  2. 第二个问题是显示带有gr的个人资料照片

PubNub的头像插入,这也是我无法显示。请也分享这个。

这是我的Javascript文件:

        //create a new instance of ChatEngine
        ChatEngine = ChatEngineCore.create({
            publishKey: key
            subscribeKey: key
        },{ debug: true});

        // create a bucket to store our ChatEngine Chat object
        let myChat;

        // create a bucket to store 
        let me;

        // these function is used for typing indicator
        let sendmsg = function () {};
        let keypress = function () {};

        // create an optional config object to increase the default 
            timeout from 1000ms
        let typingconfig = { timeout: 1000 };

        // compile handlebars templates and store them for use later
        let peopleTemplate = Handlebars.compile($("#person- 
           template").html());
     let meTemplate = Handlebars.compile($("#message-template").html());
    let userTemplate = Handlebars.compile($("#message-response- 
           template").html());

        let searchconfig = { prop: 'state.full', caseSensitive: false }
        // this is our main function that starts our chat app
        const init = () => {
        ChatEngine.connect ('email', { username: 'name', full:'K' },
        'auth-key');

        // when ChatEngine is booted, it returns your new User as 
          `data.me`
        here my function is called by the pubnub

        ChatEngine.on('$.ready', function(data) {
        // store my new user as `me`
        me = data.me;
        //create a new ChatEngine Chat and I am connecting to chatenging
       using this option.
        myChat = new ChatEngine.Chat('chat-engine-server',true);      

        // here i am updating the the state of the user
        me.update(
        {
         full:'John Doe', 
         username: 'John',
         uuid: 'johndoe@gmail.com'
        });
        //starting private chat logic
        // this is what I wrote the code that use to create the privat 
         chat 

       myChat.invite(' invited email');

        me.direct.on('$.invite', (payload) => {
        console.log("invited user");    
        let secretChat = new ChatEngine.Chat(payload.data.channel);            
        document.getElementById("punlicLog").style.display = 'none';
        document.getElementById("privateLog").style.display = 'inline';
        document.getElementById("message-to-send").style.display='none';
        document.getElementById("private-message-to-send").
               style.display='inline';            
        here I am sending message to this payload
        secretChat.on('message', (payload) => {
          console.log(payload);
      // using this methd i am rendering private message
          privaterenderMessage(payload);
          });            
          //$('#privateLog').append("Now you are in a Private Chat with " 
          + globalUsr );            

       // this is take the message from the input box to send
        $("#privateMessage").keypress(function (event) {
        if (event.which == 13) {
        secretChat.emit('message', {
        text: $('#privateMessage').val()
         });
        $("#privateMessage").val('');
        event.preventDefault();
        }
        }); });

         //ending private chat message

        // this part belong to the pic
        console.log("before gravator'''''''''''''''''': ")  
        user = new ChatEngine.User(me.state.username, {email: 
         me.state.uuid});
                    console.log(" full name : "+me.state.full); 
                    $("#pic").attr("src", user.state.gravatar);

          myChat.on('message', (message) => {
                  console.log("message send mychat.on() method to send 
                      ");
                  renderMessage(message);
              });
              // when a user comes online, render them in the online list
              });

              bind our send button and return key to send message
              $('#sendMessage').on('submit', sendMessage)

          });

        };

        send a message to the Chat
        const sendMessage = () => {

            get the message text from the text input
            let message = $('#message-to-send').val().trim();

           if the message isn't empty
            if (message.length) {

                emit the message event to everyone in the Chat
                myChat.emit('message', {
                    text: message
                });

                // clear out the text input
                $('#message-to-send').val('');

            }

            // stop form submit from bubbling
            return false;

        };

        // render messages in the list
        const renderMessage = (message, isHistory = false) => {

            // use the generic user template by default
            let template = userTemplate;

            // if I happened to send the message, use the special 
               template for myself
            if (message.sender.uuid == me.uuid) {
                template = meTemplate;
            }

            let el = template({
                messageOutput: message.data.text,
                time: getCurrentTime(),
                user: message.sender.state
            });

            // render the message
            if(isHistory) {
              $('.chat-history ul').prepend(el); 
            } else {
              $('.chat-history ul').append(el); 
            }

            // scroll to the bottom of the chat
            scrollToBottom();
        };
        // end of render message 

        const privaterenderMessage = (message, isHistory = false) => {

            // use the generic user template by default
            let template = userTemplate;

            // if I happened to send the message, use the special 
           template for myself
            if (message.sender.uuid == me.uuid) {
                template = meTemplate;
            }

            let el = template({
                messageOutput: message.data.text,
                time: getCurrentTime(),
                user: message.sender.state
            });

        init();



        This is my Html Page to display the chat messages to the user
        <!DOCTYPE html>

<body>  
                <div class="container clearfix">
                    <div class="people-list" id="people-list">
                        <input type="text" id="search-user" 
        placeholder="Search user">
                         <ul class="list">
                        </ul>
                    </div>

                    <div class="chat">

                        <div class="chat-header clearfix">
                            <!-- <img src="" alt="avatar" /> -->
                            <div class="chat-about">
                                <div class="chat-with">ChatEngine Demo 
                    Chat</div>
                            </div>
                        </div>

                         here i am display ing globle chat messaage
                        <div class="chat-history " id="punlicLog">
                            <ul></ul>
                        </div>

                     here I will display the private chat message of the 
                      user
                        <div class="private-chat-history" id="privateLog" 

                style="display: none">
                            <ul></ul>
                        </div>

                        <span class="badge badge-pill badge-success" 
             id="typing" style="color:green"></span>

                   <form id="sendMessage" class="chat-message clearfix">
                  <input type="text" name="message-to-send" id="message- 
     to-send"
    placeholder="Type your message" rows="1"  
       onkeypress="keypress(event)"></input>
                            <input type="text" name="message-to-send" 
          class=
       "form-control" id="private-message-to-send" style="display: none" 
    placeholder
     ="Your message here..." onkeypress="keypress(event)">
                            <input type="submit" value="Send" >
                        </form>
                        <!-- end chat-message -->

                    </div>

                    <!-- end chat -->
                </div>
                <!-- end container -->

                 <!-- dynamic message display using javascript with the 
        pubnub -->
                 <script id="message-template" type="text/x-handlebars- 
      template">
                    <li class="clearfix">
                        <div class="message-data align-right">
                            <span class="message-data-time">{{time}}, 
             Today</span> &nbsp; &nbsp;
                            <span class="message-data-name"> 
      {{user.first}}</span> <i class="fa fa-circle me"></i>
                        </div>
                        <div class="message other-message float-right">
                            {{messageOutput}}
                        </div>
                    </li>
                </script>
                <script id="message-response-template" type="text/x- 
            handlebars- 
      template">
                    <li>
                        <div class="message-data">
                            <span class="message-data-name"><i class="fa 
           fa- 
        circle online"></i> {{user.first}}</span>
                            <span class="message-data-time">{{time}}, 
       Today</span>
                        </div>
                        <div class="message my-message">
                            {{messageOutput}}
                        </div>
                    </li>
                </script>


                    <!-- // starting private message rendering -->


                    <script id="private-message-template" type="text/x- 
         handlebars-template" style="display: none">
                        <li class="clearfix">
                            <div class="message-data align-right">
                                <span class="message-data-time">{{time}}, 
          Today</span> &nbsp; &nbsp;
                          <span class="message-data-name">{{user.first}} 
        </span> <i class="fa fa-circle me"></i>
                            </div>
                         <div class="message other-message float-right">
                                {{messageOutput}}
                            </div>
                        </li>
                    </script>
            <script id="private-message-response-template" type="text/x- 
        handlebars-template" >
                        <li>
                            <div class="message-data">
                         <span class="message-data-name"><i class="fa fa- 
         circle online"></i> {{user.first}}</span>
                                <span class="message-data-time">{{time}}, 
      Today</span>
                            </div>
                            <div class="message my-message">
                                {{messageOutput}}
                            </div>
                        </li>
                    </script>
                    <!-- // ending private message rendering -->


          <script id="person-template" type="text/x-handlebars-template">
                    {{#if state.full}}
                    <li class="clearfix" id="{{uuid}}">
                     <img src="" alt="photo"id="pic" style="height: 5px; 
       width: 5px"/>
                        <div class="about">
                            <div class="name">{{state.full}}</div>
                            <div class="status">
                              <i class="fa fa-circle online"></i> online
                            </div>
                        </div>
                    </li>
                    {{/if}}
                </script>
            </body>

      I want a private chat between the two users of the same channel and 
 multiple users also there and profile pic with gravatar also want`enter 
       code here.

1 个答案:

答案 0 :(得分:1)

使用PubNub和ChatEngine,您需要为每个聊天室使用单独的渠道。您不能使用同一频道进行私人和公开聊天。每个用户可以同时在许多频道上订阅许多聊天。当您使用ChatEngine方法创建私人聊天时,只有所涉及的用户才能看到该聊天。 ChatEngine "invite" for private chat documentation在这里。

私人聊天

某些客户的代码

// one non-admin user running ChatEngine
let secretChat = new ChatEngine.Chat('unique-secret-channel');
secretChat.invite(adminUserObject);

管理员的客户代码

// This code goes in the admin client
me.direct.on('$.invite', (payload) => {
    let privChat = new ChatEngine.Chat(payload.data.channel, true);
});

墓碑

当用户将电子邮件作为其状态对象的一部分进行连接时,此方法有效。然后,您必须初始化gravatar插件。有一个ChatEngine Gravatar Example here

// include the gravatar plugin script above    
ChatEngine.connect(uuid, { email: email@email.com });

// ...

for (let user of ChatEngine.users) {
    user.plugin(ChatEngine.plugin.gravatar());
    let div = document.createElement("div");
    div.innerHTML = '<img src="' + user.state().gravatar + '" height="40" width="40"/>';
    // add html to the web page
}