-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathslack-tail
More file actions
executable file
·304 lines (272 loc) · 10 KB
/
slack-tail
File metadata and controls
executable file
·304 lines (272 loc) · 10 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/env python3
#
# How to get a slack API token
#
# From https://github.com/yuya373/emacs-slack/tree/1f6a40faec0d8d9c9de51c444508d05a3e995ccd#how-to-get-token
# - Using chrome or firefox, open and sign into the slack customization page, e.g. https://my.slack.com/customize
# - Right click anywhere on the page and choose "inspect" from the context menu. This will open the developer tools.
# - Find the console (it's one of the tabs in the developer tools window)
# - At the prompt ("> ") type the following: window.prompt("your api token is: ", TS.boot_data.api_token)
# - Copy the displayed token elsewhere, and close the window.
from ansi.colour import *
import ansi.cursor
import ansi.osc
import ansi.iterm
import argparse
import atexit
import emoji
import fcntl
import html
import os
from pprint import pprint
import re
import requests
import struct
import sys
import termios
import textwrap
import traceback
import unicodedata
is_iterm = os.environ['TERM_PROGRAM'] == "iTerm.app"
width=80
try:
height, width = struct.unpack('hh', fcntl.ioctl(sys.stdin, termios.TIOCGWINSZ, '1234'))
except:
pass
from slack_sdk.rtm import RTMClient
parser = argparse.ArgumentParser(description="Send messages to slack channels")
parser.add_argument('--until', metavar='REGEX')
parser.add_argument("channel", metavar="CHANNEL", nargs='?')
parser.add_argument("users", metavar="USER", nargs='*')
parser.add_argument("--debug", default=False, action='store_true')
parser.add_argument("--send", metavar="MESSAGE", default="")
args = parser.parse_args()
if args.channel and args.channel.startswith('#'):
args.channel = args.channel[1:]
@RTMClient.run_on(event="hello")
def send_message(rtm_client, web_client, **payload):
if args.send and args.channel:
msg = args.send
try:
response = web_client.chat_postMessage(channel=args.channel, text=msg)
except SlackApiError as e:
print("Got an error: " + e.response['error'], file=sys.stderr)
@RTMClient.run_on(event="message")
def show_message(rtm_client, web_client, **payload):
try:
show_message_(rtm_client, web_client, **payload)
except Exception as e:
pprint(payload, width=width)
traceback.print_exc()
def show_message_(rtm_client, web_client, **payload):
data = payload['data']
if data.get('subtype') in ('message_changed', 'message_replied', 'message_deleted'):
return
team = data.get('team', data.get('user_team', data.get('source_team', "")))
user = bot = username = display_name = None
channel = get_channel(web_client, data['channel'])
link = 'slack://channel?team=%s&id=%s' % (team, data['channel'])
avatars = {}
if 'bot_id' in data:
bot = get_bot(web_client, data['bot_id'])
if bot:
avatars = bot['icons']
if 'bot_profile' in data and 'name' in data['bot_profile']:
username = data['bot_profile']['name']
avatars = data['bot_profile']['icons']
if 'user' in data:
user = get_user(web_client, data['user'])
if 'profile' in user and 'display_name' in user['profile']:
display_name = user['profile']['display_name']
if 'real_name' in user:
username = user['real_name']
elif 'profile' in user and 'real_name' in user['profile']:
username = user['profile']['real_name']
avatars = user['profile']
if 'username' in data:
username = data['username']
if 'icons' in data:
avatars = data['icons']
if channel['is_im'] or channel['is_mpim']:
channel = ""
else:
channel = channel['name']
if args.channel and args.channel != channel:
return
if username is None:
print("Username not known!")
pprint(payload, width=width)
avatar = None
if avatars:
smallest = 100000
for k in sorted(avatars.keys()):
if k == 'emoji':
avatar = find_emoji(avatars[k][1:-1], custom_emoji=web_client.emoji)
if k.startswith('image_'):
size = k[6:]
if size.isdigit() and int(size) < smallest:
smallest = int(size)
avatar = avatars[k]
if args.users and (username not in args.users) and (display_name not in args.users):
return
if data.get('text', ''):
print_(web_client, channel, username, data['text'], args.until, link, avatar)
for a in data.get('attachments', []) + data.get('blocks', []):
if a.get('title', ''):
print_(web_client, channel, username, a['title'] + ' ' + a.get('title_link', ''), args.until, link, avatar)
if a.get('text', '') and isinstance(a['text'], str):
print_(web_client, channel, username, a['text'], args.until, link, avatar)
if a.get('image_url', ''):
msg = a['fallback'][1:-1]
imgt = None
if a['image_bytes'] < 1024 * 1024:
img = requests.get(a['image_url'])
if img.ok:
msg = ''
imgt = ansi.iterm.image(img.content)
print_(web_client, channel, username, msg, args.until, link, avatar)
if imgt:
print(imgt)
for a in data.get('files', []):
msg = "%s: %s" % (a['title'], a['url_private'])
imgt = None
if a['mimetype'].startswith('image/') and a['size'] < 1024 * 1024:
img = requests.get(a['url_private'], headers={'Authorization': 'Bearer %s' % web_client.token})
if img.ok:
msg = ''
imgt = ansi.iterm.image(img.content)
print_(web_client, channel, username, msg, args.until, link, avatar)
if imgt:
print(imgt)
if args.debug:
pprint(payload, width=width)
def print_(w, c, u, m, r, l, a):
ou = u
if len(c) > 20:
c = c[:17] + '...'
if len(u) > 20:
u = u[:17] + '...'
c = "%-20s" % c
u = "%-20s" % u
if is_iterm:
c = ansi.osc.anchor(l) + c + ansi.osc.anchor("")
c = fx.faint(c)
u = fx.bright(u)
indent = 42
if is_iterm:
u = get_avatar(ou, a) + ' ' + u
indent += 3
links = []
m = re.sub('<@([^>]+)>', lambda m_: replace_user(w, m_), m)
m = re.sub('<#([^>]+?)(?:\|([^>]+))?>', lambda m_: replace_channel(w, m_), m)
m = re.sub('<(https?://[^| >]+)\|([^>]+)>', lambda m_: replace_url(m_, links), m)
m = re.sub('<(https?://[^| >]+)>', r'\1', m)
m = re.sub(':([^ :]+):', lambda m_: find_emoji(m_.group(1)), m)
m = html.unescape(m)
frags = []
for line in m.strip().splitlines():
line = line.strip()
if not line:
continue
frags += textwrap.wrap(line, width-indent, break_on_hyphens=False)
if is_iterm:
frags = [re.sub(':([^ :]+):', lambda m_: find_emoji(m_.group(1), custom_emoji=w.emoji), m) for m in frags]
frags += [fx.faint("[%d] %s") % (pos+1, link) for (pos, link) in enumerate(links)]
if not frags:
frags = ['']
print("\n%s %s %s" % (c, u, frags[0]),flush=True, end="")
for frag in frags[1:]:
print("\n" + " " * indent + frag, flush=True, end="")
if r and re.search(r, m):
sys.exit(0)
def replace_user(w, m):
try:
return '@' + get_user(w, m.group(1))['name']
except:
return m.group(0)
def replace_channel(w, m):
if m.group(2):
return '#' + m.group(2)
try:
return '@' + get_channel(w, m.group(1))['name']
except:
return m.group(0)
def replace_url(m, links):
link = html.unescape(m.group(1))
try:
pos = links.index(link)+1
except ValueError:
pos = len(links)+1
links.append(link)
return "%s[%d]" % (m.group(2), pos)
modifiers = {
'skin-tone-1': '\U0001F3FB',
'skin-tone-2': '\U0001F3FC',
'skin-tone-3': '\U0001F3FD',
'skin-tone-4': '\U0001F3FE',
'skin-tone-5': '\U0001F3FF',
}
def find_emoji(name, custom_emoji={}, fallback=None):
if not fallback:
fallback = ':' + name + ':'
if name in modifiers:
return modifiers[name]
if name in custom_emoji:
val = custom_emoji[name]
if val.startswith('alias:'):
return find_emoji(val[6:], custom_emoji, fallback)
if val.startswith('https://'):
img = requests.get(val)
if not img.ok:
return fallback
val = custom_emoji[name] = ansi.iterm.image(img.content, name=fallback, height=1)
return val
text = ':' + name + ':'
val = emoji.emojize(text, language='alias')
if val != text:
return val
try:
return unicodedata.lookup(name)
except KeyError:
try:
return unicodedata.lookup(name.replace('_', ' '))
except KeyError:
return fallback
channels = {}
def get_channel(web_client, channel):
if channel not in channels:
channels[channel] = web_client.conversations_info(channel=channel).data['channel']
return channels[channel]
users = {}
def get_user(web_client, user):
if user not in users:
users[user] = web_client.users_info(user=user).data['user']
return users[user]
avatars = {}
def get_avatar(name, url):
if url not in avatars:
if url.startswith('https://'):
img = requests.get(url)
if not img.ok:
return None
avatars[url] = ansi.iterm.image(img.content, name=name, height=1)
else:
avatars[url] = url
return avatars[url]
bots = {}
def get_bot(web_client, bot):
if bot not in bots:
try:
bots[bot] = web_client.bots_info(bot=bot).data['bot']
except:
bots[bot] = None
return bots[bot]
if is_iterm:
print(ansi.iterm.badge("Slack"), end='', flush=True)
atexit.register(lambda: print(ansi.iterm.badge(""), end='', flush=True))
atexit.register(lambda: print(ansi.cursor.show()))
print("Waiting for slack messages..." + ansi.cursor.hide(), end="", flush=True)
slack_token = os.environ["SLACK_TOKEN"]
rtm_client = RTMClient(token=slack_token)
rtm_client._web_client.emoji = rtm_client._web_client.emoji_list()['emoji']
rtm_client.start()