Connecting to MSN Messenger without using the Windows Live Agent SDK
Many developers have created programs, known as agents or bots, which connect to msn and allow users to chat with the agent. Microsoft is ending its support for creating agents using the Windows Live Agent SDK. Is it possible for a program to connect MSN without using the Windows Live Agent SDK? Yes, I’ll show you how to connect to MSN using the MSNP-Sharp API. I found this blog post basically stating that Microsoft will stop supporting its Live Agents SDK.



Microsoft will support self-hosting until June 30, 2009. After that

date, Microsoft is no longer supporting the Agents product at all, and

we cannot guarantee that your SDK will be able to verify its license

certificate and continue to operate.



Thanks,



Britt Cooper - MSFT
Without the Live Agents SDK the only “reliable” method for connecting to MSN is to use a library that has reverse engineered the MSN Protocol and created an API to it. My personal favorite is MSNP-Sharp, a .Net API for connecting to MSN.
Here’s a quick start guide on how to use MSNP-Sharp.

To get started I will create a class called MyMsnConnector.
class MyMsnConnector
To get your application to connect to MSN you simply call the connect function.

e.g.


MyMsnConnector myMsn = new MyMsnConnector(“user”, “pass”);

myMsn.Connect();



MSNP works by throwing events for all of the actions that users can trigger on MSN. Thus the next step for creating the agent is to set up the event handlers.
   private void AddEventHandlers()<br/>    {<br/>        m_Messenger.Nameserver.ContactService.ReverseAdded += new EventHandler<ContactEventArgs>(OnReverseAdded); <br/>        m_Messenger.NameserverProcessor.ConnectingException += new EventHandler<ExceptionEventArgs>(OnConnectingException);<br/>        m_Messenger.Nameserver.ExceptionOccurred += new EventHandler<ExceptionEventArgs>(OnExceptionOccurred);<br/>        m_Messenger.Nameserver.AuthenticationError += new EventHandler<ExceptionEventArgs>(OnAuthenticationError);<br/>        m_Messenger.Nameserver.SignedIn += new EventHandler<EventArgs>(OnSignInCompleted);<br/>        m_Messenger.ConversationCreated += new EventHandler<ConversationCreatedEventArgs>(OnConversationCreated); <br/>    }

This code snippet does not show all of the event handlers, there are many more but this is enough to get a simple agent up and running. Most of the event handlers are self explanatory except for the ConversationCreated event. This is thrown when a user starts to chat with your bot and sets up event handlers for the conversation with that user. The event handlers set in the OnConversationCreated function are to core functionality for communicating with a user over MSN.
 /// <summary><br/>    /// Handle new conversation created.<br/>    /// Set conversation event handlers.<br/>    /// </summary><br/>    private void OnConversationCreated(object sender, ConversationCreatedEventArgs e)  <br/>   {<br/>        if (e.Initiator == null)<br/>        {<br/>            e.Conversation.Switchboard.UserTyping += new EventHandler<ContactEventArgs>(OnUserTyping);<br/>            e.Conversation.Switchboard.TextMessageReceived += new EventHandler<TextMessageEventArgs>(OnTextMessageReceived);<br/>            e.Conversation.Switchboard.ContactLeft += new EventHandler<ContactEventArgs>(OnContactLeft);<br/>            e.Conversation.Switchboard.NudgeReceived += new EventHandler<ContactEventArgs>(OnNudgeReceived);  <br/>        }<br/><br/>    }
Below we find the event handlers for when a user sends a message of action to the agent. The agent will deal with the event and respond appropriately.
 private void OnUserTyping(object sender, ContactEventArgs e)<br/>    {<br/>        Debug.WriteLine("User Typing: " + e.Contact.Mail);<br/>    }<br/><br/><br/>    /// <summary><br/>    /// Handle nudge received from user.<br/>    /// </summary><br/>    private void OnNudgeReceived(object sender, ContactEventArgs e)<br/>    { <br/>        TextMessage msg = new TextMessage("What is your problem!?");<br/>        ((SBMessageHandler)sender).SendTextMessage(msg);     <br/>    }<br/><br/>    /// <summary><br/>    /// Handle incoming text message.<br/>    /// </summary><br/>    private void OnTextMessageReceived(object sender, TextMessageEventArgs e)<br/>    {<br/>      	Debug.WriteLine("Received Message from " + e.Sender.Mail + ": " + e.Message.Text);<br/><br/>        SBMessageHandler handler = sender as SBMessageHandler;<br/>        handler.SendTypingMessage();<br/>         <br/>        TextMessage msg = new TextMessage("Hello, I am a real person. ;)");<br/>        handler.SendTextMessage(msg); <br/>        <br/>    	Debug.WriteLine("Sent Message: " + msg.Text);  <br/>    <br/>    }
Here’s the implementation of the rest of the event handlers that were added by the AddEventHandlers() function.

    /// <summary><br/>    /// A User adds the Bot to their contact list.<br/>    /// </summary><br/>    /// <param name="sender"></param><br/>    /// <param name="e"></param><br/>    private void OnReverseAdded(object sender, ContactEventArgs e)<br/>    {      <br/>        Debug.WriteLine("New Contact Added the bot: " + e.Contact.Name + " (" + e.Contact.Mail + ")");<br/>       <br/>        m_Messenger.Nameserver.ContactService.AddNewContact(e.Contact.Mail);<br/>        e.Contact.OnAllowedList = true;<br/>        e.Contact.OnForwardList = true;<br/>        e.Contact.OnBlockedList = false;<br/>        e.Contact.OnPendingList = false; <br/>        m_Messenger.Nameserver.SetPresenceStatus(PresenceStatus.Online);<br/>    }  <br/>   <br/><br/>    /// <summary><br/>    /// Handle Synchronization with msn server event.<br/>    /// </summary><br/>    private void OnSignInCompleted(object sender, EventArgs e)<br/>    {<br/>        m_Messenger.Nameserver.SetPrivacyMode(PrivacyMode.AllExceptBlocked);<br/>        m_Messenger.Nameserver.SetPresenceStatus(PresenceStatus.Online);<br/><br/>        PersonalizeMessenger();<br/>    }<br/><br/>   <br/><br/>    private void PersonalizeMessenger()<br/>    {<br/>        try<br/>        {<br/>            Image fileImage = Image.FromFile(ConfigurationSettings.AppSettings["ImageFileName"]); // MSN Avatar<br/>            DisplayImage displayImage = new DisplayImage();<br/>            displayImage.Image = fileImage;<br/>            m_Messenger.Owner.DisplayImage = displayImage;<br/>            m_Messenger.Nameserver.StorageService.UpdateProfile(fileImage, "MyPhoto");<br/>        }<br/>        catch<br/>        {<br/>            LogError(new StackTrace(true), "Error adding avatar image.");<br/>        }<br/><br/>        m_Messenger.Nameserver.Owner.PersonalMessage = new PersonalMessage(ConfigurationSettings.AppSettings["PersonalMessage"], MediaType.None, null, NSMessageHandler.MachineGuid);<br/>    }<br/><br/>    /// <summary><br/>    /// Handle authentication error event.<br/>    /// </summary><br/>    private void OnAuthenticationError(object sender, ExceptionEventArgs e)<br/>    {<br/>        LogError(new StackTrace(true), "AuthenticationError : " + e.Exception.Message);<br/>       <br/>    }<br/><br/>    /// <summary><br/>    /// Handle Exception event.<br/>    /// </summary><br/>    private void OnExceptionOccurred(object sender, ExceptionEventArgs e)<br/>    {<br/>        LogError(new StackTrace(true), e.Exception.Message);    <br/>    }<br/><br/>    /// <summary><br/>    /// Handle connecting exception event.<br/>    /// </summary><br/>    private void OnConnectingException(object sender, ExceptionEventArgs e)<br/>    {<br/><br/>        if (m_ConnectRetries < 5)<br/>        {<br/>            LogError(new StackTrace(true), String.Format("Connecting exception {0}: Retrying.", m_ConnectRetries.ToString()) );<br/>           <br/>            Thread.Sleep(10000); // Wait before trying to reconnect.<br/>            m_Messenger.Connect();<br/><br/>        }<br/>        else<br/>        {<br/>            LogError(new StackTrace(true), String.Format("Connecting exception {0}: Giving Up.", m_ConnectRetries.ToString()) );<br/>           <br/>        }<br/>    }
Finally for completeness here’s our error logging function:
 private void LogError(StackTrace st, string message)<br/>    {<br/>		Debug.WriteLine(message);<br/>    }<br/><br/>}

Comments...

Like to leave a comment ?


Title

Comment

Name