Repository navigation
Expand file tree
/
Copy pathslackbot.py
More file actions
executable file
·118 lines (90 loc) · 2.99 KB
/
Copy pathslackbot.py
File metadata and controls
executable file
·118 lines (90 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env python3
import arrow
import json
import pandas as pd
import time
from decouple import config
from icecream import ic
from pathlib import Path
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
# logging.basicConfig(level=logging.DEBUG)
# verbose icecream
ic.configureOutput(includeContext=True)
# pandas don't truncate output
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
# env
home = Path.home()
cwd = Path.cwd()
csv_fn = config('CSV_FN', default='raw/output.csv')
json_fn = config('JSON_FN', default='raw/output.json')
_SLACKBOT_DIR = Path(__file__).resolve().parent
groups_csv = _SLACKBOT_DIR / 'groups.csv'
tz = config('TZ', default='America/Chicago')
loc_time = arrow.now().to(tz)
time.tzset()
# creds
USER_TOKEN = config('USER_TOKEN')
BOT_USER_TOKEN = config('BOT_USER_TOKEN')
SLACK_WEBHOOK = config('SLACK_WEBHOOK')
CHANNEL = config('CHANNEL', default='testingchannel')
TTL = config('TTL', default=3600, cast=int)
HOST = config('HOST', default='localhost')
# strip double quotes from env strings (local image)
CHANNEL = CHANNEL.strip('"')
# read channel
chan = pd.read_csv(_SLACKBOT_DIR / 'channels.csv', header=0)
# create dict of channels
chan_dict = {}
# loop through channels and find id
for name, id in zip(chan['name'], chan['id'], strict=False):
chan_dict[name] = id
# channel name and id
channel_name = CHANNEL
channel_id = chan_dict[CHANNEL]
# hard-coded second channel
hard_chan = ''
# add hard-coded channel
if hard_chan != '':
hard_id = chan_dict[hard_chan]
channels = {channel_name: channel_id, hard_chan: hard_id}
else:
channels = {channel_name: channel_id}
# python sdk
client = WebClient(token=BOT_USER_TOKEN)
def fmt_events(events: list[dict]) -> list[str]:
"""Format a list of event dicts into Slack message strings."""
if not events:
return []
df = pd.DataFrame(events)
df['message'] = df.apply(lambda x: f'• {x["date"]} *{x["name"]}* <{x["eventUrl"]}|{x["title"]}> ', axis=1)
return df['message'].tolist()
def fmt_json(filename):
# read json file
data = json.load(open(filename))
return fmt_events(data)
def send_message(message, channel_id):
"""
Send formatted Slack messages to a channel.
NOTE: This function won't work with DMs or private channels.
"""
try:
response = client.chat_postMessage(
channel=channel_id, text="", blocks=[{"type": "section", "text": {"type": "mrkdwn", "text": message}}]
)
return response
except SlackApiError as e:
assert e.response["ok"] is False
assert e.response["error"]
print(f"Got an error: {e.response['error']}")
def main():
# open json file and convert to list of strings
msg = fmt_json(json_fn)
# send message as one concatenated string
for channel_name, channel_id in channels.items():
send_message('\n'.join(msg), channel_id)
return ic(msg)
if __name__ == '__main__':
main()