How to build a basic Slack Bot with Python?

How to build a basic Slack Bot with Python?

Slackbot is a chat robot that's prepared to answer any question you have about using Slack. In this post, you'll learn using Python to create a Slack bot

Working at a startup, we needed to automate messages in order to get notified of certain events and triggers. For example, the company I work with deals with connections to certain stores. If that connection is broken Python will read that information in our database. We can now send that data over to a Slack channel specifically for reconnecting that store.

We can create many possibilities for this Slack Bot, another example my colleague created would be to output Python error messages to a channel. Not only creating a notification but also an ongoing log of errors.

We can do something easy for now. For this project, we are going to construct a Slack Bot that will output a message if it detects that the date of when the script is run is a U.S. holiday.

What is required for this project: 1. Python 2. Slack workspace/account

Python modules required: 1. datetime (to tell what date it is when a script is run and standardize date times) 2. pandas (mainly for organizing data into a dataframe) 3. requests (to connect to the data we are fetching from a website and sending data to the slack API) 4. bs4 (data parsing of the data we are getting from the website) 5. json (encodes the data so slack API can use it)

First things first, let’s create a new Python file and import the required modules.

from datetime import date, datetime, timedelta
import pandas as pd
import requestsfrom bs4 
import BeautifulSoup
import json

We can fetch today’s datetime using the datetime module and store it as a string format as Year-month-day.

today = datetime.now().strftime(‘%Y-%m-%d’)
#today = '2019-10-29'

Using the module requests, we can now connect to the website we want to fetch data. For this, I am connecting to this website to fetch Holidays. When we get data from a website it is sending everything we see on that page. We only want the Holidays from this data. This is where BeautifulSoup comes into play, using the modulebs4 we can easily parse that data. We can now put this into a DataFrame.

Not the best way to transfer the data to a DataFrame but we just need to get the job done.

regionalHolidaysList = []
for result in results:    
     date = result.contents[0].text + ', ' + datetime.today().strftime('%Y')    
     weekday = result.contents[1].text    
     holidayName = result.contents[2].text    
     observance = result.contents[3].text     
     stateObserved = result.contents[4].text
     regionalHolidaysList.append((date, weekday, holidayName, observance, stateObserved))regionalHolidayDf = pd.DataFrame(regionalHolidaysList, columns = ['date', 'weekday', 'holidayName', 'observance', 'stateObserved'])regionalHolidayDf['date'] = regionalHolidayDf['date'].apply(lambda x: (datetime.strptime(x, '%b %d, %Y').strftime('%Y-%m-%d')))

We can now create a datetime list from this DataFrame

dateList = regionalHolidayDf['date'].tolist()

Reading if today is in this dateList we can tell it to print to the requested slack channel. In order to get Python to send something using Slack, we need to create an incoming webhook. Slack has some documentation on how to do that here — https://api.slack.com/messaging/webhooks.

If everything is done correctly then we should have something like this:

https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX

The last part gets a little complicated so I will post my comments in the code with hashtags.

#So we get the date if it is in this list it will send a message in slackif today in dateList:
     todayHoliday = regionalHolidayDf[regionalHolidayDf['date'] ==          today]    
     info=[]    
     for holiday in todayHoliday.itertuples():
          info.append(':umbrella_on_ground:' +                       holiday.holidayName +  ' in ' +                      holiday.stateObserved.replace('*', ''))    
     if len(info) >1:        
          infoFinal = '\n'.join(info)    
     else:        
       infoFinal = info[0]#Here is where we can format the slack message, it will output any holiday with todays

     message = f'@here Fun fact! \n Today({today}) is: \n {infoFinal}'        
     print('Sending message to the happyholiday channel...')
     slackmsg = {'text': message}    #Using the module json it formats it where the slack API can accept it
#we can store the slack link into a variable called webhook        webhook='https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
response = requests.post(webhook,  data=json.dumps(slackmsg), headers={'Content-Type': 'application/json'})    
     if response.status_code != 200:        
          raise ValueError('Request to slack returned an error %s, the response is:\n%s'            % (response.status_code, response.text)        )    
     print('Request completed!')
else:    
     print('No regional holiday today! See you next time!')

Now we can finally run this script and if successful it will output a holiday based on the date of when the script is run.

For further automation, we can put this on an EC2 and make it run every day! But that requires more credentials and setting up, let me know if that is another topic you guys are interested in!

python slack chat-bot

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Python Tricks Every Developer Should Know

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

How to Remove all Duplicate Files on your Drive via Python

Today you're going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates. We gonna use Python OS remove( ) method to remove the duplicates on our drive. Well, that's simple you just call remove ( ) with a parameter of the name of the file you wanna remove done.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

The Basics of Python OS Module

The OS module is a python module that provides the interface for interacting with the underlying operating system that Python is running.