def webhook_delivered(request, webhook_id): print("In webhook_delivered") """ Webhook function to notify user about update in component """ urllib.parse.unquote(request.body.decode("utf-8")) params_dict = urllib.parse.parse_qsl(request.body) params = dict(params_dict) #Extracting necessary data recipient = params[b'recipient'].decode('utf-8') # Fetching yellowant object try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Mail delivered to " + str(recipient) attachment = MessageAttachmentsClass() attachment.title = "Mail Stats upto last 1 month" button_get_components = MessageButtonsClass() button_get_components.name = "1" button_get_components.value = "1" button_get_components.text = "Get all stats" button_get_components.command = { "service_application": service_application, "function_name": 'get_stats', "data": {} } attachment.attach_button(button_get_components) webhook_message.data = {"recipient_email_id": recipient} webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt( access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="notify_delivered", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def update_incident(request,webhook_id): print("In update_incident") """ Webhook function to notify user about update in incident """ # Extracting necessary data data = (request.body.decode('utf-8')) response_json = json.loads(data) page_id = response_json['page']['id'] unsubscribe = response_json['meta']['unsubscribe'] incident_id = response_json['incident']['id'] name = response_json['incident']['name'] try: # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Updates in incident with Id : " + str(incident_id) + "\nName : " + str(name) attachment = MessageAttachmentsClass() attachment.title = "Incident operations" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get all incidents" button_get_incidents.command = { "service_application": service_application, "function_name": 'all_incidents', "data": { 'page_id': page_id } } attachment.attach_button(button_get_incidents) webhook_message.data = {"page_id": page_id} webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="incident_updates_webhook", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def add_new_pipeline(request, webhook_id): """ Webhook function to notify user about newly added pipeline """ data = request.body data_string = data.decode('utf-8') data_json = json.loads(data_string) name = data_json["current"]['name'] add_time = data_json["current"]['add_time'] url_tile = data_json["current"]['url_title'] order = data_json["current"]['order_nr'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "New pipeline created." + "\n" + "The pipeline name : " + str( name) attachment = MessageAttachmentsClass() button_get_pipeline = MessageButtonsClass() button_get_pipeline.name = "1" button_get_pipeline.value = "1" button_get_pipeline.text = "Get all pipelines" button_get_pipeline.command = { "service_application": service_application, "function_name": 'list_pipelines', "data": { 'data': "test", } } attachment.attach_button(button_get_pipeline) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Add Time": add_time, "Url title": url_tile, "Name": name, "Order": order, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_pipeline", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def run(self): """Method which runs when the thread is started""" global GROUP_NAME, VM_NAME, USERNAME, PASSWORD message = MessageClass() credentials, subscription_id = get_credentials(self.user_integration) compute_client = ComputeManagementClient(credentials, subscription_id) network_client = NetworkManagementClient(credentials, subscription_id) GROUP_NAME = self.args.get("Resource-Group") VM_NAME = self.args.get("VM-Name") NIC_NAME = self.args.get("nic_name") IP_CONFIG_NAME = self.args.get("ipconfig_name") USERNAME = self.args.get("username") PASSWORD = self.args.get("password") VNET_NAME = self.args.get("vnet_name") SUBNET_NAME = self.args.get("subnet_name") LOCATION = self.args.get("location") try: # Create a NIC nic = create_nic(network_client, VNET_NAME, SUBNET_NAME, IP_CONFIG_NAME, NIC_NAME) ############# # VM Sample # ############# # Create Linux VM print('\nCreating Linux Virtual Machine') vm_parameters = create_vm_parameters(nic.id, VM_REFERENCE['linux'], VM_NAME, USERNAME, PASSWORD, LOCATION) async_vm_creation = compute_client.virtual_machines.create_or_update( GROUP_NAME, VM_NAME, vm_parameters) # async_vm_creation.wait() message.message_text = "You are Virtual Machine is being created" except CloudError: print('A VM operation failed:', traceback.format_exc(), sep='\n') message.message_text = "There was an error.Please try again" else: webhook_message = MessageClass() webhook_message.message_text = "VM created successfully" attachment = MessageAttachmentsClass() attachment.title = VM_NAME webhook_message.attach(attachment) yellowant_user_integration_object = YellowAnt( access_token=self.user_integration.yellowant_integration_token) yellowant_user_integration_object.create_webhook_message( requester_application=self.user_integration. yellowant_integration_id, webhook_name="start_vm_webhook", **webhook_message.get_dict()) print('All example operations completed successfully!')
def list_all(args, user_integration): #print("LIST") bxc = BOX_Credentials.objects.get(user_integration_id=user_integration) ACCESS_TOKEN = bxc.BOX_ACCESS_TOKEN #print(ACCESS_TOKEN) REFRESH_TOKEN = bxc.BOX_REFRESH_TOKEN #print(REFRESH_TOKEN+" refreshtoken") # Log the token we're using & starting call logging.info('Using Refresh Token: %s' % REFRESH_TOKEN) # Get new access & refresh tokens #print("logged") getTokens = requests.post(oauth2URL, data={ 'grant_type': 'refresh_token', 'refresh_token': REFRESH_TOKEN, 'client_id': clientId, 'client_secret': clientSecret }) #print("GOT TOKENS") # If the above gives a 4XX or 5XX error #getTokens.raise_for_status() # Get the JSON from the above newTokens = getTokens.json() #print("GOT NEW TOKEN") # Get the new access token, valid for 60 minutes accessToken = newTokens['access_token'] refreshToken = newTokens['refresh_token'] # print("New accessToken " + accessToken) # print("New refreshToken " + refreshToken) bxc.BOX_REFRESH_TOKEN = refreshToken bxc.BOX_ACCESS_TOKEN = accessToken bxc.save() # Get the new access token, valid for 60 minutes CLIENT_ID = settings.CLIENT_ID CLIENT_SECRET = settings.CLIENT_SECRET oauth2 = OAuth2(CLIENT_ID, CLIENT_SECRET, access_token=accessToken) #print("listing...") client = Client(oauth2, LoggingNetwork()) items = client.folder(folder_id='0').get_items(limit=1000, offset=0) #print("List of all files and folders\n") attachment = MessageAttachmentsClass() m = MessageClass() x = '' for item in items: field = AttachmentFieldsClass() field.title = item['name'] field.value = item['id'] #print("Name: "+item['name']+" ID: "+item['id']) x = x + "Name: " + item['name'] + " ID: " + item['id'] + "\n" attachment.attach_field(field) m.attach(attachment) return m
def startGame(args,user_integration): object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id) board = chess.Board() object.board_state = INITIAL_BOARD + INITIAL_BOARD_REST object.save() print("inside start game") print(user_integration.id) m = MessageClass() color = args['Color'] # if color == "White": # MOVE_FLAG = 0 # else: # MOVE_FLAG = 1 # # #board = chess.Board() m.message_text = "You chose " + color attachment = MessageAttachmentsClass() print(color + " to move") if (color=="Black"): m = playComputer(args,user_integration) return m print(IMAGE_URL + INITIAL_BOARD) attachment.image_url = IMAGE_URL + INITIAL_BOARD field1 = AttachmentFieldsClass() field1.title = "Move" field1.value = color + " to move" attachment.attach_field(field1) button = MessageButtonsClass() button.text = "Make move" button.value = "Make move" button.name = "Make move" button.command = { "service_application": str(user_integration.yellowant_integration_id), "function_name": "makemove", "inputs": ["move"], "data": {"move": "testing"}, } attachment.attach_button(button) button1 = MessageButtonsClass() button1.text = "Play Computer" button1.value = "Play Computer" button1.name = "Play Computer" button1.command = {"service_application": str(user_integration.yellowant_integration_id), "function_name": "playcomputer", "data": {"move": "testing"}, } attachment.attach_button(button1) m.attach(attachment) #m.image_url = "http://www.fen-to-image.com/image/rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" return m
def resolve_incidents(self, args): """ This resolves an incident or a list of incidents. """ message = MessageClass() url = settings.VICTOROPS_RESOLVE_INCIDENTS incident_list = args['Incident-Numbers'].split(',') body = { "userName": self.victor_ops_uid, "incidentNames": incident_list, "message": args['Resolution-Message'] } # PATCH request to victorops server response = requests.patch(url, headers=self.headers, data=json.dumps(body)) r_text = response.text if re.search(r'Already', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "The incident is already resolved" message.attach(attachment) return message.to_json() elif re.search(r'User not found', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "User not found" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() attachment.text = "Resolved!" message.attach(attachment) return message.to_json()
def ack_incidents(self, args): """ This acknowledges an incident or a list of incidents. """ message = MessageClass() url = settings.VICTOROPS_ACK_INCIDENTS # If there are multiple incidents they are split and added to an array incident_list = args['Incident-Numbers'].split(',') body = { "userName": self.victor_ops_uid, "incidentNames": incident_list, "message": args['Acknowledgement-Message'] } # PATCH request to victorops server response = requests.patch(url, headers=self.headers, data=json.dumps(body)) r_text = response.text if re.search(r'Already', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "The incident is already resolved" message.attach(attachment) return message.to_json() elif re.search(r'User not found', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "User not found" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() attachment.text = "Acknowledged!" message.attach(attachment) return message.to_json()
def user_details(args, user_integration): bxc = BOX_Credentials.objects.get(user_integration_id=user_integration) ACCESS_TOKEN = bxc.BOX_ACCESS_TOKEN REFRESH_TOKEN = bxc.BOX_REFRESH_TOKEN bxc = BOX_Credentials.objects.get(user_integration_id=user_integration) ACCESS_TOKEN = bxc.BOX_ACCESS_TOKEN #print(ACCESS_TOKEN) REFRESH_TOKEN = bxc.BOX_REFRESH_TOKEN #print(REFRESH_TOKEN + " refreshtoken") # Log the token we're using & starting call logging.info('Using Refresh Token: %s' % REFRESH_TOKEN) # Get new access & refresh tokens getTokens = requests.post(oauth2URL, data={ 'grant_type': 'refresh_token', 'refresh_token': REFRESH_TOKEN, 'client_id': clientId, 'client_secret': clientSecret }) # If the above gives a 4XX or 5XX error # getTokens.raise_for_status() # Get the JSON from the above newTokens = getTokens.json() # Get the new access token, valid for 60 minutes accessToken = newTokens['access_token'] refreshToken = newTokens['refresh_token'] #print("New accessToken " + accessToken) #print("New refreshToken " + refreshToken) bxc.BOX_REFRESH_TOKEN = refreshToken bxc.BOX_ACCESS_TOKEN = accessToken bxc.save() CLIENT_ID = settings.CLIENT_ID CLIENT_SECRET = settings.CLIENT_SECRET oauth2 = OAuth2(CLIENT_ID, CLIENT_SECRET, access_token=accessToken) attachment = MessageAttachmentsClass() client = Client(oauth2, LoggingNetwork()) items = client.folder(folder_id='0').get_items(limit=1000, offset=0) # print("List of all files and folders\n") m = MessageClass() #print("The users are:\n") my = client.user(user_id='me').get() field = AttachmentFieldsClass() field.title = "LOGIN ID" field.value = my['login'] attachment.attach_field(field) m.attach(attachment) #print(my) return m
def incident_resolved(request, webhook_id): # data = request.body data_string = data.decode('utf-8') data_json = json.loads(data_string) name = data_json['display_name'] entity_id = data_json['entity_id'] incident_number = data_json['incident_number'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Incident Resolved\n The entity ID : " + str(entity_id) \ + "\nThe Incident Number : " + str(incident_number) attachment = MessageAttachmentsClass() attachment.title = "Incident Operations" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get all incidents" button_get_incidents.command = { "service_application": service_application, "function_name": 'list_incidents', "data": { 'data': "test", } } attachment.attach_button(button_get_incidents) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Display Name": name, "Entity ID": entity_id, "Incident Number": incident_number, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_incident_resolved", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def create_incident(self, args): """ Creates a new incident given the incident body, description and the user to be paged for the incident A flag is also returned which denotes the success or the failure of incident creation which is used to provide a webhook. """ url = settings.VICTOROPS_CREATE_LIST_INCIDENT # Check if the user to be paged exists if self.test_get_user(args['Send-To']) == 0: message = MessageClass() attachment = MessageAttachmentsClass() attachment.text = "User not found!" message.attach(attachment) return message.to_json() else: body = { "summary": args['Incident-Summary'], "details": args['Incident-Body'], "userName": self.victor_ops_uid, "targets": [{ "type": "User", "slug": args['Send-To'] }] } response = requests.post(url, headers=self.headers, data=json.dumps(body)) message = MessageClass() attachment = MessageAttachmentsClass() attachment.text = "Incident created " r_text = response.text print(r_text) # A regex check to find the incident number of the new incident incident_nos = re.findall("\d+", r_text) # print(incident_nos) # print(incident_nos[0]) entity_id, vo_uuid = self.test_list_incidents(incident_nos[0]) field2 = AttachmentFieldsClass() field2.title = "Entity ID" field2.value = entity_id # print(field2.value) attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "VO_UUID" field3.value = vo_uuid attachment.attach_field(field3) message.attach(attachment) return message.to_json()
def get_domain(self, args): """ Get a single domain """ # API parameteres for getting account information auth = ("api", self.mailgun_access_token) # Consuming the API r = requests.get("https://api.mailgun.net/v3/domains/" + str(self.domain_name), auth=auth) print(self.mailgun_access_token) # Response check if r.status_code == requests.codes.ok: # Getting response in JSON print(json.loads(r.content.decode("utf-8"))) response = json.loads(r.content.decode("utf-8")) # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = "Domain details :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Domain :" field1.value = response['domain']["name"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "State :" field2.value = response['domain']["state"] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Created at :" field3.value = response['domain']['created_at'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Type :" field4.value = response['domain']['type'] attachment.attach_field(field4) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def search(self, args): input = args['input'] sp = spotipy.Spotify(auth=self.access_token) # artist_name = 'Ed Sheeran'.join(sys.argv[1:]) results = sp.search(q=input, limit=20) message = MessageClass() for i, t in enumerate(results['tracks']['items']): print(' ', i, t['name']) attachment = MessageAttachmentsClass() attachment.title = t['name'] message.attach(attachment) message.message_text = "The Search Results are" return message.to_json()
def deal_get(self, args): """For viewing the account details""" id = args['Id'] query = "api_key=" + self.API_Access_key + "&api_action=deal_get&api_output=json&id="+id url = (self.API_Access_URL + "/admin/api.php?" + query) print(self.API_Access_URL) print(url) response = requests.get(url) response_json = response.json() print(response_json) message = MessageClass() message.message_text = "Account Details:" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Title" field1.value = response_json['title'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Contact Email" field2.value = response_json['contact_email'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Deal Notes" field3.value = response_json['deal_notes'] attachment.attach_field(field3) message.attach(attachment) message.message_text = "The Details of Deal are:" return message.to_json()
def get_space_usage(self,args): print("In get_space_usage") headers = { 'Authorization': 'Bearer ' + str(self.dropbox_access_token), } # Consuming the API r = requests.post('https://api.dropboxapi.com/2/users/get_space_usage', headers=headers) # Response check if r.status_code == requests.codes.ok: # Fetching response in JSON response = r.content.decode("utf-8") response = json.loads(response) print(response) #Creating a message object from YA SDK message = MessageClass() message.message_text = "Space usage/allocation details :" attachment = MessageAttachmentsClass() used_gb = float(response['used']/1000000000) allocated_gb = float(response['allocation']['allocated']/1000000000) field1 = AttachmentFieldsClass() field1.title = "Used : " field1.value = str(Decimal(str(used_gb)).quantize(Decimal('.01'), rounding=ROUND_DOWN)) + " gb" attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Allocated : " field2.value = str(Decimal(str(allocated_gb)).quantize(Decimal('.01'), rounding=ROUND_DOWN)) + " gb" attachment.attach_field(field2) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def account_view(self,args): """For viewing the account details""" query = "api_key="+self.API_Access_key+"&api_action=account_view&api_output=json" url = (self.API_Access_URL + "/admin/api.php?"+ query) print(self.API_Access_URL) print(url) response = requests.get(url) response_json = response.json() message = MessageClass() message.message_text = "Account Details:" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Account" field1.value = response_json['account'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Email" field2.value = response_json['email'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Subscriber Limit" field3.value = response_json['subscriber_limit'] attachment.attach_field(field3) message.attach(attachment) return message.to_json()
def get_webhook(args, user_integration): object = UserIntegration.objects.get(id=user_integration.id) message = MessageClass() message.message_text = "Webhook ID" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Webhook ID" field1.value = object.webhook_id attachment.attach_field(field1) message.attach(attachment) return message
def Contact_Lists(self, args): # List all the contact lists(groups) the user has created. user_id = self.user_integration.yellowant_integration_id url = (settings.SM_API_BASE + settings.VIEW_CONTACTLISTS) try: message = MessageClass() message.message_text = "Contact list:\n" attachment = MessageAttachmentsClass() response = requests.get(url, headers=self.headers) response_json = response.json() data = response_json["data"] send_data = {\ 'list':[]\ } for i in range(len(data)): button1 = MessageButtonsClass() obj = data[i] name = obj["name"] id = obj["id"] send_data['list'].append({'id':id, 'name':name}) button1.text = name button1.value = name button1.name = name button1.command = { "service_application": user_id, "function_name": "ContactListDetails",\ "data":{\ "ContactListId":id\ } } attachment.attach_button(button1) message.attach(attachment) message.data = send_data # use inbuilt sdk method to_json to return message in a json format accepted by YA return message.to_json() except Exception as e: print("Exception occured is") print(str(e)) traceback.print_exc()
def campaign_status(self, args): """For viewing the account details""" message = MessageClass() id = args['Id'] status = args['status'] query = "api_key=" + self.API_Access_key + "&api_action=campaign_status&api_output=json&id="+id+"&status="+status url = (self.API_Access_URL + "/admin/api.php?" + query) response = requests.get(url) response_json = response.json() print(response_json) attachment = MessageAttachmentsClass() attachment.title = response_json['result_message'] message.attach(attachment) message.message_text = "" return message.to_json()
def settings(self, args): """ To get the number of functions in the Lambda """ region = args['Region'] message = MessageClass() aws_lambda = boto3.client(service_name='lambda', region_name=region, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=self.aws_access_key, aws_secret_access_key=self.aws_secret_token, aws_session_token=None, config=None) response = aws_lambda.get_account_settings() attachment = MessageAttachmentsClass() attachment.title = response['AccountUsage']['FunctionCount'] message.attach(attachment) message.message_text = "The Function Count is:" return message.to_json()
def get_logs(self, args): """To get the logs of the function""" region = args['Region'] function_name = args['FunctionName'] message = MessageClass() attachment = MessageAttachmentsClass() logstream = self.log_stream(args, function_name) # If Logstream is 0 then the Logs dosen't exist if logstream ==0: message.message_text = "There are no logs for that Function or the Log" \ " group name and the Function Name are mismatched" return message.to_json() aws_lambda = boto3.client(service_name='logs', region_name=region, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=self.aws_access_key, aws_secret_access_key=self.aws_secret_token, aws_session_token=None, config=None) log_group_name = "/aws/lambda/"+function_name # The following while loop is to find the i till which last log exists, for usage in get_log_events i = 0 strin="" while strin != "START": response = aws_lambda.get_log_events( logGroupName=log_group_name, logStreamName=logstream, limit=i+1 ) string=str(response['events'][0]['message']) i = i+1 strin = string[:5] # response = aws_lambda.get_log_events( logGroupName=log_group_name, logStreamName=logstream, limit=i ) events = [event['message'] for event in response['events']] for event in events: attachment.text = event message.attach(attachment) message.message_text = "The Event logs are:" return message.to_json()
def Contact_List_Details(self, args): # List all the details of the contact lists(groups) the user has created. contact_list_id = args["ContactListId"] url = "https://api.surveymonkey.com/v3/contact_lists/%s/contacts"%(contact_list_id) try: message = MessageClass() message.message_text = "Contacts details: \n" response = requests.get(url, headers=self.headers) response_json = response.json() data = response_json["data"] for i in range(len(data)): obj = data[i] attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "First name" field1.value = obj["first_name"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Last name" field2.value = obj["last_name"] attachment.attach_field(field2) field4 = AttachmentFieldsClass() field4.title = "Email" field4.value = obj["email"] attachment.attach_field(field4) field3 = AttachmentFieldsClass() field3.title = "Id" field3.value = obj["id"] attachment.attach_field(field3) message.attach(attachment) # use inbuilt sdk method to_json to return message in a json format accepted by YA return message.to_json() except Exception as e: print("Exception occured is") print(str(e)) traceback.print_exc()
def download_file(self, args): print("In download_file") # Fetching the arguments passed from slack path = args['path'] # API call parameters for creating a customer headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"path": path} # Consuming the API r = requests.post( 'https://api.dropboxapi.com/2/files/get_temporary_link', headers=headers, json=data) # Response check if (r.status_code == requests.codes.ok): # Getting the response response = r.content.decode("utf-8") response = json.loads(response) print(response) # Creating message using YA SDK message = MessageClass() message.message_text = "Temporary link to download :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "This link expires in 4 Hr :" field1.value = response['link'] attachment.attach_field(field1) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def home(self,args): try: l=self.api.home_timeline(count=30) except: m = MessageClass() m.message_text="can't get the feed!!!" return m.to_json() m=MessageClass() for status in l: st=MessageAttachmentsClass() st.title=status.author.screen_name+" "+str(status.id) tweet=AttachmentFieldsClass() tweet.value=status.text st.attach_field(tweet) m.attach(st) return m.to_json()
def get_all_shared_folders(self,args): print("In get_all_shared_folders") endpoint = "https://api.dropboxapi.com/2/sharing/list_folders" headers = { 'Authorization': 'Bearer ' + str(self.dropbox_access_token), 'Content-Type': 'application/json', } data = {"limit": 100,"actions": []} # Consuming the API r = requests.post(endpoint, headers=headers, json=data) # Response check if (r.status_code == requests.codes.ok): response = r.content.decode("utf-8") response = json.loads(response) print(response) #Creating message from YA SDK message = MessageClass() message.message_text = "All shared file details :" attachment = MessageAttachmentsClass() for i in range(0,len(response['entries'])): field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = response['entries'][i]['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Preview URL :" field2.value = response['entries'][i]['preview_url'] attachment.attach_field(field2) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def deal_delete(self, args): """For viewing the account details""" id = args['Id'] query = "api_key=" + self.API_Access_key + "&api_action=deal_delete&api_output=json&id="+id url = (self.API_Access_URL + "/admin/api.php?" + query) print(self.API_Access_URL) print(url) response = requests.get(url) response_json = response.json() print(response_json) message = MessageClass() attachment = MessageAttachmentsClass() attachment.title = response_json['result_message'] message.attach(attachment) message.message_text = "" return message.to_json()
def new_releases(self, args): # input = args['input'] sp = spotipy.Spotify(auth=self.access_token) # artist_name = 'Ed Sheeran'.join(sys.argv[1:]) results = sp.search(q=input, limit=20) message = MessageClass() response = sp.new_releases() albums = response['albums'] for i, item in enumerate(albums['items']): print(albums['offset'] + i, item['name']) attachment = MessageAttachmentsClass() attachment.title = item['name'] # if albums['next']: # response = sp.next(albums) message.attach(attachment) message.message_text = "The New Releases are:" return message.to_json()
def add_new_invoice(request, id): """ Webhook function to notify user about newly created invoice """ print(request.body) invoice_id = request.POST['ID'] contact_email = request.POST['Email'] total = request.POST['Total'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id # service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "New invoice added" attachment = MessageAttachmentsClass() field = AttachmentFieldsClass() field.title = "Invoice ID" field.value = invoice_id attachment.attach_field(field) field1 = AttachmentFieldsClass() field1.title = "Total" field1.value = total attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Contact Email" field2.value = contact_email attachment.attach_field(field2) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Invoice ID": invoice_id, "Total": total, "Contact Email": contact_email, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_invoice", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def download_file(self,args): print("In download_file") # Fetching the arguments passed from slack path = args['path'] # API call parameters for creating a customer headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"path": path} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/get_temporary_link', headers=headers, json=data) # Response check if (r.status_code == requests.codes.ok): # Getting the response response = r.content.decode("utf-8") response = json.loads(response) print(response) # Creating message using YA SDK message = MessageClass() message.message_text = "Temporary link to download :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "This link expires in 4 Hr :" field1.value = response['link'] attachment.attach_field(field1) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def item_attachment(item, user_integration, attachment=None): attachment = attachment or MessageAttachmentsClass() attachment.title = item.get("title") attachment.text = item.get("description") attachment.attach_field(AttachmentFieldsClass("ID", 1, item.get("id"))) attachment.attach_button(update_item_button(item, user_integration)) return attachment
def get_ips(self, args): """ Get a list of all IPs """ # API parameteres for getting account information auth = ("api", self.mailgun_access_token) # Consuming the API r = requests.get("https://api.mailgun.net/v3/ips", params={"dedicated": "true"}, auth=auth) # NOT USED here sample_response = { "items": ["192.161.0.1", "192.168.0.2"], "total_count": 2 } # Response check if r.status_code == requests.codes.ok: # Getting response in JSON print(json.loads(r.content.decode("utf-8"))) response = json.loads(r.content.decode("utf-8")) # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = "List of IPs :" attachment = MessageAttachmentsClass() for i in range(0, len(response['items'])): field1 = AttachmentFieldsClass() field1.title = "Click :" field1.value = response['items'][i] attachment.attach_field(field1) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def list_view(self, args): """For viewing the account details""" id = args['Id'] query = "api_key=" + self.API_Access_key + "&api_action=list_view&api_output=json&id="+id url = (self.API_Access_URL + "/admin/api.php?" + query) print(self.API_Access_URL) print(url) response = requests.get(url) response_json = response.json() print(response_json) message = MessageClass() message.message_text = "Account Details:" attachment = MessageAttachmentsClass() try: field1 = AttachmentFieldsClass() field1.title = "User ID" field1.value = response_json['userid'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Name" field2.value = response_json['name'] attachment.attach_field(field2) attachment = MessageAttachmentsClass() button2 = MessageButtonsClass() button2.text = "Delete List" button2.value = "Delete List" button2.name = "Delete List" button2.command = {"service_application": self.yellowant_integration_id, "function_name": "list-delete", "data": {"Id": args['Id']}} attachment.attach_button(button2) message.attach(attachment) message.message_text = "The Details of the list are:" except: message.message_text = "The Given list Does not exist" return message.to_json()
def create_invoice(self, args): """ This function is used to create an invoice given the org ID, customer ID,date, Item ID and the quantity """ org_id = args['organization'] customer_id = args['customer_id'] date = args['date'] item_id = args['item_id'] quantity = args['quantity'] # org_id = "669665442" # customer_id = "1392605000000069001" # date = "2018-07-27" # item_id = "1392605000000072001" # quantity = 1 headers = { "Authorization": "Zoho-oauthtoken" + " " + self.zohoinvoice_access_token, "X-com-zoho-invoice-organizationid": org_id, "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" } url = settings.ZOHO_INVOICE_URL payload = { "customer_id": customer_id, "date": date, "line_items": [{ "item_id": item_id, "quantity": quantity, }], } response = requests.post(url, headers=headers, data={"JSONString": json.dumps(payload)}) response_json = response.json() print(response) print(response_json) message = MessageClass() if response.status_code == 400: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Error" field1.value = response_json['message'] attachment.attach_field(field1) message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() attachment.text = "Invoice created" message.attach(attachment) return message.to_json()
def get_account_info(self,args): print("In get_company_info") endpoint = "https://api.dropboxapi.com/2/users/get_account" # API parameteres for getting account information headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"account_id": str(self.account_id)} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/users/get_account', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: # Getting response in JSON response = r.content.decode("utf-8") response = json.loads(response) # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = "User Account Details :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = response["name"]["display_name"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "E-mail :" field2.value = response["email"] attachment.attach_field(field2) attachment.image_url = response["profile_photo_url"] message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_all_folders(self,args): print("In get_all_folders") # API call parameters for getting all customers path = args['path'] headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } if path == '/': path = "" data = {"path": path, "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/list_folder', headers=headers, json=data) # Error check if r.status_code == requests.codes.ok: # Getting response in JSON format response = r.content.decode("utf-8") response = json.loads(response) print(response) message = MessageClass() message.message_text = "List files and folders :" attachment = MessageAttachmentsClass() for i in range(0, len(response['entries'])): field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = response['entries'][i]['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Type :" field2.value = response['entries'][i]['.tag'] attachment.attach_field(field2) attachment2 = MessageAttachmentsClass() if response['has_more'] == True: button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get more files and folders" button.command = { "service_application": str(self.user_integration.yellowant_integration_id), "function_name": 'get_more_folders', "data": {"cursor": response['cursor']} } attachment2.attach_button(button) message.attach(attachment) message.attach(attachment2) return message.to_json() message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def webhook(request, hash_str=""): '''Respond to the webhook verification (GET request) by echoing back the challenge parameter.''' print("Inside webhook") if request.method == "GET": print("Inside webhook validation") challenge = request.GET.get('challenge',None) if challenge != None: return HttpResponse(challenge,status=200) else: return HttpResponse(status=400) else: print("In notifications") webhook_id = hash_str data = (request.body.decode('utf-8')) response_json = json.loads(data) print(response_json) data = { "users": [], "accounts": [] } try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "File/Folder updated !" attachment = MessageAttachmentsClass() attachment.title = "Updated file/folder details :" for i in range(0,len(response_json['list_folder']['accounts'])): field1 = AttachmentFieldsClass() field1.title = "Id : " field1.value = response_json['list_folder']['accounts'][i] data["accounts"].append(response_json['list_folder']['accounts'][i]) attachment.attach_field(field1) attachment2 = MessageAttachmentsClass() attachment2.title = "User update details :" for i in range(0, len(response_json['delta']['users'])): field2 = AttachmentFieldsClass() field2.title = "Id : " field2.value = response_json['delta']['users'][i] data["users"].append(response_json['delta']['users'][i]) attachment2.attach_field(field2) button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get all files and folders " button.command = { "service_application": service_application, "function_name": 'get_all_folders', "data" : {"path": "", "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True} } attachment.attach_button(button) webhook_message.attach(attachment) webhook_message.attach(attachment2) #print(integration_id) print("-----------") print(data) print("------------") webhook_message.data = data # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="files_folders_update", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def get_shared_links(self,args): print("In get_shared_links") flag = False # Arguments passed from slack # For the optional argument try: path = args['path'] flag = True except: flag = False headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } endpoint = 'https://api.dropboxapi.com/2/sharing/list_shared_links' if flag == True: data = {"path": path} else: data = {} # Consuming the API r = requests.post(endpoint, headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: # Getting response in JSON response = r.content.decode("utf-8") response = json.loads(response) print(response) links = response['links'] message = MessageClass() message.message_text = "List of all shared links :" attachment = MessageAttachmentsClass() for i in range(0,len(links)): try: field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = links[i]['name'] attachment.attach_field(field1) except KeyError : 'name' # field2 = AttachmentFieldsClass() # field2.title = "Type :" # field2.value = links[i]['.tag'] # attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Preview URL :" field3.value = links[i]['url'] attachment.attach_field(field3) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_more_folders(self,args): print("In get_more_folders") # Fetching arguments passed from Slack cursor = args['cursor'] # API call parameters for getting customer details headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"cursor": cursor} re = requests.post('https://api.dropboxapi.com/2/files/list_folder/continue', headers=headers, json=data) if re.status_code == requests.codes.ok: res = re.content.decode("utf-8") res = json.loads(res) print("----") print(res) message = MessageClass() message.message_text = "More files and folders :" attachment = MessageAttachmentsClass() for i in range(0, len(res['entries'])): field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = res['entries'][i]['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Type :" field2.value = res['entries'][i]['.tag'] attachment.attach_field(field2) attachment2 = MessageAttachmentsClass() if res['has_more'] == True: button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get more files and folders" button.command = { "service_application": str(self.user_integration.yellowant_integration_id), "function_name": 'get_more_folders', "data": {"cursor": res['cursor']} } attachment2.attach_button(button) message.attach(attachment) message.attach(attachment2) return message.to_json() message.attach(attachment) return message.to_json() else: m = MessageClass() print(re.content.decode("utf-8")) d = re.content.decode("utf-8") m.message_text = "{0}: {1}".format(re.status_code, re.text) return m.to_json()
def search(self,args): print("In search") print(args) path = args['path'] query = args['search'] headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } if path == '/': path = "" data = {"path": path,"query": query,"start": 0,"max_results": 100,"mode": "filename"} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/search', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: print("---------------") # Getting response in JSON r = r.content.decode("utf-8") response = json.loads(r) print(response) # Creating message using YA SDK message = MessageClass() if len(response['matches']) == 0: message.message_text = "No matches !\nPlease search again." return message.to_json() message.message_text = "Matches :" attachment = MessageAttachmentsClass() for i in range(0, len(response['matches'])): field1 = AttachmentFieldsClass() field1.title = "Path:" field1.value = response['matches'][i]['metadata']['path_display'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Name :" field2.value = response['matches'][i]['metadata']['name'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Type :" field3.value = response['matches'][i]['metadata']['.tag'] attachment.attach_field(field3) message.attach(attachment) return message.to_json() else: print("Error") m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def share_folder(self, args): print("In share_folder") # Arguments from slack path = args["path"] member_policy = args['member_policy'] shared_link_policy = args['shared_link_policy'] if member_policy != 'anyone' and member_policy != "team": m = MessageClass() m.message_text = "Invalid value in member_policy argument" return m.to_json() if shared_link_policy != 'anyone' and shared_link_policy != "team": m = MessageClass() m.message_text = "Invalid value in shared_link_policy argument" return m.to_json() # API call parameters for getting all customer ids headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"path": path,"acl_update_policy": "editors","force_async": False,"member_policy": member_policy ,"shared_link_policy": shared_link_policy} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/sharing/share_folder', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: # Fetching response in JSON r = r.content.decode("utf-8") response = json.loads(r) print(response) # Creating a message object using YA SDK functions m = MessageClass() m.message_text = "Details for the shared folder : " attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Shared link : " field1.value = response['preview_url'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Visibility :" field2.value = response['policy']['shared_link_policy']['.tag'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Name :" field3.value = response['name'] attachment.attach_field(field3) m.attach(attachment) return m.to_json() else: print("Error") m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def create_folder(self, args): print("In create_folder") print(args) path = args['path'] autorename = args['autorename'] if autorename != 'true' and autorename != 'false': m = MessageClass() m.message_text = "Invalid value in autorename argument" return m.to_json() headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } if autorename == 'true': autorename = True else: autorename = False data = {"path": path,"autorename": autorename} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/create_folder_v2', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: print("---------------") # Getting response in JSON r = r.content.decode("utf-8") response = json.loads(r) print(response) #Creating message using YA SDK message = MessageClass() attachment = MessageAttachmentsClass() attachment2 = MessageAttachmentsClass() message.message_text = "New folder successfully created" button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get folder details" button.command = { "service_application": str(self.user_integration.yellowant_integration_id), "function_name": 'get_all_folders', "data" :{"path": response['metadata']['path_display'], "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True} } attachment2.attach_button(button) message.attach(attachment) message.attach(attachment2) return message.to_json() else: print("Error") m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()