forked from juanpabloaj/slacker-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
executable file
·180 lines (141 loc) · 5.12 KB
/
__init__.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Send message to Slack from command line
"""
from slacker import Slacker
from slacker.utils import get_item_id_by_name
import requests
import argparse
import sys
import os
try:
from urllib import quote as urllib_quote
except ImportError:
from urllib.parse import quote as urllib_quote
import warnings
warnings.filterwarnings('ignore', message=".*InsecurePlatformWarning.*")
# This function will be removed after below PR is merged:
# https://github.com/os/slacker/pull/46
def get_item_by_key_value(list_dict, key, value):
for d in list_dict:
if d[key] == value:
return d
return {}
def post_message(token, channel, message, name, as_user, icon,
as_slackbot, team, **kwargs):
if as_slackbot:
post_message_as_slackbot(team, token, channel, message)
else:
slack = Slacker(token)
slack.chat.post_message(channel, message, username=name,
as_user=as_user, icon_emoji=icon, **kwargs)
class SlackerCliError(Exception):
pass
def post_message_as_slackbot(team, token, channel, message):
url = 'https://{team}.slack.com/services/hooks/slackbot'
url += '?token={token}&channel={channel}'
url = url.format(team=team, token=token, channel=urllib_quote(channel))
res = requests.post(url, message)
if res.status_code != 200:
raise SlackerCliError("{0}:'{1}'".format(res.content, url))
def get_im_id(token, username):
slack = Slacker(token)
members = slack.users.list().body['members']
user_id = get_item_id_by_name(members, username)
ims = slack.im.list().body['ims']
return get_item_by_key_value(ims, key='user', value=user_id).get('id')
def get_channel_id(token, channel_name):
slack = Slacker(token)
channels = slack.channels.list().body['channels']
return get_item_id_by_name(channels, channel_name)
def upload_file(token, channel_name, file_name):
""" upload file to a channel """
slack = Slacker(token)
slack.files.upload(file_name, channels=channel_name)
def args_to_dict(lst):
ret = {}
for item in lst:
# skip args with bad syntax
if item.count('=') < 1:
continue
k, v = item.split('=', 1)
ret[k] = v
return ret
def args_priority(args, environ):
'''
priority of token
1) as argumment: -t
2) as environ variable
priority of as_user
1) as argument: -a
2) as environ variable
'''
arg_token = args.token
arg_as_user = args.as_user
slack_token_var_name = 'SLACK_TOKEN'
if slack_token_var_name in environ.keys():
token = environ[slack_token_var_name]
else:
token = None
if arg_token:
token = arg_token
# slack as_user
slack_as_user_var_name = 'SLACK_AS_USER'
as_user = bool(environ.get(slack_as_user_var_name))
if arg_as_user:
as_user = True
return token, as_user, args.channel
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--channel", help="Slack channel")
parser.add_argument("-u", "--user", help="Slack user")
parser.add_argument("-t", "--token", help="Slack token")
parser.add_argument("-f", "--file", help="File to upload")
parser.add_argument("-n", "--name", help="Sender name")
parser.add_argument("-a", "--as-user", action="store_true", help="As user")
parser.add_argument("-i", "--icon-emoji", help="Sender emoji icon")
parser.add_argument("-s", "--as-slackbot", action="store_true",
help="Send as Slackbot")
parser.add_argument("-m", "--team", help="Slack team")
parser.add_argument("kwargs",
help="Additional arguments to send to post_message",
default=[],
nargs=argparse.REMAINDER)
args = parser.parse_args()
user = args.user
message = sys.stdin.read()
as_slackbot = args.as_slackbot
kwargs = args_to_dict(args.kwargs)
if as_slackbot:
token = args.token or os.environ.get('SLACKBOT_TOKEN')
as_user = False
channel = args.channel
name = None
icon = None
file_name = None
team = args.team or os.environ.get('SLACK_TEAM')
else:
token, as_user, channel = args_priority(args, os.environ)
name = args.name
icon = args.icon_emoji
file_name = args.file
team = None
if token and channel and message:
post_message(token, '#' + channel, message, name, as_user, icon,
as_slackbot, team, **kwargs)
if token and user and message:
if as_slackbot:
channel = '@' + user
else:
im_id = get_im_id(token, user)
channel = im_id or '@' + user # allow user send DM to slackbot
post_message(token, channel, message, name, as_user, icon,
as_slackbot, team, **kwargs)
if token and file_name:
if user:
upload_file(token, '@' + user, file_name)
elif channel:
upload_file(token, '#' + channel, file_name)
if __name__ == '__main__':
main()