How to build your own Slack Bot. Simple and Easy Guide

precise(57)
Published in
#life
Words
687
Reading
4 min
Listen
Play
9y

Creating your first slack bot is fun and easy. Let's add this Slack Bot to our army of bots.

But first you may wonder, why create these bots? What do I get out of it? Do I need them?

The answers, could may well depend on your lifestyle and life goals but for me personally, here are few benefits I got having these bots with me:

  • It gets the job done - done well, accurately and in a timely manner.
  • It won't complain and question the task. (Trivial and repeating tasks are boring and are sometimes the cause for burning out and stress )
  • Very objective, has no emotions and is precise (right, I could be a bot)
  • It does the trivial daily tasks for you making you more productive, efficient and get the most out of your time.

Before we get started, let's actually do the Maths. Here's my typical daily activities.

ActivityTime Spent
1. Check emails1 hour
2. Read daily news1 hour
3. Crypto Trading2-3 hours
4. Day-job (work related) tasks8 hours
5. Server maintenance ( Steem Witness, Decent Witness, Para-sa-Bayan Servers etc)30-60 minutes

Yes, I run a Steem Witness Node. If you feel voting for me just go here and vote precise@precise

Time Savings from using productivity bots

* The table below shows the bot tasks to help with the activities above and the third column shows the time saved using the bot.

Bot TasksTime Spent (Based above)Time Savings
1. Sorting, segregating and compiling of emails and making sure I only open the important ones1 hour20 mins
2. Parse RSS feeds, compile relevant news (as set accordingly), display only news that I will surely read1 hour40 mins
3. Generate Technical Analysis Graphs, Recommend Buy and Sell positions, Pull prices from various exchanges2-3 hours60 mins
4. Track and update tasks, do trivial work-related tasks8 hours60 mins
5. Server Status check, clean up, do updates30 - 60 minues30 mins

Thats a total of 210 minutes or 3.5 hours a day! So what can you do with that extra 3.5 hours a day?

  • Exercise, Go to the gym, go for a walk , a stroll in the park, run, play sports (3.5 hours worth of this)
  • It takes no more than 3 minutes to call a love one, a friend or a relative to say you care for them and with extra 3.5 hours a day that equates to 70 love ones who will receive your dearly affection everyday because now you have more time! (thanks bots!)
  • A 3-second hug, a 1-second kiss and a 3-second "I love you" is enough to show your affection. Imagine how many people you can give love because now you have 3.5 extra hours to do so?

And if the bots will go wrong? Just re-start it, update and re-code. Your life goes on...

Don't worry they won't rise up against you or humanity. If it does, then you're coding it wrong.

So now let's get that Slack bot up and running.

slack_bot_logo.jpeg

1. Setting up a Slack bot account

  • Sign-in to an existing team or create a new one.
  • Go to https://api.slack.com/bot-users to create a new bot user
    Bot_Users___Slack.png
  • Create and configure the bot details
    2.png
  • Get your bot's API token
    3.png
  • Get the bot ID. Create a python script get_bot_id.py and copy paste below ( replace the API_TOKEN with the token you derived above):
import os
from slackclient import SlackClient

BOT_NAME = 'precise-bot'
API_TOKEN = "xoxb-xxxxxxxx-yxxxxxxxxxxxxg"
slack_client = SlackClient(API_TOKEN)

if __name__ == "__main__":
    api_call = slack_client.api_call("users.list")
    if api_call.get('ok'):
        # retrieve all users so we can find our bot
        users = api_call.get('members')
        for user in users:
            if 'name' in user and user.get('name') == BOT_NAME:
                print("Bot ID for '" + user['name'] + "' is " + user.get('id'))
    else:
        print("could not find bot user with the name " + BOT_NAME)

  • Run get_bot_id.pyto get your bot's ID
    botid.png

2. The Code

  • Create the main python script for the bot and replace the tokens using the API_TOKEN and the BOT_ID we derived on the previous steps. Copy and paste the code below. The Code below is simply waiting for commands from a slack channel where the bot is registered. If a user type in @precise-bot knc the bot pulls the price feed of KNC cryptocoin and return this to the channel.
import os,re
import datetime
import time, requests, json
from slackclient import SlackClient

BOT_NAME = 'precise-bot'
BOT_ID = "UxxxTU"
API_TOKEN = "xoxb-2xxxxxxxx6-yyxxxxxxxxxxxkg"
slack_client = SlackClient(API_TOKEN)

# constants
AT_BOT = "<@" + BOT_ID + ">"
SHOW_COMMAND = "knc"
KNC_URL = "https://api.liqui.io/api/3/ticker/knc_btc"

def get_knc_price():
    r = requests.get(KNC_URL)
    data_json =  json.loads(r.text)
    output  =  "Last Price: {}\n".format(data_json['knc_btc']['last'])
    output +=  "Buy: {}\n".format(data_json['knc_btc']['buy'])
    output +=  "Sell: {}\n".format(data_json['knc_btc']['sell'])
    output +=  "Volume (BTC): {} BTC\n".format(data_json['knc_btc']['vol'])
    output +=  "Volume (KNC): {} KNC\n".format(data_json['knc_btc']['vol_cur'])
    output +=  "High: {}\n".format(data_json['knc_btc']['high'])
    output +=  "Low: {}\n".format(data_json['knc_btc']['low'])
    output +=  "Ave. Price: {}\n".format(data_json['knc_btc']['avg'])
    return output

def handle_command(command, channel):
    response = "Use the *" + SHOW_COMMAND + \
               "* "
    if command.startswith(SHOW_COMMAND):
        response = get_knc_price()

    slack_client.api_call("chat.postMessage", channel=channel,
                          text=response, as_user=True)

def parse_slack_output(slack_rtm_output):
    output_list = slack_rtm_output
    if output_list and len(output_list) > 0:
        for output in output_list:
            if output and 'text' in output and AT_BOT in output['text']:
                # return text after the @ mention, whitespace removed
                return output['text'].split(AT_BOT)[1].strip().lower(), \
                       output['channel']
    return None, None


if __name__ == "__main__":
    READ_WEBSOCKET_DELAY = 1
    if slack_client.rtm_connect():
        print("Precise Slack Bot connected and running!")
        while True:
            command, channel = parse_slack_output(slack_client.rtm_read())
            if command and channel:
                print channel
                handle_command(command, channel)
            time.sleep(READ_WEBSOCKET_DELAY)
    else:
        print("Connection failed.")

3. Register the bot to a channel

add.png

4. Run and Deploy

Please refer to this post on how to set-up a proper development environment. The only main dependency for a slack bot is slack client library $ pip install slackclient then run our script above.
$ python slack_bot.py

chat.png


I code with purpose. I am precise@precise.

How to build your own Slack Bot. Simple and Easy Guide | Ecency