-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
339 lines (277 loc) · 12.2 KB
/
bot.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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import os
import json
import time
import logging
import threading
from datetime import datetime
from flask import Flask, request
import requests
from webexteamssdk import WebexTeamsAPI
from apscheduler.schedulers.background import BackgroundScheduler
from tinydb import TinyDB, Query, where
from tinydb.operations import delete, increment, decrement
from config import (
webex_teams_token,
bot_email,
bot_name,
logging_config,
webhook_listener_base_url,
webhook_port,
)
logging.basicConfig(**logging_config)
logger = logging.getLogger()
# initialize the database
db = TinyDB("db.json", indent=2, sort_keys=True)
db.table(name="_default", cache_size=0)
User = Query()
# Initialize the Bot in Webex Teams
api = WebexTeamsAPI(access_token=webex_teams_token)
bot_room_list = api.rooms.list()
registered_webhooks = api.webhooks.list()
webhook_listener = webhook_listener_base_url + f":{webhook_port}/{bot_name}"
# initialize the db for users who do not yet exist
for room in bot_room_list:
print(f"bot is spawning in {room.title}")
app = Flask(__name__)
help_message_group = f"## Webex Teams Update Notifier\nThank you for adding me to your space. I am here to alert you when new versions of Webex Teams are released by Cisco. I will do this automatically unless you ask me not to.\n\n* If you want to stop receiving automatic updates simply @mention me and type `unsubscribe`.\n\n* If you want to opt back in simply @mention me and type `subscribe`\n\n* If you want to know the latest version, simply type `version`"
help_message_direct = f"## Webex Teams Update Notifier\nThank you for adding me to your space. I am here to alert you when new versions of Webex Teams are released by Cisco. I will do this automatically unless you ask me not to.\n\n* If you want to stop receiving automatic updates simply type `unsubscribe`.\n\n* If you want to opt back in simply type `subscribe`\n\n* If you want to know the latest version, simply type `version`"
release_notes = f"https://help.webex.com/en-us/mqkve8/Cisco-Webex-Teams-Release-Notes"
whats_new = f"https://help.webex.com/en-us/8dmbcr/What-s-New-in-Cisco-Webex-Teams"
def register_webhook():
# cleanout any old webhooks the bot created in the past when initializing
for webhook in registered_webhooks:
try:
api.webhooks.delete(webhook.id)
except Exception as e:
logger.info(e)
# Register the BOT webhook for new message notification
webhook_reg = api.webhooks.create(
name=bot_name, targetUrl=webhook_listener, resource="all", event="all"
)
logger.info(webhook_reg)
def get_latest_version():
"""
returns a dict with the latest win and osx version numbers
"""
win_ver_url = "https://7f3b835a2983943a12b7-f3ec652549fc8fa11516a139bfb29b79.ssl.cf5.rackcdn.com/WebexTeamsDesktop-Windows-Gold/webexteams_upgrade.txt"
mac_ver_url = "https://7f3b835a2983943a12b7-f3ec652549fc8fa11516a139bfb29b79.ssl.cf5.rackcdn.com/WebexTeamsDesktop-OSX-Gold/webexteams_upgrade.txt"
win_ver_info = requests.get(win_ver_url)
mac_ver_info = requests.get(mac_ver_url)
win_ver_dict = json.loads(win_ver_info.text)
mac_ver_dict = json.loads(mac_ver_info.text)
return {
win_ver_dict["versionInfo"]["platform"]: win_ver_dict["versionInfo"]["version"],
mac_ver_dict["versionInfo"]["platform"]: mac_ver_dict["versionInfo"]["version"],
}
def check_version_cache_exists():
exists = os.path.isfile("version_cache.json")
if exists:
pass
else:
update_version_cache(get_latest_version())
def get_old_version():
check_version_cache_exists()
with open("version_cache.json", "rb") as ov:
version_file = ov.read()
version_dict = json.loads(version_file)
return version_dict
def latest_version_message(version_info):
"""
return a message formatted with the latest versions known available
"""
messages = []
for platform, version in version_info.items():
message_body = (
f"The latest version of Webex Teams for {platform} is **{version}**"
)
messages.append(message_body)
messages.append(
f"To learn more, you can check out the [release notes]({release_notes}) and find out [what's new]({whats_new})"
)
return messages
def compare_latest_version(version_info):
# pull last known version and compare it to the latest one received from get_latest_version()
updated_versions = []
old_ver = get_old_version()
new_ver = version_info
for platform, version in old_ver.items():
if new_ver[platform] > version:
updated_versions.append({platform: new_ver[platform]})
return updated_versions
def update_room_in_database(json_data):
"""
# Get Room details from room ID and update the DB if room does not exist
"""
room_id = json_data["data"]["roomId"]
room = api.rooms.get(roomId=room_id)
print(f"webhook received from: {room.title}")
room_type = json_data["data"]["roomType"]
bot_user = db.search(User.room_id == room_id)
if bot_user == [] or bot_user == None:
print(f"{room.title} not in db")
logger.info(f"{room.title} not in db")
db.insert(
{
"room_id": room_id,
"room_title": room.title,
"room_type": room_type,
"subscribed": True,
"help_requests": {"general": 0},
"last_access": str(datetime.now()),
"createdAt": str(datetime.now()),
}
)
else:
bot_user[0]["last_access"] = str(datetime.now())
bot_user[0]["room_title"] = room.title
bot_user[0]["help_requests"]["general"] = (
bot_user[0]["help_requests"]["general"] + 1
)
db.write_back(bot_user)
def unsubscribe_to_updates(room_id, reason="message"):
"""
update the database subscription to false if the user types `unsubscribe`
"""
bot_user = db.search(User.room_id == room_id)
bot_user[0]["subscribed"] = False
db.write_back(bot_user)
logger.info(f"room has unsubscribed from updates: {room_id}")
print(f"room has unsubscribed from updates: {room_id}")
if reason == "message":
api.messages.create(
roomId=room_id,
markdown=f"This room is now unsubscribed from update announcements.",
)
def subscribe_to_updates(room_id, reason="message"):
"""
update the database subscription to True if the user types `subscribe`
"""
bot_user = db.search(User.room_id == room_id)
bot_user[0]["subscribed"] = True
logger.info(f"room has subscribed to updates: {room_id}")
print(f"room has subscribed to updates: {room_id}")
if reason == "message":
api.messages.create(
roomId=room_id,
markdown=f"This room is now subscribed to update announcements.",
)
else:
if bot_user[0]["room_type"] == "group":
api.messages.create(roomId=room_id, markdown=help_message_group)
else:
api.messages.create(roomId=room_id, markdown=help_message_direct)
db.write_back(bot_user)
def respond_to_message(json_data):
"""
"""
message_id = json_data["data"]["id"]
user_id = json_data["data"]["personId"]
email = json_data["data"]["personEmail"]
room_id = json_data["data"]["roomId"]
room_type = json_data["data"]["roomType"]
input_file = json_data["data"].get("files")
received_message = api.messages.get(messageId=message_id)
# Only respond to messages not from the Bot account to avoid infinite loops...
if email == bot_email:
return # break out of this function
# print(received_message)
if "unsubscribe" in received_message.text.lower():
unsubscribe_to_updates(room_id, reason="message")
elif "subscribe" in received_message.text.lower():
subscribe_to_updates(room_id)
elif "help" in received_message.text.lower() and room_type == "direct":
api.messages.create(roomId=room_id, markdown=help_message_direct)
elif "help" in received_message.text.lower() and room_type == "group":
api.messages.create(roomId=room_id, markdown=help_message_group)
else:
latest_versions = get_latest_version()
version_messages = latest_version_message(latest_versions)
for message in version_messages:
api.messages.create(roomId=room_id, markdown=f"{message}")
@app.route(f"/{bot_name}", methods=["POST"])
def webhook_receiver():
"""
Listen for incoming webhooks. Webex Teams will send a POST for each message directed to the BOT.
For a group space, @mention of the BOT must occur.
For a 1-1, @mentions are not allowed and the bot will respond to any message directed to it.
"""
json_data = request.json
# logger.debug(json_data)
# update database with room info if it does not exist yet
if json_data["data"]["personEmail"] != bot_email:
update_room_in_database(json_data)
# print(json_data)
if json_data["resource"] == "memberships" and json_data["event"] == "created" and json_data["data"]["roomType"] == "direct":
update_room_in_database(json_data)
subscribe_to_updates(
room_id=json_data["data"]["roomId"], reason="deleted_membership"
)
if json_data["resource"] == "memberships" and json_data["event"] == "deleted" and json_data["data"]["roomType"] == "direct":
# disable subscription for room
unsubscribe_to_updates(
room_id=json_data["data"]["roomId"], reason="deleted_membership"
)
if json_data["resource"] == "messages" and json_data["event"] == "created":
respond_to_message(json_data)
return "200"
def update_version_cache(latest_versions):
with open("version_cache.json", "w") as outfile:
json.dump(latest_versions, outfile, indent=2)
return True
def alert_subscribers(messages):
"""
Alert subscribers that a version has changed
"""
subscribers = db.search(User.subscribed == True)
for user in subscribers:
try:
message_heading = f"## Webex Teams Update Notification:\n\n"
message_body = "".join(messages)
message_footer = f"To unsubscribe just type `unsubscribe`\n\n"
new_message = message_heading + message_body + message_footer
api.messages.create(user["room_id"], markdown=new_message)
except Exception as e:
unsubscribe_to_updates(room_id=user['room_id'], reason="404 not found")
logger.error(e)
logger.error(f"unable to send to room {user['room_id']}: {user['room_id']}")
else:
logger.info(f"sending {messages} to {user['room_title']}")
def construct_version_update_messages(version_check):
messages = []
for ver in version_check:
for platform, version in ver.items():
messages.append(f"* Webex Teams for {platform} has been updated to version {version}.\n\n")
messages.append(
f"To learn more, you can check out the [release notes]({release_notes}) and find out [what's new]({whats_new}). "
)
return messages
def periodic_version_check():
"""
This function will run inside a loop and check if versions have changed every 30 minutes.
"""
# interval = 180 # frequency of checks
# time.sleep(interval / 2)
logger.debug(f"checking version for change")
latest_versions = get_latest_version()
version_changed = compare_latest_version(latest_versions)
if not version_changed:
print(f"no change in version")
pass
else:
update_messages = construct_version_update_messages(version_changed)
# alert_subscribers of change and send update messages
alert_subscribers(update_messages)
update_version_cache(latest_versions)
# threading.Timer(interval / 2, periodic_version_check).start()
if __name__ == "__main__":
register_webhook()
latest_versions = get_latest_version()
# print(latest_versions)
version_messages = latest_version_message(latest_versions)
for message in version_messages:
print(message)
scheduler = BackgroundScheduler()
job = scheduler.add_job(periodic_version_check, "interval", minutes=7)
scheduler.start()
print(f"bot is running")
app.run(debug=True, host="0.0.0.0", port=webhook_port, use_reloader=False)