forked from birdman4512/sam-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SAMbot.py
executable file
·233 lines (213 loc) · 8.91 KB
/
SAMbot.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
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
#!/usr/bin/env python3
import os, time, re, requests, logging, json, pyjokes, traceback
from slackclient import SlackClient
from pprint import pprint
from logging.config import dictConfig
from mispattruploader import *
import helper
### MultiChannel Support
multi_channel = True ## Use if you would like the channel name to be used in the title
default_title = "#manual_ioc" ## If above set to false, provide a default
### Configuration loading and logging enabled.
dir_path = os.path.dirname(os.path.realpath(__file__))
config_file = dir_path + '/config.json'
# instantiate Slack client
output_error_file = ""
with open(config_file) as json_data_file:
data = json.load(json_data_file)
token=data["slack"]["SLACK_BOT_TOKEN"]
if 'logging' in data:
if 'output_file' in data['logging']:
output_all_file = data['logging']['output_file']
else:
exit("Please include output_file in config")
if 'output_error_file' in data['logging']:
output_error_file = data['logging']['output_error_file']
else:
output_all_file = dir_path + "/sambot.log"
logging_config = dict(
version = 1,
formatters = {
'f': {'format':
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'}
},
handlers = {
'Stream': {'class': 'logging.StreamHandler',
'formatter': 'f',
'level': 'DEBUG'
},
'file_all': {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'DEBUG',
'formatter': 'f',
'filename': output_all_file,
'mode': 'a',
'maxBytes': 10485760,
'backupCount': 5,
},
},
root = {
'handlers': ['Stream', 'file_all'],
'level': 'DEBUG',
},
)
if output_error_file != "":
logging_config['handlers']['file_error'] = {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'ERROR',
'formatter': 'f',
'filename': output_error_file,
'mode': 'a',
'maxBytes': 10485760,
'backupCount': 5,
}
logging_config['root']['handlers'].append('file_error')
dictConfig(logging_config)
logger = logging.getLogger('SAMbot')
slack_client = SlackClient(token)
logger.info("Slack client created")
logger.info("Connecting to misp server")
misp = misp_custom(data['misp']['url'], data['misp']['key'], data['misp']['ssl'])
logger.info("Connected to misp server successfully")
helperFunc = helper.TonyTheHelper(slack_client)
# starterbot's user ID in Slack: value is assigned after the bot starts up
starterbot_id = None
# constants
RTM_READ_DELAY = 1 # 1 second delay between reading from RTM
EXAMPLE_COMMAND = "Tell a joke"
MENTION_REGEX = "^<@(|[WU].+?)>(.*)"
####
## Get the slack username name for the message
####
def get_username(slack_event):
members = slack_client.api_call("users.list")['members']
if 'user' in slack_event:
logger.info(slack_event['user'])
for member in members:
if member['id'] == slack_event['user']:
name = member['profile']['display_name_normalized']
logger.info(name)
return name
else:
return "Unknown"
####
## Get the slack channel name for the message
####
def get_channelname(slack_event):
channels = slack_client.api_call("conversations.list", types="public_channel,private_channel")['channels']
if 'channel' in slack_event:
logger.info(slack_event['channel'])
for channel in channels:
if channel['id'] == slack_event['channel']:
name = channel['name']
logger.info(name)
return "#" + name
else:
return "Unknown"
def parse_bot_commands(slack_events):
"""
Parses a list of events coming from the Slack RTM API to find bot commands.
If a bot command is found, this function returns a tuple of command and channel.
If its not found, then this function returns None, None.
"""
for event in slack_events:
try:
#logger.debug(event)
if event["type"] == "message" and "files" in event:
for file in event["files"]:
if file["mode"] == "snippet":
url = file["url_private_download"]
channel = get_channelname(event)
title = file["title"]
#Work out the title
if title == "Untitled":
#Now check how to display the title
if multi_channel:
strTitle = channel
else:
strTitle = default_title
else:
if multi_channel:
strTitle = channel + " " + title
else:
strTitle = default_title + " " + title
headers = {'Authorization': 'Bearer '+token}
r = requests.get(url, headers=headers)
content = r.content.decode("utf-8")
e_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(event['event_ts'])))
e_title = e_time + " - " + str(strTitle)
username = get_username(event)
misp_response = misp.misp_send(0, content, e_title, username)
return misp_response, None, event["channel"], event["user"]
elif event["type"] == "message" and not "subtype" in event:
logger.debug("Caught new method")
user_id, message = parse_direct_mention(event["text"])
logger.debug("User_id: %s \n Message: %s" %(user_id, message))
logger.debug("starterbot_id : %s" %starterbot_id)
if user_id == starterbot_id:
return None, message, event["channel"], user_id
except:
error = traceback.format_exc()
helperFunc.respond_channel(error, event["channel"])
return None, None, None, None
# def respond(command, channel, user):
# # This is where you start to implement more commands!
# # Sends the response back to the channel
# slack_client.api_call(
# "chat.postEphemeral",
# channel=channel,
# text=command,
# user=user
# )
# def helperFunc.respond_channel(command, channel):
# slack_client.api_call(
# "chat.postMessage",
# channel=channel,
# text=command
# )
def parse_direct_mention(message_text):
"""
Finds a direct mention (a mention that is at the beginning) in message text
and returns the user ID which was mentioned. If there is no direct mention, returns None
"""
matches = re.search(MENTION_REGEX, message_text)
# the first group contains the username, the second group contains the remaining message
return (matches.group(1), matches.group(2).strip()) if matches else (None, None)
def tell_a_joke(command, channel, user):
"""
Executes bot command if the command is known
"""
# Default response is help text for the user
default_response = "Not sure what you mean. Try *{}*.".format(EXAMPLE_COMMAND)
help_command = "Help"
# Finds and executes the given command, filling in response
response = None
# This is where you start to implement more commands!
if command.lower().startswith(EXAMPLE_COMMAND.lower()):
response = pyjokes.get_joke(category='all') + " This joke has been Brought to you by pyjokes."
elif command.lower().startswith(help_command.lower()):
response = helperFunc.print_help()
# Sends the response back to the channel
helperFunc.respond_channel(response or default_response, channel)
if __name__ == "__main__":
if slack_client.rtm_connect(with_team_state=False, auto_reconnect=True):
logger.info("SAMbot connected and running!")
# Read bot's user ID by calling Web API method `auth.test`
starterbot_id = slack_client.api_call("auth.test")["user_id"]
online = True
while online:
try:
misp_response, smartass, channel, user = parse_bot_commands(slack_client.rtm_read())
if misp_response:
helperFunc.respond(misp_response, channel, user)
elif smartass:
print(smartass)
tell_a_joke(smartass, channel, user)
time.sleep(RTM_READ_DELAY)
except Exception as e:
error = traceback.format_exc()
logger.error(error)
helperFunc.respond_channel("The bot has caught a fatal error. Please review the error log. Exiting now.", "#bot-test")
online = False
else:
logger.info("Connection failed. Exception traceback printed above.")