def teamswebhook(): """ Handle """ print("\n" + str(request.method) + " received\n") print(request.json) json_data = request.json webhook_obj = Webhook(json_data) room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) # Don't respond to yourself if message.personId == teams_api.people.me().id: return 'OK' else: teams_api.messages.create(room.id, text=chess_response) person = teams_api.people.get(message.personId) with open('players.json') as f: player_json = f.read() try: board_dest = json.loads(player_json)[0][person]['active'] except (Exception) as e: board_dest = "board.bd" board_dict = json.loads(player_json)[0] board_dict[person]['active'] = board_dest with open('players.json', 'w') as f: json.dump(board_dict, f) board = parser.Board(dest=board_dest) chess_response = parser.parse(board, message)
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': return (browser_response) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") try: # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("person========",person) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: print("FOUND '/CAT'. Now sending adaptive card") # Get a cat fact #cat_fact = get_catfact() #print("SENDING CAT FACT '{}'".format(cat_fact)) # Post the fact to the room where the request was received api.messages.create(room.id, text="my adaptive card", attachments= default_message ) else: #default message api.messages.create(room.id, text="This client doesnt support Adaptive cards", attachments= default_message ) return 'OK' except: print("Couldnt retreive message") return 'OK'
def POST(self): """Respond to inbound webhook JSON HTTP POSTs from Webex Teams.""" json_data = web.data() # Get the POST data sent from Webex Teams #print("\nWEBHOOK POST RECEIVED:") #print(json_data, "\n") webhook_obj = Webhook( json_data) # Create a Webhook object from the JSON data room = api.rooms.get(webhook_obj.data.roomId) # Get the room details message = api.messages.get( webhook_obj.data.id) # Get the message details # Ignore messages bot itself sent if message.personId == me.id: return 'OK' else: # Message was sent by someone else; parse message and respond. person = api.people.get( message.personId) # Get the sender's details print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) #Test message sent #response = 'Message received {}'.format(mention(person.emails[0])) #api.messages.create(room.id, markdown=response) actionSelector( api, message, teams) #Depending on message defines action to perform return 'OK'
def teamswebhook(): if request.method == 'POST': json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") webhook_obj = Webhook(json_data) # Details of the message created room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) person = teams_api.people.get(message.personId) email = person.emails[0] print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = teams_api.people.me() if message.personId == me.id: return 'OK' else: teams_api.messages.create(room.id, text='hello, person who has email ' + str(email)) else: print('received none post request, not handled!')
def webex_teams_webhook_events(): if request.method == 'GET': return ("""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"> <title>Webex Teams Bot served via Flask</title></head><body><p> <strong>Your Flask web server is up and running!</strong></p></body></html>""") elif request.method == 'POST': json_data = request.json webhook_obj = Webhook(json_data) if webhook_obj.resource != "messages" or webhook_obj.event != "created": return 'OK' else: room = api.rooms.get(webhook_obj.data.roomId) message = api.messages.get(webhook_obj.data.id) person = api.people.get(message.personId) if message.personId == api.people.me().id: return 'OK' else: if not Database.get_user(conn, person.id): Database.create_user(conn, (person.id, person.emails[0], None, None, None)) msg = ((message.text).replace("TheBetterGifBot", "")).strip().lower() print("\nNEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'".format(msg)) return process_command(msg, room, message, person)
async def webhook(request): """Respond to inbound webhook HTTP POST from Webex Teams.""" logger.debug("Received webex webhook call") # Get the POST data sent from Webex Teams json_data = request.json # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the message details message = self.api.messages.get(webhook_obj.data.id) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the # messages that the bot posts and thereby create a loop me = self.api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return response.text("OK") else: await self.process_message(on_new_message, text=message.text, sender_id=message.personId) return response.text("")
def webhook_received(): """ Recieve the card responses """ if request.method == 'POST': webhook = Webhook(request.json) respond_to_button_press(webhook) return "Webhook Recieved", 200
def webex_teams_webhook_events(): """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Create a Webhook object from the JSON data webhook_obj = Webhook(request.json) print(webhook_obj) if (webhook_obj.resource == MESSAGE_WEBHOOK_RESOURCE and webhook_obj.event == MESSAGE_WEBHOOK_EVENT): wbxu.respond_to_message_event(webhook_obj) elif (webhook_obj.resource == CARDS_WEBHOOK_RESOURCE and webhook_obj.event == CARDS_WEBHOOK_EVENT): pass else: print(f"IGNORING UNEXPECTED WEBHOOK:\n{webhook_obj}") return "OK"
def post_events_service(request): """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json log.info("\n") log.info("WEBHOOK POST RECEIVED:") log.info(json_data) log.info("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) log.info("NEW MESSAGE IN ROOM '{}'".format(room.title)) log.info("FROM '{}'".format(person.displayName)) log.info("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return {'Message': 'OK'} else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: log.info("FOUND '/CAT'") # Get a cat fact catfact = get_catfact() log.info("SENDING CAT FACT'{}'".format(catfact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=catfact) return {'Message': 'OK'}
def execute_action(self, json_data): # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = self.api.rooms.get(webhook_obj.data.roomId) # Get the message details action = self.api.attachment_actions.get(webhook_obj.data.id) # Get the sender's details person = self.api.people.get(action.personId) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. if action.personId == self.me.id: print("Sent by me") # Message was sent by me (bot); do not respond. return "OK" # Sanitise the inputs so that it is compatable with the database and to remove # security concerns if type(action.inputs) == list: inputs = self.editor.sanitise_inputs(action.inputs[0]) else: inputs = self.editor.sanitise_inputs(action.inputs) # Will return a string if something went wrong, otherwise a dict if type(inputs) == str: self.api.messages.create(roomId=room.id, markdown=str(f"**{inputs}**")) else: edit_result = self.editor.edit_switch_by_id( action.inputs["id"], inputs) # Same here, if something goes wrong it will be a str if type(edit_result) == str: self.api.messages.create(roomId=room.id, markdown=str(f"**{edit_result}**")) else: # Everything is OK self.api.messages.delete(messageId=webhook_obj.data.messageId) if edit_result == utils.Results.EDIT: message = f"Successfully updated {action.inputs['id']}" else: message = f"Successfully added {action.inputs['id']}" self.api.messages.create(roomId=room.id, markdown=str(f"**{message}!**")) return "OK"
def webex_teams_webhook_events(): """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Create a Webhook object from the JSON data webhook_obj = Webhook(request.json) # Handle a new message event if (webhook_obj.resource == MESSAGE_WEBHOOK_RESOURCE and webhook_obj.event == MESSAGE_WEBHOOK_EVENT): respond_to_message(webhook_obj) # Handle an Action.Submit button press event elif (webhook_obj.resource == CARDS_WEBHOOK_RESOURCE and webhook_obj.event == CARDS_WEBHOOK_EVENT): respond_to_button_press(webhook_obj) # Ignore anything else (which should never happen else: print(f"IGNORING UNEXPECTED WEBHOOK:\n{webhook_obj}") return "OK"
def teamswebhook(): if request.method == 'POST': json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") webhook_obj = Webhook(json_data) # Details of the message created room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) person = teams_api.people.get(message.personId) email = person.emails[0] print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = teams_api.people.me() searchterm = message.text # Check message length to avoid array out of bounds # if len(searchterm) > 11): # if searchterm[:len("Kalah duck ")] == "Kalah duck ": searchterm = searchterm[(len("Kalah ") - 1):] answer = query(searchterm) teams_api.messages.create(room.id, text=answer.abstract) # else: # teams_api.messages.create(room.id, text="Search term too short that's what she said.") # # if message.personId == me.id: # return 'OK' # else: # teams_api.messages.create(room.id, text=searchterm +str(email)) else: print('received none post request, not handled!')
def teamswebhook(): # Only execute this section of code when a POST request is sent, as a POST indicates when a message # has been sent and therefore needs processing. if request.method == 'POST': json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Pass the JSON data so that it can get parsed by the Webhook class webhook_obj = Webhook(json_data) # Obtain information about the request data such as room, message, the person it came from # and person's email address. room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) person = teams_api.people.get(message.personId) email = person.emails[0] print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = teams_api.people.me() if message.personId == me.id: return 'OK' else: teams_api.messages.create(room.id, text='Hello, person who has email ' + str(email) + ' and sent the message ' + str(message)) else: print('received none post request, not handled!')
def teamswebhook(): # Only execute this section of code when a POST request is sent, as a POST indicates when a message # has been sent and therefore needs processing. if request.method == 'POST': json_data = request.get_json() print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Pass the JSON data so that it can get parsed by the Webhook class webhook_obj = Webhook(json_data) # Obtain information about the request data such as room, message, the person it came from # and person's email address. room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) person = teams_api.people.get(message.personId) email = person.emails[0] print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = teams_api.people.me() if message.personId == me.id: return 'OK' else: teams_api.messages.create(spaceRoomId, text='Hello, ' + person.displayName + '.') if 'thoughts' in message.text or 'feeling' in message.text or 'think' in message.text: teams_api.messages.create(spaceRoomId, text='Checking votes..') contents = urllib.request.urlopen('http://server:3000/votes/') teams_api.messages.create( spaceRoomId, text='Here\'s how people feel about the suggestion:') data = json.loads(contents.read().decode()) print(data) average = 0 speech_votes = data['votes']['speechVotes'] video_votes = data['votes']['videoVotes'] for speech_score in speech_votes: average += float(speech_score) teams_api.messages.create( spaceRoomId, text='A speech sentiment score is: ' + str("%.2f" % round(float(speech_score), 2))) for video_score in video_votes: average += float(video_score) teams_api.messages.create( spaceRoomId, text='The video sentiment score for one person is: ' + str("%.2f" % round(float(video_score), 2))) average /= (len(speech_votes) + len(video_votes)) print('average', average) percentage = average + 10 percentage *= 5 emoji = '' if percentage > 50: emoji = ':D' else: emoji = 'D:' teams_api.messages.create( spaceRoomId, text='The average sentiment score for <' + suggestion + '> is: ' + str("%.2f" % round(float(percentage), 2)) + '%! ' + emoji) else: teams_api.messages.create(spaceRoomId, text='Say what?') else: print('received none post request, not handled!')
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Webex Teams Bot served via Flask</title> </head> <body> <p> <strong>Your Flask web server is up and running!</strong> </p> <p> Here is a nice Cat Fact for you: </p> <blockquote>{}</blockquote> </body> </html> """.format(get_catfact())) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: print("FOUND '/CAT'") # Get a cat fact cat_fact = get_catfact() print("SENDING CAT FACT '{}'".format(cat_fact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=cat_fact) return 'OK'
def webex_teams_webhook_attachements(): """Processes incoming requests to the '/attachements' URI.""" if request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json print("\n") print("Attachement POST RECEIVED:") print(json_data) print("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the sender's details person = api.people.get(webhook_obj.data.personId) if webhook_obj.data.type == "submit": # Get the message details submit_json = api.attachment_actions.get(webhook_obj.data.id) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print(" Email id: ",person.emails[0]) print("Input values from submit '{}'\n".format(submit_json)) #bug in webexteamssdk\models\mixins\attachment_action.py", line 73, has to be fixed #only then this function works: submit_json.inputs print(submit_json.inputs['submit_value']) print(dict(submit_json.inputs)) if submit_json.inputs['submit_value'] == "poll_start": print("poll_start received") api.messages.create(room.id, text='Get number of questions', attachments= poll_get_question_count ) elif submit_json.inputs['submit_value'] == "poll_count": print("poll questions count received:") polls_qc = int(submit_json.inputs['polls_questions_count']) print(polls_qc) print(poll_form_generator(polls_qc)) api.messages.create(room.id, text='Poll form creator', attachments= poll_form_generator(polls_qc) ) elif submit_json.inputs['submit_value'] == "poll_creator_form": print("poll_creator_form submission received, sending preview form:") #saves end user form in db, this function also returns the form #this end user fomr is used to publish the poll after preview preview_form = save_formdetails(room,person,submit_json) print(preview_form) api.messages.create(room.id, text='Poll preview form', attachments= preview_form ) elif submit_json.inputs['submit_value'] == "poll_publish": print("poll_publish received, sending end user form to all participants") #get enduser form end_user_form = fetch_end_user_form(submit_json.inputs['poll_id']) #get the list of participants participants_list = get_poll_participants(submit_json.inputs['poll_id']) #remove leading and trailing whitespace participants_list = [x.strip() for x in participants_list] print("stripped list:",participants_list) #remove duplicate entries participants_list = list(set(participants_list)) #get the list of all rooms this Bot is part of all_rooms = api.rooms.list(type="group") all_room_title = [room.title for room in all_rooms] print ("all_room_title: ",all_room_title) #validate email ids and rooms regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' participant_check = True for participant in participants_list: if(re.search(regex,participant)): print(participant,"Valid Email") elif [c for c in all_room_title if c in participant]: #if its not email id then it should be room title , validate it from all_rooms print(participant, " is valid room") else: participant_check = False error_msg = "email or Team Space: \"" + participant + "\" is invalid. Cannot publish. Start over" print(error_msg) api.messages.delete(webhook_obj.data.messageId) poll_abort_db(submit_json.inputs['poll_id']) api.messages.create(room.id, text=error_msg) break if participant_check: #create a new table create_enduser_table(submit_json.inputs['poll_id']) for participant in participants_list: email_id = "default" room_name = "default" if(re.search(regex,participant)): print("Sending enduser form to email: ", participant) email_id = participant rsp_msg = api.messages.create(toPersonEmail=participant, text='Poll end user form sent to all participants', attachments= end_user_form) msg_id = rsp_msg.id else: room_id = [room.id for room in all_rooms if room.title in participant] room_name = participant print("Sending enduser form to team space: ",participant , "with room_id: ", room_id[0]) rsp_msg = api.messages.create(room_id[0], text='Poll end user form sent to all participants', attachments= end_user_form) msg_id = rsp_msg.id print("msg_id-------",msg_id) #save_msg_id(poll_id_value, msg_id , email_id, room_name) save_msg_id(submit_json.inputs['poll_id'] , msg_id,str(email_id) ,str(room_name)) elif submit_json.inputs['submit_value'] == "poll_abort": print("poll_abort received, removing entry from db") poll_abort_db(submit_json.inputs['poll_id']) api.messages.delete(webhook_obj.data.messageId) api.messages.create(room.id, text='poll canceled. Start again',) elif submit_json.inputs['submit_value'] == "poll_enduser_submit": print("poll_enduser_submit received, adding entry into db") response_val = save_enduser_inputs(submit_json,str(person.emails[0]),str(room.title)) #api.messages.delete(webhook_obj.data.messageId) api.messages.create(room.id, text=response_val, ) elif submit_json.inputs['submit_value'] == "poll_stop": print("poll_stop received") elif submit_json.inputs['submit_value'] == "poll_status": print("poll_status received") return 'OK'
def webhook(request): def SetupLogging(): # Configure the logger to write to the matilde.log file and to the console global logger logging.Formatter.converter = time.gmtime hostName = socket.gethostname() logger = logging.getLogger(hostName) logger.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)-8s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(formatter) logger.addHandler(console) # the log file is located in the same folder as this script # -> adds the absolute path of the current module to the log file file = os.path.join(os.path.dirname(__file__), 'matilde-bot.log') logfile = logging.FileHandler(file) logfile.setLevel(logging.DEBUG) logfile.setFormatter(formatter) logger.addHandler(logfile) def ReadSettings(file): # reads the settings INI file and assign the values to global variables # returns TRUE if OK def ResetConfigFile(filename, newfile): # Writes or resets the configuration file. Returns nothing # note: allow_no_value is required to add comments config = configparser.ConfigParser(allow_no_value=True) config.optionxform = str try: config.add_section('WXT') config.set('WXT', 'botToken', '<input here>') config.set('WXT', 'logSpace', '<input here>') config.set('WXT', 'notification', 'No') config.set('WXT', 'TeamScope', '<input here>') config.add_section('DB') config.set('DB', 'host', '<input here>') config.set('DB', 'port', '<input here>') config.set('DB', 'user', '<input here>') config.set('DB', 'password', '<input here>') config.set('DB', 'dbname', '<input here>') with open(filename, 'w') as configfile: config.write(configfile) if newfile: logger.warning('Config file created in the current folder.') else: logger.warning( 'Configuration file reset in the current folder.') logger.warning( 'Please set the required configuration parameters and re-run.') except Exception as e: logger.error('Error creating the configuration file: ' + e) global botToken, logSpace, NOTIF_ON, TeamScope global DBhost, DBport, DBuser, DBpass, DBname config = configparser.ConfigParser(allow_no_value=True) # the .ini file is located in the same folder as this script # -> adds the absolute path of the current module to the .ini filename file = os.path.join(os.path.dirname(__file__), file) if os.path.isfile(file): try: config.read(file) botToken = str(config['WXT']['botToken']).strip() logSpace = str(config['WXT']['logSpace']).strip() NOTIF_ON = config.getboolean('WXT', 'notification') TeamScope = str(config['WXT']['TeamScope']).strip() DBhost = str(config['DB']['host']).strip() DBport = str(config['DB']['port']).strip() DBuser = str(config['DB']['user']).strip() DBpass = str(config['DB']['password']).strip() DBname = str(config['DB']['dbname']).strip() # Validation of settings if len(botToken) < 90: raise ValueError('Setting not valid ' + botToken) if NOTIF_ON and len(logSpace) < 30: raise ValueError('Setting not valid ' + logSpace) except Exception as e: logger.critical('Error reading the .ini file ' + str(e)) ResetConfigFile(file, newfile=False) return False else: # Creates config file because it does not exist logger.critical('The .ini file does not exist') ResetConfigFile(file, newfile=True) return False return True SetupLogging() logger.info("Matilde's webhook received...") if not ReadSettings(file='config.ini'): logger.critical('Terminating') sys.exit() api = WebexTeamsAPI(botToken) # Create a Webhook object from the JSON data whookData = json.loads(request.body) webhook_obj = Webhook(whookData) # Get the space details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender details person = api.people.get(message.personId) # print("NEW MESSAGE IN ROOM '{}'".format(room.title)) # print("FROM '{}'".format(person.displayName)) # print("MESSAGE '{}'\n".format(message.text)) # filters out messages sent by Matilde herself if person.displayName != 'Matilde': # checks if the sender and/or the space are authorized if authorizedRequest(person.emails[0], room.id): logger.info('Request from authz user/space {}/{}'.format(person.emails[0], room.id)) # checks if the BOT service is enabled in the Matilde's DB argument = '' if not BOT_enabled(): response = 'maintenance' else: reqText = message.text.strip().lower() if reqText.lower() == 'matilde' or 'help' in reqText: response = 'help' elif 'status' in reqText: response = 'status' elif 'report' in reqText: trialId = re.search(r'\s[0-9]+', reqText) if trialId: trialId = int(trialId.group().strip()) if trialId > 0: response = 'trial_report' argument = trialId else: response = 'report_incomplete' else: response = 'report_incomplete' elif 'echo' in reqText: response = 'echo' argument = reqText else: response = 'unknown' else: response = 'unauthorized' argument = '' # executes action(person.emails[0], room.id, response, argument) return HttpResponse('<p>greetings from Matilde<p>')
def attachmentActions_webhook(): if request.method == 'POST': print("attachmentActions POST!") webhook_obj = Webhook(request.json) return process_card_response(webhook_obj.data)
def messages_webhook(): if request.method == 'POST': webhook_obj = Webhook(request.json) return process_message(webhook_obj.data)
def messageHandling(): f = open('./apic.creds', 'r') creds = f.read() f.close() creds = creds.split("\n") APIC_ADDR = creds[0] APIC_USER = creds[1] APIC_PASS = creds[2] f = open('./access.tkn', 'r') bot_token = f.read() f.close() f = open('./AWX.pass', 'r') contents = f.read() contents = contents.split('\n') awx_token = contents[0] awx_IP = contents[1] f.close() print(awx_token) json_data = request.data # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details ATM messages.get is bad, and i think it has delay while getting group chat messages message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) me = api.people.me() print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) if message.personId == me.id: return 'OK' else: if ("find" in message.text): return_msg = getIP(message.text) if (return_msg != "not_valid"): DATA = { 'extra_vars': { 'host_ip_addr': return_msg, 'RoomId': room.id, 'bot_token': bot_token, 'apic': APIC_ADDR, 'apic_username': APIC_USER, 'apic_password': APIC_PASS } } URL = 'http://' + str( awx_IP) + '/api/v2/job_templates/15/launch/' HEADERS = { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + str(awx_token) } api.messages.create(room.id, text=str("Finding " + return_msg + " in fabric")) r = requests.post(URL, data=json.dumps(DATA), headers=HEADERS) else: pre, preTwo, ip = message.text.split(" ") api.messages.create(room.id, text=str("\'" + ip + "\'" + " is not a valid IPV4 address")) elif ("Cohesity" in message.text): api.messages.create(room.id, text=str("Checking Cohesity now")) DATA = { 'extra_vars': { 'Return_Room': room.id, 'bot_token': bot_token } } URL = 'http://' + str(awx_IP) + '/api/v2/job_templates/17/launch/' HEADERS = { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + str(awx_token) } r = requests.post(URL, data=json.dumps(DATA), headers=HEADERS) elif ("create contract" in message.text): api.messages.create(room.id, text=str("Creating contract now....")) message_arr = message.text.split(" ") DATA = { 'extra_vars': { "src_ip_addr": message_arr[3], "dst_ip_addr": message_arr[4], "subj_name": message_arr[5], "dst_port": message_arr[6], 'apic': APIC_ADDR, 'apic_username': APIC_USER, 'apic_password': APIC_PASS, "bot_token": bot_token, "RoomId": room.id } } URL = 'http://' + str(awx_IP) + '/api/v2/job_templates/18/launch/' HEADERS = { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + str(awx_token) } r = requests.post(URL, data=json.dumps(DATA), headers=HEADERS) else: api.messages.create( room.id, text=str( "Bot Help Page: \n > @bot_name find IP_ADDRESS \n Finds the IP Address within the ACI fabric, if not there will return not found. If its found will return information about it. \n > @bot_name Cohesity \n Checks Cohesity for jobs run and provides information about pass/fail as well as providing links to them \n > @bot_name create contract SRC_IP DEST_IP SUBJ_NAME DST_PORT \n Creats a contract in ACI with using the parameters provided" )) return 'OK'
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Webex Teams Bot served via Flask</title> </head> <body> <p> <strong>Your Flask web server is up and running!</strong> </p> </body> </html> """) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) if person.firstName: #if they have a First Name populated on Webex Teams use that. Otherwise use their full name. first_name = person.firstName else: first_name = person.displayName #define list of questions questions = [ 'Is this a VRD project? (Yes/No)', 'Is this a new project? (Yes/No)', 'Are there any integrations or non-standard elements which require billable PS? (Yes/No)', 'Are there any on-site services? (Yes/No)', 'Are you adding sites? (Yes/No)', 'Are you adding any new integrations or non-standard elements which require billable PS? (Yes/No)', 'Are there any on-site services? (Yes/No)' ] # Bot Loop Control me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Helper functions list_update = 0 #import file and create dictionary history = {} with open("history_list.txt") as f: history = json.load(f) #get current time and time of last conversation current_time = datetime.now() print(current_time) #check if this user is in history list if message.personId in history: user_ID = history[message.personId] user_history = history[message.personId]['answers'] tracking = history[message.personId]['tracking'] last_conv_str = history[message.personId]['last_conv'] last_conv = datetime.strptime(last_conv_str, '%Y-%m-%d %H:%M:%S.%f') last_conv_print = last_conv.strftime('%m/%d/%Y') time_out = last_conv + timedelta(minutes=10) user_input = str.lower(message.text) user_input = remove_prefix(user_input, 'beta ') complete = tracking[2] show_results = 0 show_list = 0 print("Existing user: "******"Here are some commands you can give me: \n**Help**: to show all valid commands \n**Restart**: restart the questions from the beginning \n**Results**: see the previous list of documents based on the last time you completed all questions \n**List**: list all of the current design documents") api.messages.create( room.id, markdown= "Here are some commands you can give me: \n**Help**: to show all valid commands \n**Restart**: restart the questions from the beginning \n**Results**: see the previous list of documents based on the last time you completed all questions" ) elif user_input == 'list': show_results = 1 show_list = 1 elif current_time > time_out or user_input == 'restart': tracking = [0, 0, 0] user_history = [0, 0, 0, 0, 0, 0, 0] api.messages.create( room.id, text="Hi " + first_name + "! It's nice to hear from you again. We last spoke on " + last_conv_print + ". Let's get started.") next_question = tracking[0] next_question_txt = questions[next_question] api.messages.create(room.id, text=next_question_txt) elif complete == 1: if user_input == 'results': api.messages.create( room.id, text='Here are the results from last time') show_results = 1 else: api.messages.create( room.id, text='Welcome back ' + first_name + '! The last time we talked I gave you links to the UCCaaS documents you needed. \ Do you want to see that again? Then reply with "Results". Or reply with "Restart" to begin again.' ) else: current_answer = tracking[1] if user_input == 'yes' or user_input == 'y': user_history[current_answer] = 1 if tracking[1] == 3 or tracking[1] == 6: complete = 1 show_results = 1 tracking[2] = 1 else: tracking[1] += 1 elif user_input == 'no' or user_input == 'n': if tracking[1] == 3 or tracking[1] == 6: complete = 1 show_results = 1 tracking[2] = 1 else: tracking[1] += 1 else: api.messages.create( room.id, text= "I'm sorry I didn't understand that response. Please reply with Yes or No. You can also reply with HELP. Here is the last question I asked you..." ) next_question = tracking[0] next_question_txt = questions[next_question] api.messages.create(room.id, text=next_question_txt) return 'Ok' if tracking[1] == 2 and user_history[1] == 0: tracking[0] = 3 tracking[1] = 4 next_question = tracking[0] + 1 if complete != 1: next_question_txt = questions[next_question] api.messages.create(room.id, text=next_question_txt) tracking[0] += 1 if show_results == 1: api.messages.create( room.id, text= "Based on your answers, you need the following design documents: (Opening your browser and logging into CrowdAround will enable you to download the documents directly)" ) if user_history[1] == 1 or show_list == 1: api.messages.create( room.id, markdown= "Latest HLD version 2.01: [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4338989-102-2-647636/HLD%20Customer%20O-xxxxxxx%20v1%20mmddyy.dotm)" ) if user_history[0] == 0 or show_list == 1: api.messages.create( room.id, markdown= "Legacy SDW version 17:03: [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4286180-102-4-589448/UC-SDW%2017-03a%20final%20CUSTOMERNAME%20O-XXXXXXX-v1-mmdd17.xlsm)" ) elif user_history[0] == 1 or show_list == 1: api.messages.create( room.id, markdown= "Latest SDW version 19.03: [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4353240-102-1-652158/SDW%2019-03%20CUSTOMERNAME%20O-XXXXXXX-v1-mmdd19.xlsm)" ) if user_history[1] == 1 or show_list == 1: api.messages.create( room.id, markdown= "Latest SoR version 19.04: [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4335312-102-6-653816/SOR%20Verizon%20UCCaaS%20PS%20MRC%20SOR%20v19_04.dotm)" ) if user_history[2] == 1 or show_list == 1: if user_history[0] == 1 or show_list == 1: api.messages.create( room.id, markdown= "Latest SoW (Dated 4-10-19): [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4279389-102-5-653818/SOW%20Customer%20Project%20O-xxxxxxx%20v1%20mmdd19.dotm)" ) elif user_history[0] == 0 or show_list == 1: api.messages.create( room.id, markdown= "Legacy SoW: [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4279390-102-2-422140/Legacy%20UCCaaS%20Only%20NRC%20Addendum%20SOW%20Template%20011316.doc)" ) if user_history[3] == 1 or show_list == 1: api.messages.create( room.id, markdown= "Latest Site Services SoW: [Link](https://perc.vzbi.com)" ) elif user_history[1] == 0: api.messages.create( room.id, markdown= "Latest SoR version 19.04: [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4335312-102-6-653816/SOR%20Verizon%20UCCaaS%20PS%20MRC%20SOR%20v19_04.dotm)" ) if user_history[5] == 1 and user_history[0] == 0: api.messages.create( room.id, markdown= "Legacy SoW: [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4279390-102-2-422140/Legacy%20UCCaaS%20Only%20NRC%20Addendum%20SOW%20Template%20011316.doc)" ) elif user_history[5] == 1 and user_history[0] == 1: api.messages.create( room.id, markdown= "Latest SoW (Dated 4-10-19): [Link](https://crowdaround.verizon.com/servlet/JiveServlet/downloadBody/4279389-102-5-653818/SOW%20Customer%20Project%20O-xxxxxxx%20v1%20mmdd19.dotm)" ) if user_history[6] == 1: api.messages.create( room.id, markdown= "Latest Site Services SoW: [Link](https://perc.vzbi.com)" ) list_update = 1 else: print("This is a new user") api.messages.create( room.id, text="Hi " + first_name + "! I am the UCCaaS SA Bot. I can help you figure out which UCCaaS design documents you need for your project. Please answer the following questions:" ) history[message.personId] = { "last_conv": current_time, "tracking": [0, 0, 0], "answers": [0, 0, 0, 0, 0, 0, 0, 0, 0] } user_history = [0, 0, 0, 0, 0, 0, 0, 0, 0] tracking = [0, 0, 0] next_question = tracking[0] next_question_txt = questions[next_question] api.messages.create(room.id, text=next_question_txt) list_update = 1 #write updated entries to file if list_update == 1: history[message.personId]['answers'] = user_history history[message.personId]['last_conv'] = current_time history[message.personId]['tracking'] = tracking def myconverter(o): if isinstance(o, datetime): return o.__str__() with open("history_list.txt", "w") as f: json.dump(history, f, default=myconverter) return 'Ok'
def receive_message(self, json_data): # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = self.api.rooms.get(webhook_obj.data.roomId) # Get the message details message = self.api.messages.get(webhook_obj.data.id) # Get the sender's details person = self.api.people.get(message.personId) # if __debug__: # print(f"\nNEW MESSAGE IN ROOM '{room.title}'") # print(f"FROM '{person.displayName}'") # print(f"MESSAGE '{message.text}'\n") # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. if message.personId == self.me.id: print("Sent by me") # Message was sent by me (bot); do not respond. return "OK" if not message.text or message.text == "": print("Empty message.") return "OK" message_text = message.text # Remove the user tag if message_text.lower().startswith("meercat"): message_text = " ".join([ part for part in message_text.split(" ") if part.lower() != "meercat" ]) # Fix for help command if message_text.strip() == "help": message_text = "/help" # User has entered a command if message_text.strip()[0] == "/": response_message = self.handle_command(message.personId, message_text) else: # Create a unique session id as a combo of person and room id # We will also use this in the future to send content back (probably a little hacky) session_id = message.personId + "." + room.id # Call DialogFlow API to parse intent of message response = self.converter.detect_intent_texts( session_id, message_text, 'en') response_message = response.fulfillment_text if response_message: # Allow for a list response if type(response_message) is not list: response_message = [response_message] for response in response_message: # Response will be dict if it is an adaptivecard if type(response) is dict: self.api.messages.create( roomId=room.id, text=response['content']['fallbackText'], attachments=[response]) else: try: self.api.messages.create(roomId=room.id, markdown=str(response)) # Sometimes the message is too long so we will split it in half except ApiError as e: if "length limited" not in e.message.lower(): raise ApiError(e.response) parts = str(response).split('\n') part_1 = '\n'.join(parts[0:int(len(parts) / 2)]) part_2 = '\n'.join(parts[int(len(parts) / 2):]) self.api.messages.create(roomId=room.id, markdown=str(part_1)) self.api.messages.create(roomId=room.id, markdown=str(part_2)) response_text = {"message": "OK"} return jsonify(response_text)
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': logger.info("GET request recieved on port responding") return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WORKING</title> </head> <body> <p> <strong>WORKING</strong> </p> </body> </html> """) elif request.method == 'POST': logger.info("POST messaged received on port with the following details") json_data = request.json logger.info(str(json_data)) # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) logger.debug("NEW MESSAGE IN ROOM '{}'".format(room.title)) logger.debug("FROM '{}'".format(person.displayName)) logger.debug("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. logger.info("checked message but it was from me") return 'OK' else: # Message was sent by someone else; parse message and respond. if message.files: print(message.files) camsnapshots = snapshot.snapshot() newmessage = camsnapshots[0] print(camsnapshots[0]) api.messages.create(room.id, text="Mugshot Taken") headers= { 'Authorization': "Bearer ZTlhN2Y3YWYtOWYwNC00YWIzLTk0YjktMWY1Y2UxMjI4ODY0ZTNhN2FiN2QtMWRi_PF84_1eb65fdf-9643-417f-9974-ad72cae0e10f", 'cache-control': "no-cache", 'Postman-Token': "7c9aaad4-88a7-4206-9a7d-28fd442dc59d" } webex_attachment_start_fetch_time = datetime.now() ################ print(webex_attachment_start_fetch_time) dstresponse = requests.get(message.files[0], headers=headers) webex_attachment_finish_fetch_time = datetime.now() ################ print(webex_attachment_finish_fetch_time) webex_attachement_response_time = webex_attachment_finish_fetch_time - webex_attachment_start_fetch_time ################################ print(webex_attachement_response_time) print("################GOT DST") if dstresponse.status_code == 200: imageTarget = BytesIO(dstresponse.content) print("################GOT DST Content") print(type(imageTarget)) recognition = AppDynamicsHackathon2019_AWS.get_images_from_LOCAL_and_URL(imageTarget,camsnapshots[0]) api.messages.create(room.id, text=recognition) #try: # print(str(int(webex_attachement_response_time.microseconds))) # AppDController.Get_image(int(webex_attachement_response_time.microseconds), "WebEx") # print(str(int(meraki_snapshot_url_creation_time.microseconds))) # AppDController.Meraki_snap(int(meraki_snapshot_url_creation_time.microseconds), "Meraki_snap") # AppDController.Pull_Meraki() # AppDController.Upload_AWS() #except Exception as e: # return "error hit was " + str(e) elif "HELP" in str(message.text).upper() or "?" in message.text: return_messsage = """Welcome to the Cisco AppD Who the F**k are you bot!!!! The Bot will respond to the following commands: 'help' - displays this text '?' - displays this text 'Go' - Will initiate a snapshot of Imposter and Identity """ # Post the fact to the room where the request was received api.messages.create(room.id, text=return_messsage) # Post a message to the tracking/debug room # api.messages.create(TRACKING_ROOM_ID, text=str(room.id + " - " + # webhook_obj.data.personEmail + " - " + # message.text)) return 'OK' else: lookup_go = re.split(' |\n', str(message.text).upper()) for go in lookup_go: normalised_sku = go.upper().strip(" ").strip("\n") if normalised_sku == "GO" or \ normalised_sku == "go" : camsnapshots = snapshot.snapshot() newmessage=camsnapshots[0] print(camsnapshots[0]) recognition = AppDynamicsHackathon2019_AWS.get_images_from_URL(camsnapshots[0], camsnapshots[1]) api.messages.create(room.id, text=str(recognition)) continue return 'OK'
def teamsWebHook(): global roomFollows global roomLanguages global roomFilters global roomVoices format = "text" json_data = request.json # Pass the JSON data so that it can get parsed by the Webhook class webhook_obj = Webhook(json_data) # Obtain information about the request data such as room, message, the person it came from # and person's email address. room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) person = teams_api.people.get(message.personId) email = person.emails[0] group = room.type == "group" if room.id not in roomLanguages: roomLanguages[room.id] = ["en", "English"] roomFilters[room.id] = [] roomFollows[room.id] = {} roomVoices[room.id] = True roomWolfram[room.id] = True has_translation = False has_voice = False new_follow = False text = message.text if text: # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = teams_api.people.me() print(u"Message sent by {} of type {} from room {}.\n Content is {}". format(person.displayName, room.type, room.id, text)) if message.personId == me.id: return 'OK' else: #Start the translation process ascii = text.encode('ascii', 'ignore') lower = ascii.lower() output = "" if lower.startswith("!setlanguage"): #Attempt to set the language newLang = ascii.split() if len(newLang) > 1: confidence, detectedLang, shortcode = get_shortcode_of( newLang[1]) if confidence == 100: roomLanguages[room.id] = [shortcode, detectedLang] output = "Language set to {}".format(newLang[1]) elif confidence > 70: roomLanguages[room.id] = [shortcode, detectedLang] output = "Language set to {} (Auto-recognised with confidence level {})".format( detectedLang, confidence) else: output = "We did not understand {}, did you mean {}?".format( newLang[1], detectedLang) else: output = "No language was provided for !setlanguage" elif lower.startswith("!notranslate"): #Add word to ignored list words = "" for word in lower.split(): if word != "!notranslate" and word not in noTranslate: roomFilters[room.id].append(word) output = "The following words are now not translated: {}".format( roomFilters[room.id]) elif lower.startswith("!dotranslate"): words = "" for word in lower.split(): if word != "!notranslate" and word in roomFilters[room.id]: roomFilters[room.id].remove(word) output = "The following words are now not translated: {}".format( roomFilters[room.id]) elif lower.startswith("!help"): output = "The following commands are valid:\n" output += "!help - List this help command\n" output += "!notranslate word1 word2 .. - Do not translate these words\n" output += "!dotranslate word1 word2 .. - Remove these words from the no translate list\n" output += "!setlanguage language - Set the translation target to the language. Minor spelling errors are corrected automatically\n" output += "!follow language - Follow a group chat in a specific language (excludes your messages).\n" output += "!voice - Allow attaching of voice pronounciation for supported languages.\n" output += "!novoice - Disable attaching of voice pronounciation for supported languages.\n" output += "!nowolfram - Disable attempted parsing of messages by wolfram API" output += "!wolfram - Enable attempted parsing of messages by wolfram API" elif lower.startswith("!follow"): if not group: output = "You cannot follow a direct chat!" else: newLang = ascii.split() if len(newLang) > 1: confidence, detectedLang, shortcode = get_shortcode_of( newLang[1]) if confidence == 100: roomFollows[room.id][message.personId] = [ shortcode, detectedLang ] output = "{} is now following {} in {}".format( person.displayName, room.title, newLang[1]) new_follow = True elif confidence > 70: roomFollows[room.id][message.personId] = [ shortcode, detectedLang ] output = "{} is now following {} in {} (Auto-recognised with confidence level {})".format( person.displayName, room.title, newLang[1], confidence) new_follow = True else: output = "We did not understand {}, did you mean {}?".format( newLang[1], detectedLang) print(output + " in room " + room.title) print(roomFollows[room.id]) else: output = "No language was provided for !follow" elif lower.startswith("!voice"): if roomVoices[room.id]: output = "Voice attachments are already enabled!" else: roomVoices[room.id] = True output = "Voice attachments are enabled for supported languages." elif lower.startswith("!novoice"): if not roomVoices[room.id]: output = "Voice attachments are already disabled!" else: roomVoices[room.id] = False output = "Voice attachments are disabled for this room" elif lower.startswith("!wolfram"): if roomWolfram[room.id]: output = "Wolfram parsing is already enabled!" else: roomWolfram[room.id] = True output = "Wolfram parsing is enabled for supported languages." elif lower.startswith("!nowolfram"): if not roomWolfram[room.id]: output = "Wolfram parsing is already disabled!" else: roomWolfram[room.id] = False output = "Wolfram parsing is disabled for this room" elif lower.startswith("!summarize"): msgs = list(teams_api.messages.list(room.id)) string = [] for msg in msgs: botId = "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8xZWVjYmVkMS1mZTNmLTQ1MDctOTk0Yy1mNGEyOThmYzZlYWM" if type( msg.text ) is unicode and msg.personId != botId and shouldSend( msg.text) and not stringInOurList( msg.text, string): #pprint(vars(msg)) string.append(msg.text) stringstring = '\n'.join(Set(string)) print(Set(string)) #print(stringstring) print("SUMMARIZER BELOW") text = summarizer.summarize(stringstring, ratio=0.20) teams_api.messages.create( room.id, text= u"The following is a suggested summarization of 20% of the chat content:\n{}" .format(text)) print(text) else: #Translate normally result = translate_client.detect_language(text) language = result['language'] target = roomLanguages[room.id][0] fullTarget = roomLanguages[room.id][1] print("Detected is " + language) print("Target is " + target) print("Confidence {}".format(result['confidence'])) has_result = False if roomWolfram[room.id]: wolfram_result = "" english = "" attempt_again = language != "en" and language != "und" and result[ 'confidence'] > 0.7 if attempt_again: english = translate_client.translate( text, "en", format_="text")['translatedText'] if message.personId not in wolframConvos: wolfram_result = readwolfram.ask(text) if "result" in wolfram_result: has_result = True wolframConvos[message.personId] = wolfram_result elif attempt_again: wolfram_result = readwolfram.ask(english) if "result" in wolfram_result: has_result = True wolframConvos[ message.personId] = wolfram_result else: wolfram_result = readwolfram.askContinuingConvo( text, wolframConvos[message.personId]) if "result" not in wolfram_result: del wolframConvos[message.personId] # Try again wolfram_result = readwolfram.ask(text) if "result" in wolfram_result: has_result = True wolframConvos[ message.personId] = wolfram_result elif attempt_again: wolfram_result = readwolfram.ask(english) if "result" in wolfram_result: has_result = True wolframConvos[ message.personId] = wolfram_result else: # Refresh the answer wolframConvos[message.personId] = wolfram_result has_result = True print(wolfram_result) if has_result: if attempt_again: back_translated = translate_client.translate( wolframConvos[message.personId]["result"], language, format_="text")['translatedText'] teams_api.messages.create( room.id, text= u"Wolfram Alpha suggests the following:\n{}\nOriginal:({})" .format( back_translated, wolframConvos[message.personId]["result"])) else: teams_api.messages.create( room.id, text=u"Wolfram Alpha suggests the following:\n{}" .format( wolframConvos[message.personId]["result"])) if language != "und" and result['confidence'] > 0.7: has_translation = True elif not has_result: output = u"Sorry, could not recognise the language of {} with enough certainty. Maybe it is too short?".format( text) if language != target and has_translation: print(u"Language of {} detected as {} with confidence {}". format(text, result['language'], result['confidence'])) input = "" for word in text.split(): if word.lower() in roomFilters[room.id]: input += "<span translate=\"no\">" + word + "</span> " format = "html" else: input += word + " " output = translate_client.translate( input, target, format_=format)['translatedText'] if format == "html": regex = re.compile( "<span translate ?= ?\"no\"> ?(\w+) ?<\/ ?span>") output = regex.sub("\\1", output) if roomVoices[room.id] and get_voice_of(target): #Get the voice file voice_lang, voice_type, voice_gender = get_voice_of( target) voice_input = texttospeech.types.SynthesisInput( text=output) voice = texttospeech.types.VoiceSelectionParams( language_code=voice_lang, name=voice_type) audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.MP3 ) response = voice_client.synthesize_speech( voice_input, voice, audio_config) # The response's audio_content is binary. with open('output.mp3', 'wb') as out: out.write(response.audio_content) has_voice = True output = u"{}'s message in {} is {}".format( person.displayName, fullTarget, output) print(output) if output != "": teams_api.messages.create(room.id, text=output) if has_voice: #Attach the voice file teams_api.messages.create( room.id, text="Language is compatible, play file for speech output", files=["output.mp3"]) if has_translation: # Now notify the followers print(roomFollows[room.id]) for key, value in roomFollows[room.id].iteritems(): format = "text" if language != value[0] and message.personId != key: target = value[0] input = "" for word in text.split(): if word.lower() in roomFilters[room.id]: input += "<span translate=\"no\">" + word + "</span> " format = "html" else: input += word + " " output = translate_client.translate( input, target, format_=format)['translatedText'] if format == "html": regex = re.compile( "<span translate ?= ?\"no\"> ?(\w+) ?<\/ ?span>" ) output = regex.sub("\\1", output) # Write to user here output = u"{}'s message from {} in {} is {}".format( person.displayName, room.title, fullTarget, output) teams_api.messages.create(toPersonId=key, text="YEET" + output) print("Message should be sent here") if roomVoices[room.id] and get_voice_of(target): #Get the voice file voice_lang, voice_type, voice_gender = get_voice_of( target) voice_input = texttospeech.types.SynthesisInput( text=output) voice = texttospeech.types.VoiceSelectionParams( language_code=voice_lang, name=voice_type) audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums. AudioEncoding.MP3) response = voice_client.synthesize_speech( voice_input, voice, audio_config) # The response's audio_content is binary. with open('output.mp3', 'wb') as out: out.write(response.audio_content) #Attach the voice file teams_api.messages.create( toPersonId=key, text= "Language is compatible, play file for speech output", files=["output.mp3"]) return 'OK'
def index(): if request.method == 'GET': return 'OK. This is the break_out_bot!' if request.method == 'POST': webhook_obj = Webhook(request.get_json()) room = wbxapi.rooms.get(webhook_obj.data.roomId) message = wbxapi.messages.get(webhook_obj.data.id) me = wbxapi.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. logger.info('Not responding to self.') return 'OK. Not responding to self.' try: team = wbxapi.teams.get(room.teamId) except(TypeError) as e: logger.error(f'Error: {e}') wbxapi.messages.create( room.id, markdown="Oh no! 😵 It seems this space isn't part of a **team**. " "I can only work within a **team**. " ) if team: command_list = message.text.split(' ') if 'help' in command_list[1]: wbxapi.messages.create( room.id, markdown=f"Hello! 👋 I'm B.O.B the break_out_bot! Currently, I'm aware of the team **{team.name}**. \n" "\nCommands available:\n" "- **help**: Shows this help text.\n" "- **breakout n**: Create breakout spaces and add _n_ number of team members to it.\n" "- **cleanup**: Archive any breakout spaces that were created by me." ) elif 'breakout' in command_list[1]: breakout_size = int(command_list[2]) team_memberships = wbxapi.team_memberships.list(team.id) team_members = [member for member in team_memberships if not member.personId == me.id] team_member_count = len(team_members) team_room_number = int(team_member_count/breakout_size) team_member_names = [member.personDisplayName for member in team_members] wbxapi.messages.create( room.id, markdown=f"Creating breakout teams for: {', '.join(team_member_names)}" ) for i in range(team_room_number+1): if len(team_members) > 0: new_room = wbxapi.rooms.create(f"BOB_Breakout Space #{i+1}", teamId=team.id) logger.info(f'Created room {new_room.title}.') wbxapi.messages.create( room.id, markdown=f"Created breakout space {new_room.title}." ) wbxapi.messages.create( new_room.id, markdown=f"Welcome to {new_room.title}!" ) if len(team_members) < breakout_size: for m in team_members: add_member_to_room(m, new_room) else: for i in range(breakout_size): m = rm_member_from_list(team_members) add_member_to_room(m, new_room) # Remove bot from new room, but disables cleanup. # bot_membership = wbxapi.memberships.list(roomId=new_room.id, personId=me.id) # for bot in bot_membership: # wbxapi.memberships.delete(bot.id) elif 'cleanup' in command_list[1]: breakout_rooms = wbxapi.rooms.list(teamId=team.id) for r in breakout_rooms: if 'BOB_Breakout' in r.title: wbxapi.messages.create( room.id, markdown=f"Cleaning up breakout space {r.title}." ) wbxapi.rooms.delete(r.id) wbxapi.messages.create( room.id, markdown="Cleaning up finished! 🥳." ) return 'OK'
def teamswebhook(): # Only execute this section of code when a POST request is sent, as a POST indicates when a message # has been sent and therefore needs processing. if request.method == 'POST': json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Pass the JSON data so that it can get parsed by the Webhook class webhook_obj = Webhook(json_data) # Obtain information about the request data such as room, message, the person it came from # and person's email address. room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) person = teams_api.people.get(message.personId) email = person.emails[0] print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = teams_api.people.me() if message.personId == me.id: return 'OK' else: pass if message.text[:8] == "@answer ": query_string = message.text[7:] # print(query_string) response = query(query_string) # print(str(response).encode('utf-8')) # print(str(response.abstract_url).encode('utf-8')) url = response.abstract_url # print(str(response.related_topics[0].url).encode('utf-8')) # teams_api.messages.create(room.id, text=response.related_topics[0].text) if response.abstract_text: teams_api.messages.create(room.id, text=response.abstract_text) else: teams_api.messages.create(room.id, text=response.related_topics[0].text) teams_api.messages.create(room.id, text='Read more: {}'.format(url)) elif message.text[:10] == "@calendar ": if message.text == "@calendar tomorrow": events = CalendarQuery.tomorrow(ci) print_events(webhook_obj, events) elif re.match('@calendar\snext\s\d+', message.text) is not None: num_events = int(message.text.rsplit(' ', 1)[1]) events = CalendarQuery.next_events(ci, num_events) print_events(webhook_obj, events) elif message.text == "@calendar next": events = CalendarQuery.next_events(ci, 10) print_events(webhook_obj, events) elif message.text == "@calendar today": events = CalendarQuery.today(ci) print_events(webhook_obj, events) elif message.text[:13] == "@availability": if message.text == "@availability": best_dates, people_that_agree = parser.get_best_date() if not best_dates: teams_api.messages.create(room.id, text='There is no availability information available.') else: teams_api.messages.create(room.id, text='The best day for a meeting is: {}'.format(str(best_dates[0]))) if people_that_agree: teams_api.messages.create(room.id, text='The following teammates confirmed they are available: {}'.format(', '.join(list(set(people_that_agree))))) if message.text == "@availability reset": parser.reset_date() if re.match('@availability\screate\s-start\s\d+\s-end\s\d+', message.text) is not None: parts = message.text.split(' ') start_time = datetime.datetime.combine(parser.get_best_date()[0][0], datetime.datetime.min.time()) + datetime.timedelta(hours = int(parts[3])) end_time = datetime.datetime.combine(parser.get_best_date()[0][0], datetime.datetime.min.time()) + datetime.timedelta(hours = int(parts[5])) existing_events = ci.get_events(start_time=start_time, end_time=end_time) print(start_time) print(end_time) if existing_events: teams_api.messages.create(room.id, text='An event already exists at that time.') print_events(webhook_obj,existing_events) else: ci.add_event(summary = "Meeting by @calendar_bot", start_time = start_time, end_time = end_time) teams_api.messages.create(room.id, text='Meeting setup succesful.') else: print(parser.extract(message.text)) parser.manage_text(message.text) print(parser.get_best_date())
def teamswebhook(): if request.method == 'POST': json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") webhook_obj = Webhook(json_data) # Details of the message created room = teams_api.rooms.get(webhook_obj.data.roomId) message = teams_api.messages.get(webhook_obj.data.id) person = teams_api.people.get(message.personId) email = person.emails[0] print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = teams_api.people.me() if message.personId == me.id: return 'OK' else: print(message) if message.text.lower()[:3] == "new": dest = "board.bd" board = parser.Board(dest=dest) chess_response = str(board) teams_api.messages.create(roomId=room.id, text=chess_response) teams_api.messages.create( toPersonEmail=message.text.lower()[4:], text=str(person.displayName + " invited you to play Chess")) opponent_email = message.text.lower()[4:] board.save(dest) teams_api.messages.create(toPersonEmail=opponent_email, text=chess_response) with open('players.json', 'w') as f: print("\nSaving...\n") json.dump([{ str(person.emails[0]): { 'board': str(dest), 'opponent_email': opponent_email }, opponent_email: { 'board': str(dest), 'opponent_email': str(person.emails[0]) } }, { 'turn': person.emails[0] }], f) else: with open('players.json', 'r') as f: status_dict = json.loads(f.read()) game_dict = status_dict[0] turn_email = status_dict[1]['turn'] dest = game_dict[person.emails[0]]['board'] board = parser.load_board(dest) opponent_email = game_dict[ person.emails[0]]['opponent_email'] if turn_email != person.emails[0]: chess_response = "It is not your turn." teams_api.messages.create(toPersonEmail=person.emails[0], text=chess_response) print(turn_email) return 1 if message.text == "?": s = str(board.legal_moves).split('(')[1].split('(') chess_response = str(s)[2:-4] teams_api.messages.create(toPersonEmail=person.emails[0], text=chess_response) elif message.text.lower() == "show": chess_response = str(board) teams_api.messages.create(toPersonEmail=person.emails[0], text=chess_response) else: try: board.push_san(message.text) chess_response = "```\n" + str(board) + "\n```" with open('players.json', 'w') as f: json.dump( [game_dict, { 'turn': str(opponent_email) }], f) if board.is_checkmate(): chess_response = str(person.displayName) + " wins!" if board.is_stalemate(): chess_response = "Stalemate!" except (Exception) as e: chess_response = "Illegal move!" teams_api.messages.create( toPersonEmail=person.emails[0], text=chess_response) return 1 teams_api.messages.create(toPersonEmail=person.emails[0], markdown=chess_response) teams_api.messages.create(toPersonEmail=opponent_email, markdown=chess_response) board.save(board.dest) else: print('received none post request, not handled!')