Add excpetion handling and fix actions palcement in schema

master
Gary Steers 2020-02-05 22:23:55 +01:00
parent e96d7388b9
commit eaf469dda4
1 changed files with 10 additions and 17 deletions

View File

@ -1,13 +1,12 @@
#!/usr/bin/env python
import json, os, httplib, urllib, ssl, copy
import json, httplib, urllib, ssl, copy
# import stock icons
try:
stock_icons = json.loads(open('icons.json','r').read())
except:
print('Unable to load icon file')
os._exit(1)
raise Exception('Unable to load icon file')
# The Actual class
class MessageCard:
@ -18,7 +17,6 @@ class MessageCard:
'@context': 'http://schema.org/extensions',
'summary': '',
'sections': [],
'potentialAction': []
}
action_button_template = {
@ -41,8 +39,7 @@ class MessageCard:
try:
self.SetupTLS(tls_verify_host,tls_verify_mode)
except:
print('Unable to setup TLS/SSL Context')
os._exit(1)
raise Exception('Unable to setup TLS/SSL Context')
def SetupTLS(self,tls_verify_host,tls_verify_mode):
self.tls_ctx = ssl.create_default_context()
@ -54,11 +51,13 @@ class MessageCard:
if isinstance(data_array,dict):
for key, value in data_array.items():
self.facts.append({'name': key, 'value': value})
if isinstance(data_array,list):
elif isinstance(data_array,list):
for fact in data_array:
if isinstance(fact,dict):
for key, value in fact.items():
self.facts.append({'name': key, 'value': value})
else:
raise Exception('No data provided for facts')
def AddButton(self, action_array):
" Add a button, expects a dict with action_name, button_label and post_uri "
@ -79,10 +78,7 @@ class MessageCard:
raise Exception('post_uri not present')
self.actions.append(thisAction)
else:
self.error = 'No data provided for action'
return False
raise Exception('No data provided for action')
def GenerateCard(self):
" Generate the JSON for the card "
@ -92,7 +88,7 @@ class MessageCard:
self.card['sections'][0]['activitySubtitle'] = self.subtitle
self.card['sections'][0]['activityImage'] = self.icon
self.card['sections'][0]['facts'] = self.facts
self.card['sections'][0]['potentialAction'] = self.actions
self.card['potentialAction'] = self.actions
self.card['sections'][0]['markdown'] = 'true'
self.card['summary'] = self.title
@ -101,8 +97,7 @@ class MessageCard:
self.GenerateCard()
uri = self.channel_uri.split('/')
if not len(uri) == 8:
self.error = 'Invalid Channel URI'
return False
raise Exception('Invalid Channel URI')
endpoint = uri[2]
del uri[2], uri[1], uri[0]
uri = '/' + str('/'.join(uri))
@ -110,13 +105,11 @@ class MessageCard:
try:
hookconnection = httplib.HTTPSConnection(endpoint, context=self.tls_ctx)
except:
self.error = 'Unable to open connection'
return False
raise Exception('Unable to open connection')
hookconnection.request('POST',uri,json.dumps(self.card))
self.response = hookconnection.getresponse()
#print(self.response.read())
def PrintJSON(self):
" Print the JSON of the card "
self.GenerateCard()