Skip to main content

How to integrate pubnub chat in website?

Integrate pubnub chat

 
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.7.2.3.min.js"></script>

<style>

.user_pubnub_mgs {

    height: 450px;

    border: 1px solid #d0d0d0;

    padding: 10px 12px;

    overflow-y: auto;

}

.other_user_chat {

    background: #b4b4b4;

    margin-bottom: 10px;

    padding: 10px;

    width: fit-content;

    font-size: 14px;

    border-radius: 10px 0px 10px 10px;

    color: #fff;

    display: block;

    word-break: break-word;

}

.current_user_chat {

    background: #2695ee;

    margin-bottom: 10px;

    padding: 10px;

    width: fit-content;

    font-size: 14px;

    border-radius: 10px 0px 10px 10px;

    color: #fff;

    display: block;

    word-break: break-word;

    margin-left: auto;

}

#send_chat_bt {

    background: #2695ee;

}

#send_chat_bt[disabled] {

    background: #dadada !important;

}

</style>

<script>

const buttonClick = () => {

    var input = document.getElementById('message-input');

    publishMessage(input.value);

    input.value = '';

};


const delete_full_messages = () => {

    var channel_name = "hello_world";

    pubnub_delete_full_messages(channel_name);

};


const showMessage = (msg) => {

var message = '';

msg = msg;

if(msg !== null && msg !== ""){

    var currentUserId = {{ auth('customer')->user()->id }};

    console.log(msg);

    var user_class = '';

    if (currentUserId == msg.user_id) {

        user_class = "current_user_chat";

    }

    else{

        user_class = "other_user_chat";

    }

    console.log(user_class);

    message = "<div class='chat_messages " + user_class + "'>" + msg.chat_message     + "</div>"

    $('#messages').append(message);

    if(message){

         const divElement = $(".user_pubnub_mgs");

        const innerScrollHeight = divElement.prop("scrollHeight") - divElement.height();

        $(".user_pubnub_mgs").animate({

            scrollTop: $('.user_pubnub_mgs').offset().top + innerScrollHeight

        }, 0); 

    }  

}  

};



const appendMessageToWebPage = (message) => {

    myObj = message.entry.chat_message;

    if (myObj !== null && typeof myObj !== 'undefined') {

        showMessage(message.entry);

    }

}


let pubnub;

const setupPubNub = () => {

    // Update this block with your publish/subscribe keys

    pubnub = new PubNub({

        publishKey: "pub-c-52377dc0-a888-44a0-841f-825b319416b9",

        subscribeKey: "sub-c-c2a10f4c-394c-4b89-ba16-4de660c4f0b0",

        userId: "1"

    });


    // add listener

    const listener = {

        status: (statusEvent) => {

            if (statusEvent.category === "PNConnectedCategory") {

                console.log("Connected");

            }

        },

        message: (messageEvent) => {


            // handle message

            const channelName = messageEvent.channel;

            const channelGroup = messageEvent.subscription;

            const publishTimetoken = messageEvent.timetoken;

            const msg = messageEvent.message;

            const publisher = messageEvent.publisher;


            //show time

            const unixTimestamp = messageEvent.timetoken / 10000000;

            const gmtDate = new Date(unixTimestamp * 1000);

            const localeDateTime = gmtDate.toLocaleString();



            showMessage(messageEvent.message);


        },

        messageAction: function(ma) {

            // handle message actions

            console.log('messageAction');

        },

        presence: (presenceEvent) => {

            // handle presence

            console.log('working');

        }


    };

    pubnub.addListener(listener);


    // subscribe to a channel

    pubnub.subscribe({

        channels: ["hello_world"]

    });



    pubnub.history({

        channel: 'hello_world',


    }, function(status, response) {

/*         console.log(response.messages); */

        if (response.messages.length) {

            console.log(response.messages);

            response.messages.forEach(appendMessageToWebPage);

        }


    });


};


// run after page is loaded

window.onload = setupPubNub;

// publish message

const publishMessage = async (message) => {

    // With the right payload, you can publish a message, add a reaction to a message,

    // send a push notification, or send a small payload called a signal.

    var currentUserId = {{ auth('customer')->user()->id }};

    const publishPayload = {

        channel: "hello_world",

        message: {

            title: "User Chat",

            type: "user_chat",

            chat_message: message,

            user_id: currentUserId,

            read: 0,

        }

    };

    await pubnub.publish(publishPayload);

}

// Delete_messages message

const pubnub_delete_full_messages = async (channel_name) => {

    // With the right payload, you can publish a message, add a reaction to a message,

    // send a push notification, or send a small payload called a signal.

    try {

        const result = await pubnub.deleteMessages({

            channel: channel_name,

            //start: "15088506076921021",

            //end: "15088532035597390",

        });

    } catch (status) {

        console.log(status);

    }

}

</script>

<div class="ps-section__header">

    <h3>Messages</h3>


    <!-- <div class="float-right">

            <a class="add-address ps-btn ps-btn--sm ps-btn--small" href="{{ route('customer.address.create') }}">

                <span>{{ __('Add a new address') }}</span>

            </a>

        </div> -->

</div>

<div class="ps-section__content">

    <div>

<!--         <button onclick="delete_full_messages()">Delete messages</button> -->

        <div id="messages" class="user_pubnub_mgs"></div>

        <input id="message-input" type="text">

        <button onclick="buttonClick()" id="send_chat_bt">Send</button>

    </div>

</div>

<script>

$(document).ready(function(){

    $("body").on("click, keyup","#message-input", function(){

    var message_body =  $(this).val();

        if(message_body){

            $("#send_chat_bt").prop('disabled', false);

        }

        else{

            $("#send_chat_bt").prop('disabled', true);

        }

    });

    $(document).on('keyup','#message-input',function(e){

            if (e.code === "Enter") {  //checks whether the pressed key is "Enter"

                buttonClick();

            }

    });

});


</script>


Comments

Popular posts from this blog

How to use inner html value or data in php from javascript(innerHTML)?

 use inner html value or data in php from javascript(innerHTML)? <html> <body> <p id="demo">use inner html value in php(innerhtml)</p> <script>   var jassi = document.getElementById("demo").innerHTML;   //document.write(jassi); </script> <?php $jassi = '<script>document.write(jassi);</script>'; echo $jassi; ?> </body> </html>

How to get store data from WCFM(Best Multi Vendor Marketplace) Plugin?

 Get store data from WCFM(Best Multi Vendor Marketplace) Plugin. global $WCFM, $WCFMmp, $wp, $WCFM_Query, $post; $store_id = ''; if ( isset( $attr['id'] ) && !empty( $attr['id'] ) ) { $store_id = absint($attr['id']); } if (  wcfm_is_store_page() ) { $wcfm_store_url = get_option( 'wcfm_store_url', 'store' ); $store_name = apply_filters( 'wcfmmp_store_query_var', get_query_var( $wcfm_store_url ) ); $store_id  = 0; if ( !empty( $store_name ) ) { $store_user = get_user_by( 'slug', $store_name ); } $store_id    = $store_user->ID; } $user_id = $store_id;  $vendor_data = get_user_meta( $user_id, 'wcfmmp_profile_settings', true ); $street_1 = $vendor_data['address']['street_1']; $street_2 = $vendor_data['address']['street_2']; $city     = $vendor_data['address']['city']; $zip      = $vendor_data['address']['zip&#

How to create login with phone number in woocommerce wordpress?

Create login with phone number in woocommerce wordpress. function wooc_extra_register_fields() {?>        <p class="form-row form-row-wide">        <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?><span class="required">*</span></label>        <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />        </p>            <?php  }  add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );  function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) { if ( isset( $_POST['billing_phone'] ) ) {    $hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);    if ( !empty($hasPhoneNumber)) {      $validation_er