How I built an Ms Lync ‘Bot’ formally known as D.A.V.E.

Lync_LogoMicrosoft Lync is Microsoft’s latest offering of a unified communications system. Sporting features you’d expect to find in a SIP/Unified Comms client, Lync is a pretty powerful piece of kit.

What’s more, Microsoft offer an SDK to enable easy development of tools and add-ons using Lync technologies. Most of the tutorials and blog posts seem to focus on either C# or Silverlight, which is fine – however, as I am primarily a VB.Net developer I decided to publish my own guide on how to intercept and respond to received Lync messages.

Firstly, I need to point out that I have only had access to Lync for a couple of months now and only downloaded the SDK earlier this month.. So although the code below is functional, I am constantly learning and may find a better way of doing things as my learning continues. To make things easier, make sure you subscribe to the post and you’ll get an update each time I adjust the code.

You will need to download and install the Microsoft Lync SDK then fire up your copy of Visual Studio, create a new windows form project. Obviously you could use any type of project here, however I have plans for a GUI in the future so I am using a windows form project.

Now, open the code view of your new form and import the following:

Now, under your “Public Class Form1” but before your “Private Sub Form1_Load()” enter the following lines of code:

That’s all there is to it for the declarations, as you can see I have used ‘WithEvents’ to expose the ‘methods’ in the GUI and make things a little easier developing with them.

Next in the “Form_Load()” event, paste in the following code:

This essentially ties your code to the Lync client running on your machine, then using ‘automation’ it confirms the client is signed in, if not it signs in for you.

Now, your app is hooked into the Lync client, you will need to ‘capture’ the message received event and handle it appropriately.

As you can see from the post above, I am using the built in replace functionality of the string. This is because the Lync client passes line feeds after its message, which makes handling the received message quite complicated.

So, from the code above – each time an instant message is received by your Lync client the variable strRec will contain the received message.

Now, upon receipt of a message you may want to send a response – which is where my next code snippet comes in. The following Sub send’s an instant message to the participants of the conversation:

From the code above, you should see the sub requires a string to be passed to it. This is what will be relayed to the client who sent the original message.

So there you have it, a fairly simple way of receiving and sending back a Lync ‘IM’.

Obviously, you may want to improve this slightly by trimming the received message and handling it depending on the users request. So, for example – you may want to ‘serve’ a simple weather forecast based on the users request. To do this all you need to do is enhance the ‘_LocalIMModality_InstantMessageReceived’ sub to include code something like this:

Now, create another sub which makes use of Yahoo’s weather forecasting, to reply to the Lync user with details of the local forecast:

As you can see from the code above, I have also built in the functionality for the Lync user to request weather for a couple of locations around the UK. This could be increased to as many as you want, or removed to only send details of one particular place.

Some other things you might want to consider would be for your ‘Bot’ to query a SQL table and pass back the results, or perhaps perform other functionality such as PING a device and send the reply details in an IM.

In a future blog post I will show you how to connect your new ‘BOT’ into a AI handler to provide an AI Bot capable of holding a ‘conversation’ of sorts.

As per my opening paragraph, I am very much in the early days of my Lync development – so if you have any suggestions on how I could improve the code above, please get in touch.

Mike Hudson

Mike Hudson is a Infrastructure Analyst living and working in Kingston Upon Hull. With extensive experience in Microsoft and Apple technologies, ranging from desktop OS’s to Server OS’s and hardware. By day working as part of an infrastructure team, and by night ridding the world of IT issues through blog posts..

  • Phabrikam

    am not much of a dev, but how much of a challenge would it be to output data from a MS CRM to a lync powershell/.net bot? like when an update to an email is received for example to output to the lync persistent chat?

    • Hi, thanks for taking the time to comment.

      Yes, that would be possible… DAVE has now grown into something very similar, and now monitors many of our systems in our office. I actually send IM’s based on network monitors and even CCTV systems.

      I dont have much exsposure to MS CRM, however if it has data stored in tables that the bot can monitor, or it can perform actions on data input then it would be fairly easy to implement.

      Hope that helps!


      • Phabrikam

        that’s awesome. is there a code update? if some of it is proprietary that could be stripped out respectively. I was looking to get something going this year as I dig further into powershell. since lync has its own mgmt shell cmdlets if maybe it could be done via powershell. Jaykul has a irc powershell bot looking to do something similar with lync. this is a great start

        • Hi

          Yes, I’ve not yet written a post on it, but watch this space for how to call PowerShell commands via a Lync bot.

  • Michael Diarmid

    Just did a similar bot to this as an example but in Powershell, 🙂

  • Wow… hmmm…. you say this hooks into your existing Lync client software, eh? That’s terrific. I’d been wondering if there was some way I could create a Lync bot WITHOUT my having access to our corporate Lync servers. I’m sure the red-tape required to do that would be huge. And I’d just like to set up something where my server would push notifications to our workgroup. (Unfortunately, we’re all on older versions of IE, otherwise I’d probably be using Websockets or EventSource.)

    Currently, the old system I have in place is everybody’s running (Vista) Desktop Gadgets that poll a MySQL server and then send messages to the System Tray via a little executable. It works, but I’d really like to get rid of having a separate app (and versioning issues).

    • Hope this works with the Lync 2010 SDK.

      • Hi David

        You can code the API to use a Lync client that’s suppressed so doesn’t actually show on the desktop of the machine running the bot.

        I’m not sure there’s anything you can do without access to a Lync server. You’d be best off making some sort of server/client app. There’s dozens of tutorials on the net for these. If you get stuck, let me know, I built one recently to deploy software.


        • Ah, so following this tutorial DOES require access to the Lync server itself, eh? I didn’t realize that. Thanks!

          • The tutorial uses the client on the PC to communicate with the Lync server. So if the client can connect the code will connect.

            Hope that makes sense 🙂

          • Well, that’s what I originally thought, then. I’ve got the Lync client installed on my laptop. (All employees do.) I just thought I’d need to have direct access to the Lync servers themselves (where I could do such things as, modify their configuration, restart services, or whatever) in order to build any sort of bot for our workgroup. And your tutorial seems to provide me a solution for that.

            I was just thrown off a bit when you said “I’m not sure there’s anything you can do without access to the Lync server”. Got confused about what you meant by that.

            Thank you!

          • Ahh ok. Sorry I thought you meant you was trying to develop a solution that didn’t require a Lync server 🙂

            The only thing you may get stuck with is you may need to create an account for the bot to login to. Otherwise he’ll be running as your account, and answering your IMs.

          • OK, sounds good, thank you very much!

  • Hi Garry, sounds like you have a reference missing from the project.. Can you list which you have added, and I will tell you which one is missing.


  • Kipper11

    Hi Mike, I’m new to C# but thought I’d try this little app as I have Lync access. I followed instructions but as soon as I paste in the ‘Imports Microsoft.Lync’ I get an error. I ‘ve added the lync SDK but can’t see it anywhere in references…what am I doing wrong ?

    • Hi Kipper

      You’ll need to add the references to your project from the following location C:Program FilesMicrosoft OfficeOffice15LyncSDKAssemblies.

      Let me know how you get on, or if you get stuck at any stage! 🙂

      • Kipper11

        Hi Mike,
        I found the references but this opened up a can of worms ! I now get 4 errors. I added all the references I could see for Lync trying to get rid of errors but when I saw Microsoft.Lync.Model and it’s subsets I lost the will to live…..

        The code looks like VB.Net not C# – am I correct ? If that is the case can I just add simple buttons to send and receive and a text box/listbox to show and enter I.Ms ?

        Here are the errors and I’ve pasted code in that I have used. I’ve highlighted the errors in red text. Any suggestions would be appreciated.


        Error 1 ‘_InitializeFlag’ is not declared. It may be inaccessible due to its protection level.

        Error 2 ‘LycConversation’ is not declared. It may be inaccessible due to its protection level.

        Error 3 ‘Lyc’ is not declared. It may be inaccessible due to its protection level.

        Error 4 ‘AddressOf’ expression cannot be converted to ‘Object’ because ‘Object’ is not a delegate type.

        • Kipper11

          Mike – as per my last post, am I being a numbty ? I cannot get rid of these errors. Is there somewhere i could download a working version of this so I could reverse engineer to see how it works ?

          • Kipper11

            Amazing what rereading code does ! I’ve got rid of the errors !!

          • Sorry Kipper. Things have been very hectic. Glad to hear you got sorted in the end. Let me know how you get on, I’ve got some more things I’ve got DAVE doing which I plan on sharing soon. 🙂

          • Kipper11

            Rome wasn’t built in a day…I have got it working but when I try to message back, I get ‘Object reference not set to an instance of an object’ when I hit the Dim Modal = directcast line in code. Sorrry Mike, any ideas ?

          • Hi Kipper, sat down tonight to look at your code… My Visual Studio install has gone completely nuts.. Having to rebuild… This could take a while!

            Whilst I get sorted out, can you try replacing your Send message function with this:

            Public Sub SendIM(ByVal strMessage As String)


            _LocalIMModality.BeginSetComposing(True, AddressOf SendMessageCallback, Nothing)

            Dim Modal = DirectCast(_LycConversation.Modalities(Microsoft.Lync.Model.Conversation.ModalityTypes.InstantMessage), InstantMessageModality)

            Modal.BeginSendMessage(strMessage, AddressOf SendMessageCallback, Nothing)

            End Sub

            Bit of a straw clutch as I can’t compile, all I have is VS Code for OS X atm.

          • Kipper11

            I can see you’re a busy man Mike, thanks for taking time out to answer me.

          • Might be easier if you zip up an mail me the code? Upload[@] I’ll then take a look for you. I find it easier debugging code by running it if that makes sense 🙂

          • Kipper11

            Mike – you are an absolute Gem ! I’ll zip it up and send first thing in the morning.

  • Anselm Schüle

    Hi, first of all: Great job, it gives a good start to lync automation. I am struggeling with the following line:

    _LocalIMModality = TryCast(e.conversation.Participants(1).Modalities(ModalityTypes.InstantMessage), InstantMessageModality)

    can you tell me how to get a handle to every new message, including my own? My understanding of this line is, that it only handles new messages from participant(1) i.e. your conversation partner in a 1:1 conversation.


  • Szilveszter Dömötör

    Mate got several question, isn’t there any event directly in Lync client which can invoke this action, actually what i can see a new conversation subscribe to a messagereceived event. After all then I know the sender I can get the mail address. Thats should be a perfect way to forward your lync chat to your phone in SMS while you are away. Or even implement the possibility to someone nudge u like in back in time messenger. I am just getting confused that if i get multiple messages, multiple new conversations and it executing paralel i might send autoreply forward wrong messages. Anyway if I want to use this for anytime startup application then i also need to make the actual conversations subscribed to this event. Usually i have like 30 conversations open, and i start this app which would deal with this event, then those windows not subscribed to the event, did u went farer with the API?

%d bloggers like this: