def deal_list(self, args): """For viewing the account details""" query = "api_key=" + self.API_Access_key + "&api_action=deal_list&api_output=json" url = (self.API_Access_URL + "/admin/api.php?" + query) response = requests.get(url) response_json = response.json() message = MessageClass() attachment = MessageAttachmentsClass() for i in response_json['deals']: field1 = AttachmentFieldsClass() field1.title = "Title" field1.value = i['title'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Email" field2.value = i['contact_email'] attachment.attach_field(field2) message.attach(attachment) message.message_text = "List of deals:" return message.to_json()
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 list_items(self, args): """ This function returns all the items of an organization """ org_id = args['organization'] headers = { "Authorization": "Zoho-oauthtoken" + " " + self.zohoinvoice_access_token, "X-com-zoho-invoice-organizationid": org_id, "Content-Type": "application/json" } url = settings.ZOHO_ITEMS_URL response = requests.get(url, headers=headers) print(response) print(response.text) message = MessageClass() message.message_text = "Items" response_json = response.json() data = response_json['items'] i = 0 print(data[0]['description']) a = data[0]['description'] if len(a) == 0: print("its none") else: print("no") for item in data: attachment = MessageAttachmentsClass() attachment.text = "Item" + " " + str(i + 1) field1 = AttachmentFieldsClass() field1.title = "Item Name" field1.value = item['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Item ID" field2.value = item['item_id'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Item Type" field3.value = item['product_type'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Rate" field4.value = item['rate'] attachment.attach_field(field4) des = item['description'] field5 = AttachmentFieldsClass() field5.title = "Description" field5.value = "-" if len(des) == 0 else des attachment.attach_field(field5) i = i + 1 message.attach(attachment) return message.to_json()
def get_incident(self, args): """ Get information corresponding to the given incident_uuid """ incident_id = args['Incident-UUID'] url = (settings.VICTOROPS_INCIDENT_ALERT_URL + incident_id) # get request to victorops server response = requests.get(url, headers=self.headers) # print(response) response_json = response.json() # print(response_json) message = MessageClass() message.message_text = "Incident Details" # if the ID does not have an incident associated with it. if response.status_code == 422: attachment = MessageAttachmentsClass() attachment.text = "No incident found for the given ID!" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Incident Description" field1.value = response_json['entityDisplayName'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Incident Body" field2.value = response_json['stateMessage'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Entity ID" field3.value = response_json['entityId'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Incident Type" field4.value = response_json['messageType'] attachment.attach_field(field4) try: # val = response_json['ackAuthor'] field5 = AttachmentFieldsClass() field5.title = "Acknowledged By" field5.value = response_json['ackAuthor'] attachment.attach_field(field5) except: pass message.attach(attachment) # print(message) # message = json.dumps(message) # return message # print(type(message)) return message.to_json()
def create_incident(self, args): """ create_incident function creates a new incident for a specific page of user """ print("In create incident") print(args) page_id = args['page_id'] status = args['status'] components_id = args['components_id'] name = args['name'] body = args['body'] data = { "incident" : { "name": name, "status": status, "body": body, "wants_twitter_update":"f", "components_ids": components_id, "deliver_notifications":"true" } } # POST request to statuspage server url = (settings.SP_API_BASE1 + page_id + "/incidents.json") response = requests.post(url,headers=self.headers,json=data) if (response.status_code == requests.codes.ok): response_json = response.json() #print("------------------------------------") print(response_json) message = MessageClass() message.message_text = "New Incident Details:" attachment = MessageAttachmentsClass() try: field1 = AttachmentFieldsClass() field1.title = "ID" field1.value = response_json['id'] attachment.attach_field(field1) except: pass try: field2 = AttachmentFieldsClass() field2.title = "Status" field2.value = response_json['status'] attachment.attach_field(field2) except: pass message.attach(attachment) return message.to_json() else: return "{0}: {1}".format(response.status_code, response.text)
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_complaints(self, args): print("In get_complaints") # API parameteres for getting account information auth = ("api", self.mailgun_access_token) # Consuming the API r = requests.get("https://api.mailgun.net/v3/" + self.domain_name + "/complaints", auth=("api", self.mailgun_access_token)) # NOT USED here sample_response = { "items": [{ "address": "*****@*****.**", "created_at": "Fri, 21 Oct 2011 11:02:55 GMT" }] } # Response check if r.status_code == requests.codes.ok: # Getting response in JSON print(print(json.loads(r.text))) response = json.loads(r.text) # Creating message objects to structure the message to be shown if (len(response['items']) == 0): message = MessageClass() message.message_text = "You don't have any complaints as of now !" return message.to_json() message = MessageClass() message.message_text = "Complaint details :" attachment = MessageAttachmentsClass() for i in range(0, len(response['items'])): field1 = AttachmentFieldsClass() field1.title = "Address :" field1.value = response['items'][i]["address"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Created at :" field2.value = response['items'][i]["created_at"] 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 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 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 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 accept(args,user_integration): """ Function to accept the invitation from another player. """ opponent_user_integration = args.get("user_int") state = str(uuid.uuid4()) opponent_object = UserIntegration.objects.get(yellowant_integration_id=opponent_user_integration) opponent_object.playing_state = state player_object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id) player_object.playing_state = state player_object.opponent_integration_id = opponent_object.yellowant_integration_id opponent_object.opponent_integration_id = player_object.yellowant_integration_id player_object.board_state = INITIAL_BOARD + INITIAL_BOARD_REST opponent_object.board_state = INITIAL_BOARD + INITIAL_BOARD_REST player_object.save() opponent_object.save() webhook_message = MessageClass() webhook_message.message_text = "Chess Invite" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Your Chess Invite has been accepted by" field1.value = player_object.yellowant_team_subdomain button = MessageButtonsClass() button.text = "Start Game" button.value = "Start Game" button.name = "Start Game" button.command = { "service_application" : str(opponent_object.yellowant_integration_id), "function_name" : "startgameplayer", "data" : {"user_int": player_object.yellowant_integration_id}, "inputs" : ["Color"] } attachment.attach_button(button) attachment.attach_field(field1) webhook_message.attach(attachment) access_token = opponent_object.yellowant_integration_token yellowant_user_integration_object = YellowAnt(access_token=access_token) send_message = yellowant_user_integration_object.create_webhook_message( requester_application=opponent_object.yellowant_integration_id, webhook_name="webhook", **webhook_message.get_dict()) m = MessageClass() return m
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_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 campaign_report_bounce_list(self, args): """For viewing the account details""" message = MessageClass() id = args['Id'] query = "api_key=" + self.API_Access_key + "&api_action=campaign_report_bounce_list&api_output=json&id="+id url = (self.API_Access_URL + "/admin/api.php?" + query) response = requests.get(url) response_json = response.json() #print(response_json[str(1)]['descript']) i=0 j=0 for i in range(1000000): try: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Description" field1.value = response_json[str(i)]['descript'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Email" field2.value = response_json[str(i)]['email'] attachment.attach_field(field2) i+=1 except: break #print(i) for j in range(i): print(j) attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Description" field1.value = response_json[str(j)]['descript'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Email" field2.value = response_json[str(j)]['email'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "ID" field3.value = response_json[str(j)]['id'] attachment.attach_field(field3) j += 1 print(j) message.attach(attachment) message.message_text = "The Bounce list is" 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 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 list_users(self, args): """ Gives information about the users of the organization """ url = settings.VICTOROPS_ALL_USERS response = requests.get(url, headers=self.headers) response_json = response.json() # print(response_json) message = MessageClass() message.message_text = "Users" if not bool(response_json): attachment = MessageAttachmentsClass() attachment.text = "No users!" message.attach(attachment) return message.to_json() else: data = response_json['users'][0] for i in range(len(data)): attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Username" field1.value = data[i]['username'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Name" field2.value = str(data[i]['firstName']) + " " + str( data[i]['lastName']) attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Email" field3.value = data[i]['email'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Password Last Updated" field4.value = data[i]['passwordLastUpdated'] attachment.attach_field(field4) field5 = AttachmentFieldsClass() field5.title = "Verified" field5.value = data[i]['verified'] attachment.attach_field(field5) 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 get_user(self, args): """ This function is used to get the user details given the victorops user id """ user = args['User-ID'] # VictorOps user ID url = settings.VICTOROPS_GET_USER + str(user) response = requests.get(url, headers=self.headers) response_json = response.json() message = MessageClass() message.message_text = "User Details" if bool(response_json) == False: attachment = MessageAttachmentsClass() attachment.text = "No user found!" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Username" field1.value = response_json['username'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Name" field2.value = str(response_json['firstName']) + " " + str( response_json['lastName']) attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Email" field3.value = response_json['email'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Password Last Updated" field4.value = response_json['passwordLastUpdated'] attachment.attach_field(field4) field5 = AttachmentFieldsClass() field5.title = "Verified" field5.value = response_json['verified'] attachment.attach_field(field5) message.attach(attachment) return message.to_json()
def employee_created(request, id): print('Inside employee created') name = request.POST['name'] contact_id = request.POST['id'] last_name = request.POST['last_name'] email = request.POST['email'] yellow_obj = UserIntegration.objects.get(webhook_id=id) access_token = yellow_obj.yellowant_integration_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 Employee added" attachment = MessageAttachmentsClass() field = AttachmentFieldsClass() field.title = "Name" field.value = name + " " + last_name attachment.attach_field(field) field1 = AttachmentFieldsClass() field1.title = "Email ID" field1.value = email attachment.attach_field(field1) # print(integration_id) webhook_message.data = { "Name": name, "ID": contact_id, "Email": email, "LastName": last_name } webhook_message.attach(attachment) # 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=service_application, webhook_name="createemployeewebhook", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
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 View_Surveys(self, args): # Display the Surveys associated with the users account. print("In view surveys") user_id = self.user_integration.yellowant_intergration_id url = (settings.SM_API_BASE + settings.VIEW_SURVEY) response = requests.get(url, headers=self.headers) response_json = response.json() print(response_json) data = response_json["data"] send_data = {"surveys": []} message = MessageClass() message.message_text = "Surveys" for i in range(len(data)): attachment = MessageAttachmentsClass() send_data['surveys'].append({ 'id': data[i]["id"], 'title': data[i]["title"] }) obj = data[i] title = obj["title"] id = obj["id"] button1 = MessageButtonsClass() attachment.title = title field1 = AttachmentFieldsClass() field1.title = "ID" field1.value = id attachment.attach_field(field1) button1.text = "Know more" button1.value = id button1.name = id button1.command = { "service_application": user_id, "function_name": "ViewSurveyDetails", "data":{\ "SurveyId":id\ } } attachment.attach_button(button1) message.attach(attachment) message.data = send_data print(message) # use inbuilt sdk method to_json to return message in a json format accepted by YA return message.to_json()
def get_attendance(args, user_integration): auth_token_object = UserIntegration.objects.get( yellowant_integration_id=user_integration.yellowant_integration_id) auth_token = auth_token_object.auth_token m = MessageClass() url = 'https://people.zoho.com/people/api/attendance/getUserReport?' sDate = args.get('start_date') eDate = args.get('end_date') employee_id = args.get('employee_id') data = { 'authtoken': auth_token, 'sdate': sDate, 'edate': eDate, 'empId': employee_id, 'dateFormat': 'yyyy-MM-dd' } response = requests.post(url, data=data) response = response.json() print(type(response)) attachment = MessageAttachmentsClass() for k, v in response.items(): attachment = MessageAttachmentsClass() attachment.title = k for k1, v1 in v.items(): field = AttachmentFieldsClass() field.title = k1 field.value = v1 attachment.attach_field(field) m.attach(attachment) field = AttachmentFieldsClass() print(response) print(sDate) print(eDate) print(employee_id) m.message_text = "Just test" return m
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 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 get_domains(self, args): """ Get a list of all domains """ print("In get_domains") # API parameteres for getting account information param = {"skip": 0, "limit": 3} auth = ("api", self.mailgun_access_token) # Consuming the API r = requests.get(API_BASE_URL, auth=auth, params=param) # 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")) items = response["items"] # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = "All domain details :" attachment = MessageAttachmentsClass() for item in range(0, len(items)): field1 = AttachmentFieldsClass() field1.title = "Domain :" field1.value = response["items"][item]["name"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "State :" field2.value = response["items"][item]["state"] 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 create_component(self, args): """ create_component function creates a new component for a specific page of user """ #print("In create component") page_id = args['page_id'] name = args['name'] description = args['description'] data = {"component": { "name": name, "description": description }} # POST request to statuspage server url = settings.SP_API_BASE1 + page_id + "/components.json" response = requests.post(url, headers=self.headers, json=data) if (response.status_code == requests.codes.ok): response_json = response.json() #print("------------------------------------") #print(response_json) message = MessageClass() message.message_text = "New Component Details:" attachment = MessageAttachmentsClass() try: field1 = AttachmentFieldsClass() field1.title = "ID" field1.value = response_json['id'] attachment.attach_field(field1) except: pass try: field2 = AttachmentFieldsClass() field2.title = "Status" field2.value = response_json['status'] attachment.attach_field(field2) except: pass message.attach(attachment) return message.to_json() else: return "{0}: {1}".format(response.status_code, response.text)
def webhooks(request, id=None): #print(request.post.data) # print(type(request)) # print((request.body)) try: body = json.loads(json.dumps((request.body.decode("utf-8")))) # print("Body is") # print(body) # print(json.loads(body)) body = json.loads(body) except: return HttpResponse("Failed", status=404) # print(body['sys_id']) User = UserIntegration.objects.get(webhook_id=id) service_application = str(User.yellowant_integration_id) access_token = User.yellowant_integration_token ####### STARTING WEB HOOK PART webhook_message = MessageClass() webhook_message.message_text = "Incident" + " " + body['state'] attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Incident Name" field1.value = body['number'] attachment.attach_field(field1) webhook_message.attach(attachment) attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Incident Description" field1.value = body['description'] attachment.attach_field(field1) webhook_message.attach(attachment) # 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=User.yellowant_integration_id, webhook_name="webhook", **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 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 add_user(self, args): """ This function is used to add an user to the organization """ org_id = args['organization'] name = args['name'] email = args['email'] role = args['user_role'] 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_USER_URL payload = {"name": name, "email": email, "user_role": role} 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 = "Your invitation has been sent." 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 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 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 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_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 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 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()