Writing a Salesforce Bot for Slack

This is another installment in my ongoing Slack and Salesforce integration series.

In part 1, I demonstrated how, using a Webhook, Salesforce can post messages to Slack channels when specific events happen (for example, when the status of an opportunity changes).

In part 2, I showed how, using Slash Commands, Slack users can access Salesforce data from within the Slack UI.

In this article, I’ll share an example of Slack and Salesforce integration using bots. Using a bot, you can monitor Slack channels activity and respond to Salesforce requests expressed in natural language.

Watch this video to see the Salesforce bot in action:

To create a bot, you create an application that opens a Websocket connection to Slack. Your application will then receive all the messages from channels your bot has been invited to, as well as the direct messages Slack users sent to your bot.

Your app can then use pattern matching algorithms and natural language processing tools to decide if and how to respond to a message.

To create this simple Salesforce bot, I used Botkit, a node.js-based toolkit that facilitates the creation of bots for Slack (and now Facebook Messenger). Botkit takes care of the low level Websocket plumbing, and provides the basic infrastructure to set up handlers that respond to specific messages.

For example, here is the code to respond to an Account Search request:

controller.hears(['search account (.*)', 'search (.*) in accounts'], 'direct_message,direct_mention,mention', (bot, message) => {
    let name = message.match[1];
    salesforce.findAccount(name)
        .then(accounts => bot.reply(message, {
            text: "I found these accounts matching  '" + name + "':",
            attachments: formatter.formatAccounts(accounts)
        }))
});

Botkit can also be extended using plugins (middleware). For example, you could add a plugin to preprocess messages with a natural language processing service.

Source Code and Installation Instructions

  1. Create a Connected App in Salesforce
  2. Clone this repository
  3. Install the dependencies:
    npm install
    
  4. Create a bot user in Slack
  5. On the command line, define the environment variables used in your Node.js app. On a Mac:
    export SLACK_BOT_TOKEN=your_slack_bot_token
    export SF_CLIENT_ID=your_salesforce_connected_app_client_id
    export SF_CLIENT_SECRET=your_salesforce_connected_app_secret
    export SF_USER_NAME=salesforce_integration_user_name
    export SF_PASSWORD=salesforce_integration_user_password
    
  6. Start Node:
    node server
    
  7. In Slack, select your bot under Direct Messages, type Help to see what you can ask, and start chatting with your bot!

Authentication

This sample bot uses an “integration user” to connect to Salesforce. In other words, all Slack users connect to Salesforce using the same Salesforce user. In a production environment, you’d probably want to map Slack user ids to Salesforce user ids so that requests coming from a specific Slack user can be served using the associated Salesforce user. I’ll demonstrate this approach in a future post.

Make sure you understand the security implications before deploying the application in a production environment.

  • Mike L

    Thanks for this post Christophe! So with this method you can create new accounts — is the process much different for editing accounts? I want to be able to change the status of a certain deal in Salesforce via Slack instead of having to go in and edit the field. Is there a big difference from what you’ve described here?

  • Expenses of property and real estate in Bengaluru have been enduring for as far back as 2 years, regardless of the way that the land market in India has been experiencing a droop. Bengaluru has possessed the capacity to hang on against this downtrend because of various variables. The fundamental reason is that it is an end client driven market instead of a financial specialist pushed market. The land designers in Bengaluru have focused on the mid fragment and moderate lodging which holds the expenses under check and the land stock stays quick moving. As the business sector is end client driven the rental expenses are high which make the land optional business sector in Bengaluru extremely alluring.
    Affordable Apartments in bengaluru

  • Pingback: Slack and Salesforce Integration: Authentication | Christophe Coenraets()

  • Nihat Yayla

    Geleceğin yatırımı olarak değerlendirilen konut ve arsalar emlakdream güvencesi ile istediğiniz tarzda ve istediğiniz konumda sizlerle .

    Kartal Konut Projeleri ile İstanbul Anadolu yakasının en çok değer kazanabilecek konutlarını sizlere sunmaktayız. Sizler için yapılan araştırmalar neticesinde web sitemizde yer alan iskanlı konutları incelemenizi tavsiye ediyoruz. Bilgilendirmeler için 7 gün 24 saat çağrı merkezimizde sizlerin çağrılarını beklemekteyiz.

    Sevdikleriniz için yaşamın önemini iyi biliyoruz bu yüzden en kaliteli mekanlarda en gözde mekanları sizler için derledik.

    http://www.emlakdream.com/etiket/kartal-konut-projeleri/

  • Emlak Dream

    Planlı gelişimi ve dev projelerle yatırımcıların yeni gözdesi Esenyurt’un en prestijli noktasında yükselen Terrace Mix’te; 1+0 daireler 163 bin lira ile 279 bin lira, 1+1 daireler 241 bin lira ile 385 bin lira, 2+1 daireler 395 bin lira ile 535 bin lira, 3+1 daireler ise 505 bin lira ile 580 bin lira arasında değişen fiyatlarla alıcıların karşısına çıkıyor. Esenyurt Konut Projeleri ile çok uygun fiyatlara konut sahibi olabilirsiniz.
    Merkezi konumu ile ideal bir mekanda konut sahibi olabileceksiniz. Sevdikleriniz ile merkezi konumdan her yere ulaşabilirsiniz.

    http://www.emlakdream.com/haber/Esenyurt-konut-projeleri/72561

  • Emlak Dream

    Tarihi Adaya komşu Zeytinburnu kazlıçeşme de bulunan 111 Dönümlük arsa üzerine Emlak Konut Ayrıcalıkları ile iyi bir yatırıma ayak basmanızın tam zamanı. Büyükyalı istanbul projesi Konumu itibari ile en çok tercih edilen yapıtlar arasında bulunan bu proje metro, metrobüs, otobüs , tranvay gibi ulaşımın olmazsa olmazlarına çok yakın mesafede aynı zamanda birçok kurum ve kuruluşa dakikalar içerisinde ulaşabileceğiniz bir yerde olması dolayısıyla zamanınızı trafiğe değil kendinize ayırabileceksiniz.

    Fırsat ve ayrıcalıklardan yararlanmak istiyorsanız sayfamızı takipte kalın en doğru ve güvenilir haberleri bizzat proje sahipleri ile olan röportajlar ile sizlere bilgi vermekteyiz.

    http://www.emlakdream.com/proje/buyukyali-istanbul-projesi/36

  • Ebenezer

    is there any way we can create a bot user using apex and not node? slash commands can be created using apex rest, but not sure if we can have web sockets open in Salesforce and hear the requests from bot user.

css.php