cron, python and slack - a beautiful combination
This year I'm trying out slack as a platform for out fantasy football league. It provides channels for banter, keeping track of transfers and, with the use of rss feeds, up to date information. In addition I've set up a channel dedicated to injuries tied to an incoming webhook. The injury channel works by running a small python code on a server via a weekly cron job. The python code scrapes a site that lists current Premiership injuries and suspensions, reformats the output and then pushes it out to the slack channel. This results in a simple solution that updates a channel weekly.
1# -*- coding: utf-8 -*-
2import pandas as pd
3from bs4 import BeautifulSoup
4import requests
5import json
6
7url = "https://www.fantasyfootballscout.co.uk/fantasy-football-injuries/"
8webhook = ## provided webhook url
9
10
11response = requests.get(url)
12
13soup = BeautifulSoup(response.text, "html5lib")
14
15table = soup.find('table', attrs={'class':'ffs-ib-full-content'})
16table_body = table.find('tbody')
17
18data = []
19
20rows = table_body.find_all('tr')
21for row in rows:
22 cols = row.find_all('td')
23 cols = [ele.text.strip() for ele in cols]
24 data.append([ele for ele in cols if ele]) # Get rid of empty values
25
26status = {"Injured": ":inj-injured:",
27 "Available": ":inj-available:",
28 "Unavailable": ":inj-unavailable:",
29 "Knock": ":inj-knock:",
30 "On Loan": ":inj-on-loan:",
31 "Suspended": ":inj-disciplinary:",
32 "Doubt 25%": ":inj-doubt-25:",
33 "Doubt 50%": ":inj-doubt-50:",
34 "Doubt 75%": ":inj-doubt-75:"}
35
36p1 = pd.DataFrame(data, columns = ['Name', 'Club', 'Status', 'Return Date', 'Latest News', 'Last Updated'])
37p1['status_icon'] = p1['Status'].replace(status)
38p1['out'] = p1['status_icon'] + ' ' + p1['Name'] + ' ' + p1['Club']
39
40# build the payload
41payload = {}
42payload['username'] = 'injury-bot'
43payload['channel'] = '#injuries'
44
45attachments = []
46attachments.append({"fallback":"Link to injury website: <https://www.fantasyfootballscout.co.uk/fantasy-football-injuries/|full injury table>"})
47attachments.append({"pretext":"Link to injury website: <https://www.fantasyfootballscout.co.uk/fantasy-football-injuries/|full injury table>"})
48
49field_inj = {}
50field_inj['title'] = 'Injury Table'
51field_inj['value'] = '\n'.join(p1['out'].tolist())
52field_inj['short'] = False
53
54attachments.append({"fields": [field_inj]})
55payload['attachments'] = attachments
56
57requests.post(webhook, data = json.dumps(payload))