• Breaking News

    Create your own Slack Bot with Node and JavaScript

    So you are willing to build a Slack bot with Node.js? This post is right for you!

    To build this bot, you will need Node v6 or higher. It's highly recommended to use the latest LTS version of node.

    You can grab the latest Node distribution from here: NODE DOWNLOAD




    Let's go now:

    Create the Slack environment

    Log in to your Slack workspace as usual and then, create a new Slack application here: SLACK APPS

    Once the new application has been created, continue creating your new bot under the "bot Users" section.

    Under the "OAuth & Permissions" section, add the "chat:write:bot" scope.

    As result, you will have a new bot user available

    Create a new Slack channel or using an existing one (like "#general") and invite your bot user to become a member of your target channel.

    How to perform the channel and bot integration

    • On your app's settings page, click the OAuth & Permissions settings item in the navigation menu.
    • In the Scopes section, add the chat:write permission scope, then click Save Changes.
    • Now that you've changed the scopes for your app, you'll need to install it again - you should see a yellow banner near the top of the screen telling you to click here to reinstall your app. Click it, and follow through the permissions authorization page.
    • You'll be redirected back to the OAuth & Permissions page, where you can see your workspace token listed at the top of the page - store this for use later on.

    Source: SLACK API REFERENCE

    Initial bot code

    Install the Slack Node SDK using npm, and then create the following simple client:
    (e.g.: slackBot.js)

    var RtmClient = require('@slack/client').RtmClient;
    var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
    
    var rtm = new RtmClient('.....'); // your token
    rtm.start();
    
    let channel = 'C--------' ; //your channel
    
    rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, function () {
      rtm.sendMessage("Hello!", channel);
    });

    You can grab the bot token from the "OAuth & Permissions" section, copy "Bot User OAuth Access Token" value into RtmClient initialization.

    And you can grab the Slack channel ID from your channel's URL:

    https://yourworkspace.slack.com/messages/C-------/details/

    Connect and test your Slack bot

    Now, everything is set to test your brand new bot.

    Just run the above code as you usually do, this would be the expected output:

    # node slackBot.js
    Logged in as ninjabot of team SMART IT NINJA, but not yet connected to a channel
    
    The expected "Hello!" message should be present in your channel's window now.

    The next post will address incoming events and how to respond to them.

    No comments