Pages Menu
TwitterRssFacebook

Posted by on May 19, 2015 in Learn Skype Web SDK

Learn Skype Web SDK Day 14 : Sending Instant Messages

Learn Skype Web SDK Day 14 : Sending Instant Messages

[contemplate-1]
View Demo

Once you’ve found the person you want to start a conversation with and set up and started the conversation – actually sending messages is a one-liner. However, the reason that it’s got it own section is that you can’t just send messages into a conversation once you’ve started it.

A newly created conversation will start Disconnected. When you call start() it will change to Created briefly before changing to Connecting. Once it’s been accepted by the other party it will change to Connected. Once one side closes the conversation its state will change back to Disconnected. You can only send IMs whilst the state is Connected, so you need to monitor this state.

To monitor the state, register a listener on the state property of the chatService, a member of the conversation. Do this before you call start() otherwise you’ll miss vital states:

var application = new Skype.Web.Model.Application;
//do sign-in process
var conversation = application.conversationsManager.createConversation();
//set up the conversation, add participants etc.
conversation.chatService.state.changed(function(newState) {
//evaluate the new state
});
//...
conversation.chatService.start();

Once the state has changed to Connected, you can then send messages, using this one-liner:

conversation.chatService.sendMessage('message to send');

In the code sample below, once the user is signed in they can send instant messages to another user:

 <div class="form-horizontal">
    <div class="form-group">
      <label for="message" class="col-sm-2 control-label">Send Message:</label>
      <div class="col-sm-10">
        <input type="email" class="form-control" id="message" placeholder="Message to send">
      </div>
    </div>  

    <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button class="btn btn-default" id="btnSendIM" disabled="disabled">Send IM</button>
      </div>
    </div>
  </div>
   <div id="footer"></div>
  
  <!-- This is not needed for the samples to run, but adds standard headers and footers to the samples, to display title, instructions, about etc.
       If you're taking this code and using it yourself, you can remove this.-->
   <script type="text/javascript" src="../../assets/layoutcodesample-min.js"></script>
  
  <script type="text/javascript">

  <!-- These variables are only needed for laying out the code sample, they are not part of the sample code. -->
  var pageTitle = 'Sending Instant Messages';
  var blogPostLocation = "http://thoughtstuff.co.uk";
  var githubLocation = "http://github.com";
 

  var client;
  $(function () {
    'use strict';

	Skype.initialize({
            apiKey: 'SWX-BUILD-SDK',
        }, function (api) {
            client = new api.application();           
			
		// whenever client.state changes, display its value
		client.signInManager.state.changed(function (state) {
		$('#loginStatus').text("Login State: " + state);
		});
	
        }, function (err) {
            alert('Error loading Skype Web SDK: ' + err);
        }); 
		
    $('#btnLogIn').click(function () {

        // start signing in
        client.signInManager.signIn({
          username: $('#username').val(),
          password: $('#password').val()
        }).then(function () {
            //log in worked!
            alert('Logged in!');
            $('#btnStartConversation').prop('disabled', false);
            
          }, function (error) {
            //Something went wrong.
            alert(error);
          });
      });

    $('#btnLogOut').click(function () {
        // start signing out
        client.signInManager.signOut()
        .then(function () {
               //log out worked!
               alert('Logged out!');
               $('#btnStartConversation').prop('disabled', true);
               $('#btnSendIM').prop('disabled', true);
             }, function (error) {
                //Something went wrong.
                alert(error);
              });
      });

    $('#btnStartConversation').click(function () {
      StartConversation($('#contact').val());
    });

        $('#btnSendIM').click(function () {
      conversation.chatService.sendMessage($('#message').val());
    });

  function StartConversation (contactSIP) {
  //first, get the person to start a conversation with. Assume one person.
  var person;
  GetContactFromName(contactSIP).then(function (results) {
    results.forEach(function (result) {
    person = result.result;          
  });

 //create the conversation object
 conversation = client.conversationsManager.createConversation();

 //add the person to the conversation by creating a conversation participant object
 var convParticipant = conversation.createParticipant(person);
 conversation.participants.add(convParticipant);

 //add the newly created conversation to the ConversationManager list
 client.conversationsManager.conversations.add(conversation);

//register for the conversation state changing to connected.
  conversation.chatService.state.changed(function(newState){
  $('#lblConversationState').text(newState);
  if (newState == 'Connected') {
    $('#btnSendIM').prop('disabled', false); //safe to send IMs now
  }
});
 
 conversation.chatService.start();
});

}

function GetContactFromName(contactSIP)
{
 var query = client.personsAndGroupsManager.createPersonSearchQuery();
 query.text(contactSIP);
 query.limit(1);
 return query.getMore();          
}

});

</script>

Demo Online

You can try this code out against your own Skype for Business environment by going to the demo page. From here you can also download the code from GitHub if you want to host it locally, or take it and use it in your next project.
[contemplate-2]

Written by Tom Morgan

Tom is a Microsoft Teams Platform developer and Microsoft MVP who has been blogging for over a decade. Find out more.
Buy the book: Building and Developing Apps & Bots for Microsoft Teams. Now available to purchase online with free updates.

1 Comment

  1. On line 95 is an error, the SDK reacts poorly to not declared variables and breaks with an exception. The error is not easy to detect, as the errormessage tells something about an unexpected character.

Post a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.