How to build a basic Slack Bot with Python?

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

How to build a basic Slack Bot with Python?
1 Likes33.20 GEEK