Exemple #1
0
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)
Exemple #2
0
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)
Exemple #3
0
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
Exemple #4
0
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)
Exemple #5
0
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
Exemple #6
0
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)
Exemple #7
0
    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()
Exemple #8
0
    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 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()
Exemple #10
0
def playAgainst(args,user_integration):
    """
    Function which sends the invite to other players to play chess.
    """
    opponent_id = args.get("yellowant_user_id")
    opponent_object = UserIntegration.objects.get(yellowant_integration_id=opponent_id)
    player_object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)

    webhook_message = MessageClass()
    webhook_message.message_text = "Chess Invite"
    attachment = MessageAttachmentsClass()
    field1 = AttachmentFieldsClass()
    field1.title = "You have been invited to play chess with "
    field1.value = player_object.yellowant_team_subdomain

    button = MessageButtonsClass()
    button.text = "Accept Invitation"
    button.value = "Accept Invitation"
    button.name = "Accept Invitation"
    button.command = {
                      "service_application": str(opponent_object.yellowant_integration_id),
                      "function_name": "accept",
                      "data": {"user_int": player_object.yellowant_integration_id }
                     }
    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)

    print("Printing webhook")
    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()
    m.message_text = "Waiting for response from opponent"

    return m
Exemple #11
0
    def next_page(self, args):
        """This returns the list of functions in the next page"""
        message = MessageClass()
        region = args['Region']
        next_marker = args['NextMarker']
        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)
        # Gets the next ten functions in lambda
        response = aws_lambda.list_functions(Marker=next_marker, MaxItems=10)
        functions = [Function['FunctionName'] for Function in response['Functions']]
        for Function in functions:

            attachment = MessageAttachmentsClass()
            attachment.title = Function

            # Button to get the logs of the function
            button = MessageButtonsClass()
            button.text = "Get Logs"
            button.value = "Get Logs"
            button.name = "Get Logs"
            button.command = {"service_application": self.yellowant_integration_id,
                              "function_name": "get-logs",
                              "data": {"FunctionName": Function, "Region": region}}
            attachment.attach_button(button)

            # Button to invoke the function
            button1 = MessageButtonsClass()
            button1.text = "Invoke"
            button1.value = "Invoke"
            button1.name = "Invoke"
            button1.command = {"service_application": self.yellowant_integration_id,
                               "function_name": "invoke-async",
                               "data": {"Function-Name": Function, "Region": region},
                               "inputs": ["input"]}
            attachment.attach_button(button1)
            message.attach(attachment)

        try:
            # Button to get the functions in next page, Checks actually if next page exists or not
            attachment = MessageAttachmentsClass()
            button2 = MessageButtonsClass()
            button2.text = "Next Page"
            button2.value = "Next Page"
            button2.name = "Next Page"
            button2.command = {"service_application": self.yellowant_integration_id,
                               "function_name": "next-page",
                               "data": {"NextMarker": response['NextMarker'], "Region": region}}
            attachment.attach_button(button2)
            message.attach(attachment)
            message.message_text = "The Functions present are:"

        except:
            message.message_text = "This is the Last page and The Functions present are: "

        return message.to_json()
Exemple #12
0
def showBoard(args,user_integration):

    print(user_integration.yellowant_integration_id)
    object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)
    board = chess.Board(object.board_state)
    print(object.board_state)

    m = MessageClass()
    m.message_text = color(object.board_state[-12])  + " to move"
    attachment = MessageAttachmentsClass()
    attachment.image_url = IMAGE_URL + board.fen()[:-13]
    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)
    m.attach(attachment)

    return m
Exemple #13
0
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)
Exemple #14
0
def add_new_user(request, webhook_id):
    """
        Webhook function to notify user about newly added user
    """

    # Extracting necessary data
    data = request.body
    data_string = data.decode('utf-8')
    data_json = json.loads(data_string)

    ID = data_json["current"][0]['id']
    name = data_json["current"][0]['name']
    Default_currency = data_json["current"][0]['default_currency']
    Email = data_json["current"][0]['email']
    phone = "-" if data_json["current"][0]['phone'] is None else data_json[
        "current"][0]['phone']

    # 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 user added."+"\n" + "The username : "******"\nThe Email ID:" + str(Email)
    attachment = MessageAttachmentsClass()
    attachment.title = "Get user details"

    button_get_users = MessageButtonsClass()
    button_get_users.name = "1"
    button_get_users.value = "1"
    button_get_users.text = "Get all users"
    button_get_users.command = {
        "service_application": service_application,
        "function_name": 'list_users',
        "data": {
            'data': "test",
        }
    }

    attachment.attach_button(button_get_users)
    webhook_message.attach(attachment)
    # print(integration_id)
    # userinfo = response['data']
    # phone = "-" if userinfo['phone'] is None else userinfo['phone']
    webhook_message.data = {
        "name": name,
        "ID": ID,
        "Email": Email,
        "Phone": phone,
        "Default currency": Default_currency
    }

    # 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_user",
        **webhook_message.get_dict())

    return HttpResponse("OK", status=200)
Exemple #15
0
def webhook_unsubscribed(request, webhook_id):
    print("In webhook_unsubscribed")
    """
    Webhook function to notify user about update in unsbscribes
    """

    urllib.parse.unquote(request.body.decode("utf-8"))
    params_dict = urllib.parse.parse_qsl(request.body)
    params = dict(params_dict)

    ## Extracting necessary data

    device_type = params[b'device-type'].decode("utf-8")
    name = params[b'client-name'].decode("utf-8")
    domain = params[b'domain'].decode("utf-8")
    city = params[b'city'].decode('utf-8')
    country = params[b'country'].decode('utf-8')
    recipient = params[b'recipient'].decode('utf-8')

    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 = "Unsubscribe details"

        attachment_message = MessageAttachmentsClass()

        field2 = AttachmentFieldsClass()
        field2.title = "Email Id :"
        field2.value = recipient
        attachment_message.attach_field(field2)

        field1 = AttachmentFieldsClass()
        field1.title = "Browser :"
        field1.value = name
        attachment_message.attach_field(field1)

        field3 = AttachmentFieldsClass()
        field3.title = "Domain"
        field3.value = domain
        attachment_message.attach_field(field3)

        field4 = AttachmentFieldsClass()
        field4.title = "Device type"
        field4.value = device_type
        attachment_message.attach_field(field4)

        field5 = AttachmentFieldsClass()
        field5.title = "City"
        field5.value = city
        attachment_message.attach_field(field5)

        field6 = AttachmentFieldsClass()
        field6.title = "Country"
        field6.value = country
        attachment_message.attach_field(field6)

        webhook_message.attach(attachment_message)

        attachment = MessageAttachmentsClass()
        attachment.title = "Unsubscribe operations"

        button_get_incidents = MessageButtonsClass()
        button_get_incidents.name = "1"
        button_get_incidents.value = "1"
        button_get_incidents.text = "Get unsubscribe details"
        button_get_incidents.command = {
            "service_application": service_application,
            "function_name": 'get_unsubscribes',
            "data": {}
        }

        attachment.attach_button(button_get_incidents)
        webhook_message.data = {
            "recipient_email_id": recipient,
            "domain": domain,
            "device_type": device_type,
            "city": city,
            "country": country,
            "name": name,
        }
        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_unsubscribe",
            **webhook_message.get_dict())
        return HttpResponse("OK", status=200)

    except YellowUserToken.DoesNotExist:
        return HttpResponse("Not Authorized", status=403)
Exemple #16
0
def startGameAgainstPlayer(args,user_integration):
    """

    """


    player_object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)

    opponent_object = UserIntegration.objects.get(yellowant_integration_id=player_object.opponent_integration_id)

    board = chess.Board(player_object.board_state)
    color = args['Color']

    attachment = MessageAttachmentsClass()

    print(color + " to move")

    if (color=="Black"):
        webhook_message = MessageClass()
        webhook_message.message_text = "You are playing White!"
        attachment = MessageAttachmentsClass()
        button = MessageButtonsClass()
        button.text = "Make Move"
        button.value = "Make Move"
        button.name = "Make Move"
        button.command = {
            "service_application": str(opponent_object.yellowant_integration_id),
            "function_name": "makemoveagainst",
            "data": {"user_int": player_object.yellowant_integration_id},
        }
        attachment.attach_button(button)

        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())

        return

    else:
        print("Inside else")
        m = MessageClass()
        attachment = MessageAttachmentsClass()
        attachment.image_url = IMAGE_URL + INITIAL_BOARD
        m.message_text = "Make a Move"
        field1 = AttachmentFieldsClass()
        field1.title = "Move"
        field1.value = color + " to move"
        attachment.attach_field(field1)

        attachment.image_url = IMAGE_URL + INITIAL_BOARD


        button = MessageButtonsClass()
        button.text = "Make Move"
        button.value = "Make Move"
        button.name = "Make Move"
        button.command = {
            "service_application": str(player_object.yellowant_integration_id),
            "function_name": "makemoveagainst",
            "inputs": ["move"],
            "data": {"user_int": player_object.yellowant_integration_id},
        }
        attachment.attach_button(button)

        m.attach(attachment)

        return m
Exemple #17
0
    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()
Exemple #18
0
    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()
Exemple #19
0
def webhook(request, hash_str=""):
    print("Inside webhook")
    data = request.body
    if len(data) == 0:
        validationToken = request.GET['validationtoken']
        try:
            print("In try")
            return HttpResponse(validationToken, status=200)
        except:
            validationToken = None
            print("Error occured")
            return HttpResponse(status=400)
    else:
        try:
            message = MessageClass()
            attachment = MessageAttachmentsClass()
            response_json = json.loads(data)
            value_obj = response_json["value"]
            value = value_obj[0]
            SubscriptionId = value["SubscriptionId"]
            ResourceData = value["ResourceData"]
            message_id = ResourceData["Id"]
            ya_user = YellowUserToken.objects.get(
                subscription_id=SubscriptionId)
            """Make a request to get the message details using message_id"""
            get_message_details = graph_endpoint.format(
                "/me/messages/{}".format(message_id))
            webhook_request = make_api_call('GET', get_message_details,
                                            ya_user.outlook_access_token)
            response_json = webhook_request.json()
            subject = response_json["subject"]
            from_user = response_json["from"]
            email_address = from_user["emailAddress"]

            attachment.title = "Subject"
            attachment.text = str(subject)
            message.attach(attachment)

            forward_button = MessageButtonsClass()
            forward_button.text = "Forward"
            forward_button.value = "forward"
            forward_button.name = "forward"
            forward_button.command = {
                "service_application": ya_user.yellowant_integration_id,
                "function_name": "forward_message",
                "data": {
                    "Message-Id": str(message_id)
                },
                "inputs": ["toRecipients", "Message"]
            }
            attachment.attach_button(forward_button)

            reply_button = MessageButtonsClass()
            reply_button.text = "Reply"
            reply_button.value = "Reply"
            reply_button.name = "Reply"
            reply_button.command = {
                "service_application": ya_user.yellowant_integration_id,
                "function_name": "reply",
                "data": {
                    "Message-Id": str(message_id)
                },
                "inputs": ["Message"]
            }
            attachment.attach_button(reply_button)

            message.message_text = "Ola! You got a new E-mail from-" + email_address[
                "name"] + "( " + email_address["address"] + " )"
            yauser_integration_object = YellowAnt(
                access_token=ya_user.yellowant_token)
            print("Reached here")
            yauser_integration_object.create_webhook_message(
                requester_application=ya_user.yellowant_integration_id,
                webhook_name="inbox_webhook",
                **message.get_dict())
            return True

        except YellowUserToken.DoesNotExist:
            return HttpResponse("Not Authorized", status=403)
Exemple #20
0
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)
Exemple #21
0
    def list_users_today(self, args):
        #Check if 'sort' param is present, else assign default as 'asc'
        if 'sort' in args:
            if args['sort'] in ['asc', 'dsc']:
                order = args['sort']
            else:
                #If invalid, fallback to default value
                order = 'asc'
        else:
            #setting default order 'asc'
            order = 'asc'

        if 'subscription' in args:
            subscription = args['subscription']
        else:
            subscription = None

        #Instantiate a Message Object
        message = MessageClass()
        message.message_text = ""

        #Create list to store the results
        users_list = []

        d_24 = datetime.datetime.now() - datetime.timedelta(days=1)
        if subscription is None:
            users_today = SiteUsers.objects.filter(date_joined__gte=d_24)
        else:
            users_today = SiteUsers.objects.filter(date_joined__gte=d_24,
                                                   subscription=subscription)

        #Creating User attachments with information of users with a button to fetch user details using the "list_user_details" command
        for user in users_today:
            user_attachment = MessageAttachmentsClass()
            user_attachment.title = user.full_name

            #Showing user data in a "Field"
            date_field = AttachmentFieldsClass()
            date_field.title = "Date Joined"
            date_field.value = user.date_joined
            date_field.short = 1  #Utilize two columns
            user_attachment.attach_field(date_field)

            #Adding a button which calls the "list_user_details" command
            get_user_details_button = MessageButtonsClass()
            get_user_details_button.value = "1"  #Give some random value
            get_user_details_button.name = "1"  #Give some random value
            get_user_details_button.text = "Get user details"
            #Encoding command in button
            get_user_details_button.command = {
                "function_name": "list_user_details",
                "service_application": self.service_application,
                "data": {
                    "id": user.id
                }
            }
            user_attachment.attach_button(get_user_details_button)

            #Adding a button which provides with a dialog to change the subscription for the user using "change_user_subcription" function
            change_user_sub_button = MessageButtonsClass()
            change_user_sub_button.value = "1"  #Give some random value
            change_user_sub_button.name = "1"  #Give some random value
            change_user_sub_button.text = "Change subscription"
            #Encoding command in button
            change_user_sub_button.command = {
                "function_name": "change_user_subcription",
                "service_application": self.service_application,
                "data": {
                    "id": user.id
                },
                "inputs": ['subscription']
            }
            user_attachment.attach_button(change_user_sub_button)

            #Add attachment to message
            message.attach(user_attachment)

        #Adding users data to be used in workflows
        message.data = {"users": serializers.serialize("json", users_today)}
        return message.to_json()
Exemple #22
0
def makeAMove(args,user_integration):

    print('hello')
    print(user_integration.yellowant_integration_id)
    object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)
    print(object.id)
    print(object.board_state)
    board = chess.Board(object.board_state)
    print(board)
    print(args)
    move = args.get('move')

    m = MessageClass()
    print(object.board_state)
    print(object.board_state[-12])
    col = color_inv(object.board_state[-12])
    print(col)
    m.message_text = col + " to move"
    move_uci = board.parse_san(move)
    if move_uci in board.legal_moves:
        board.push_san(move)
        if board.is_insufficient_material():
            print("Insufficient material")
            m.message_text = "Insufficient material"

        if board.is_stalemate():
            print("Stalemate")
            m.message_text = "Stalemate"
        if board.is_checkmate():
            print(col + " wins")
            m.message_text = col + " wins"

        object.board_state = board.fen()
        object.save()
    else:
        m.message_text = "Invalid move"
        return m



    attachment = MessageAttachmentsClass()
    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)

    attachment.image_url = IMAGE_URL + board.fen()[:-13]

    m.attach(attachment)

    return m
Exemple #23
0
def get_incident(args, user_integration):

    access_token_object = Servicenow_model.objects.get(
        user_integration=user_integration.id)
    access_token = access_token_object.access_token
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + access_token
    }

    sys_id = args.get('sys_id')
    instance = access_token_object.instance
    url = " https://" + instance + ".service-now.com/api/now/table/incident/" + sys_id

    response = requests.get(url=url, headers=headers)

    message = MessageClass()
    message.message_text = "The incident is"

    attachment = MessageAttachmentsClass()

    field1 = AttachmentFieldsClass()
    field1.title = "Incident Name"
    field1.value = response.json()["result"]["number"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Created by"
    field1.value = response.json()["result"]["sys_created_by"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Incident State"
    field1.value = response.json()["result"]["incident_state"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Description"
    field1.value = response.json()["result"]["description"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Priority"
    field1.value = response.json()["result"]["priority"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Impact"
    field1.value = response.json()["result"]["impact"]
    attachment.attach_field(field1)

    button = MessageButtonsClass()
    button.text = "Modify State"
    button.value = "Modify State"
    button.name = "Modify State"
    button.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "modifystate",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["state"]
    }
    attachment.attach_button(button)

    button = MessageButtonsClass()
    button.text = "Change impact"
    button.value = "Change impact"
    button.name = "Change impact"
    button.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "changeimpact",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["impact"]
    }
    attachment.attach_button(button)

    button1 = MessageButtonsClass()
    button1.text = "Close Incident"
    button1.value = "Close Incident"
    button1.name = "Close Incident"
    button1.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "closeincident",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["close_notes", "close_code"]
    }
    attachment.attach_button(button1)

    button2 = MessageButtonsClass()
    button2.text = "Resolve Incident"
    button2.value = "Resolve Incident"
    button2.name = "Resolve Incident"
    button2.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "resolveincident",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["resolve_notes", "close_code"]
    }
    attachment.attach_button(button2)

    button3 = MessageButtonsClass()
    button3.text = "Change priority"
    button3.value = "Change priority"
    button3.name = "Change priority"
    button3.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "changepriority",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["priority"]
    }
    attachment.attach_button(button3)

    message.attach(attachment)

    return message
Exemple #24
0
def makeMoveAgainst(args,user_integration):
    player_object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)
    opponent_object = UserIntegration.objects.get(yellowant_integration_id=player_object.opponent_integration_id)

    access_token = opponent_object.yellowant_integration_token
    yellowant_user_integration_object = YellowAnt(access_token=access_token)

    move = args.get("move")
    board = chess.Board(player_object.board_state)
    col = color_inv(player_object.board_state[-12])

    m = MessageClass()

    m.message_text = col + " to move"
    move_uci = board.parse_san(move)
    if move_uci in board.legal_moves:
        board.push_san(move)
        if board.is_insufficient_material():
            print("Insufficient material")
            m.message_text = "Insufficient material"
            endGame(args, user_integration)

            webhook_message = MessageClass()
            webhook_field = AttachmentFieldsClass()
            webhook_field.title = "Result"
            webhook_field.value = "Game drawn due to insufficient material"
            attachmentImage = MessageAttachmentsClass()
            attachmentImage.image_url = IMAGE_URL + board.fen()[:-13]
            attachmentImage.attach_field(webhook_field)
            webhook_message.attach(attachmentImage)





        if board.is_stalemate():
            print("Stalemate")
            m.message_text = "Stalemate"
            endGame(args, user_integration)
        if board.is_checkmate():
            print(col + " wins")
            m.message_text = col + " wins"
            endGame(args, user_integration)

        player_object.board_state = board.fen()
        opponent_object.board_state = board.fen()

        player_object.save()
        opponent_object.save()



    else:
        m.message_text = "Invalid move"
        return m

    attachment = MessageAttachmentsClass()
    attachment.image_url = IMAGE_URL + board.fen()[:-13]

    m.attach(attachment)
    webhook_message = MessageClass()
    webhook_field = AttachmentFieldsClass()
    webhook_field.title = "Move"
    webhook_field.value = col + " to move"
    attachmentImage = MessageAttachmentsClass()
    attachmentImage.attach_field(webhook_field)
    attachmentImage.image_url = IMAGE_URL + board.fen()[:-13]

    button = MessageButtonsClass()
    button.text = "Make Move"
    button.value = "Make Move"
    button.name = "Make Move"
    button.command = {
        "service_application": str(opponent_object.yellowant_integration_id),
        "function_name": "makemoveagainst",
        "inputs": ["move"],
        "data": {"user_int": player_object.yellowant_integration_id},
    }
    attachmentImage.attach_button(button)

    webhook_message.attach(attachmentImage)



    send_message = yellowant_user_integration_object.create_webhook_message(
        requester_application=opponent_object.yellowant_integration_id,
        webhook_name="webhook", **webhook_message.get_dict())

    return m
Exemple #25
0
    def list_function(self, args):
        """ Gives the list of the functions in the Lambda"""
        message = MessageClass()
        attachment = MessageAttachmentsClass()
        region = args['Region']
        # Page is an optional argument
        try:
            page = int(args["Page"])
        except:
            page = 1
        # If page no. is greater than 1 get the marker of the specified field and use it to get the functions in that page
        if page > 1:
            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)

            #Snippet added to check the Page No. entered is valid or not
            check = aws_lambda.get_account_settings()
            max_page = int(int(check['AccountUsage']['FunctionCount'])/10)+1

            # If page no. entered is greter than max pages of the Lambda then return this
            if page > max_page:
                message.message_text = "The Page no. entered is more than the pages present"
                return message.to_json()

            next_marker = self.marker(args, page)
            response = aws_lambda.list_functions(Marker=next_marker, MaxItems=10)
            functions = [Function['FunctionName'] for Function in response['Functions']]

            # Attaching functions and thier respective Buttons
            for Function in functions:
                attachment = MessageAttachmentsClass()
                attachment.title = Function
                message.attach(attachment)

                # Button to get the logs of the function
                button = MessageButtonsClass()
                button.text = "Get Logs"
                button.value = "Get Logs"
                button.name = "Get Logs"
                button.command = {"service_application": self.yellowant_integration_id,
                                  "function_name": "get-logs",
                                  "data": {"FunctionName": Function, "Region": region}}
                attachment.attach_button(button)

                # Button to invoke the function
                button1 = MessageButtonsClass()
                button1.text = "Invoke"
                button1.value = "Invoke"
                button1.name = "Invoke"
                button1.command = {"service_application": self.yellowant_integration_id,
                                   "function_name": "invoke-async",
                                   "data": {"FunctionName": Function, "Region": region},
                                   "inputs": ["input"]}
                attachment.attach_button(button1)

            try:
                # Button to get the functions in next page, Checks actually if next page exists or not
                attachment = MessageAttachmentsClass()
                button2 = MessageButtonsClass()
                button2.text = "Next Page"
                button2.value = "Next Page"
                button2.name = "Next Page"
                button2.command = {"service_application": self.yellowant_integration_id,
                                   "function_name": "next-page",
                                   "data": {"NextMarker": response['NextMarker'], "Region": region}}
                attachment.attach_button(button2)
                message.message_text = ("The Functions in Page %d are:" % page)

            except:
                message.message_text = "This is the last page"

        # If page is 1 or not specified than return the functions in the 1st page
        else:
            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)

            # Display first 10 functions
            response = aws_lambda.list_functions(MaxItems=10)
            functions = [Function['FunctionName'] for Function in response['Functions']]
            for Function in functions:
                attachment = MessageAttachmentsClass()
                attachment.title = Function
                message.attach(attachment)

                # Button to get the logs of the function
                button = MessageButtonsClass()
                button.text = "Get Logs"
                button.value = "Get Logs"
                button.name = "Get Logs"
                button.command = {"service_application": self.yellowant_integration_id,
                                  "function_name": "get-logs",
                                  "data": {"FunctionName": Function, "Region": region}}
                attachment.attach_button(button)

                # Button to invoke the function
                button1 = MessageButtonsClass()
                button1.text = "Invoke"
                button1.value = "Invoke"
                button1.name = "Invoke"
                button1.command = {"service_application": self.yellowant_integration_id,
                                   "function_name": "invoke-async",
                                   "data": {"Function-Name": Function, "Region": region},
                                   "inputs": ["input"]}
                attachment.attach_button(button1)

            try:
                # Button to get the functions in next page, Checks actually if next page exists or not
                attachment = MessageAttachmentsClass()
                button2 = MessageButtonsClass()
                button2.text = "Next Page"
                button2.value = "Next Page"
                button2.name = "Next Page"
                button2.command = {"service_application": self.yellowant_integration_id,
                                   "function_name": "next-page",
                                   "data": {"NextMarker": response['NextMarker'], "Region": region}}
                attachment.attach_button(button2)
                message.message_text = ("The Functions in Page %d are:" % page)

            except:
                message.message_text = "This is the last page"

        return message.to_json()
Exemple #26
0
    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()
Exemple #27
0
def add_new_customer(request, webhook_id):
    """
    Webhook function to notify user about newly created customer
    """
    print("In add_new_customer")
    print(webhook_id)
    # Extracting necessary data

    code = request.GET.get("code", False)

    if code == request.codes.ok:
        data = (request.body.decode('utf-8'))
        response_json = json.loads(data)
        print(response_json)

        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
            #QuickbookUserToken.objects.get(realmId=response_json['eventNotifications'][0]['realmId']).user_integration_id
            service_application = str(integration_id)
            print(service_application)

            # Creating message object for webhook message
            webhook_message = MessageClass()
            id = str(response_json['eventNotifications'][0]['dataChangeEvent']
                     ['entities'][0]['id'])
            webhook_message.message_text = "New customer added\n" + "ID :" + str(
                response_json['eventNotifications'][0]['dataChangeEvent']
                ['entities'][0]['id'])
            attachment = MessageAttachmentsClass()
            attachment.title = "Get all customer details"

            button_get_incidents = MessageButtonsClass()
            button_get_incidents.name = "1"
            button_get_incidents.value = "1"
            button_get_incidents.text = "Get customer details"
            button_get_incidents.command = {
                "service_application": service_application,
                "function_name": 'get_customer_details',
                "data": {
                    "customer_id": id
                }
            }

            attachment.attach_button(button_get_incidents)

            webhook_message.data = {"customer_id": 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="new_customer",
                **webhook_message.get_dict())
            return HttpResponse("OK", status=200)

        except YellowUserToken.DoesNotExist:
            return HttpResponse("Not Authorized", status=403)
    else:
        return HttpResponse(status=400)
Exemple #28
0
def add_new_deal(request, webhook_id):
    """
        Webhook function to notify user about newly added deal
    """

    # Extracting necessary data
    data = request.body
    data_string = data.decode('utf-8')
    data_json = json.loads(data_string)

    title = data_json["current"]['title']
    handled_by = data_json["current"]['owner_name']
    name = data_json["current"]['person_name']
    currency = data_json["current"]['currency']
    company = data_json["current"]['org_name']
    value = data_json["current"]['value']
    deal_email = data_json["current"]['cc_email']

    # 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 deal created."+"\n" + "The deal name : " + str(title) + "\nThe deal value:" \
                                   + str(currency)+" "+str(value)
    attachment = MessageAttachmentsClass()

    button_get_deal = MessageButtonsClass()
    button_get_deal.name = "1"
    button_get_deal.value = "1"
    button_get_deal.text = "Get all deals"
    button_get_deal.command = {
        "service_application": service_application,
        "function_name": 'list_all_deals',
        "data": {
            'data': "test",
        }
    }

    attachment.attach_button(button_get_deal)
    webhook_message.attach(attachment)
    # print(integration_id)
    webhook_message.data = {
        "Handled by": handled_by,
        "Name": name,
        "Title": title,
        "Company": company,
        "Value": value,
        "Currency": currency,
        "Deal_email": deal_email
    }

    # 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_deal",
        **webhook_message.get_dict())
    return HttpResponse("OK", status=200)
Exemple #29
0
    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()
Exemple #30
0
def add_new_activity(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)

    title = data_json["current"]['deal_title']
    handled_by = data_json["current"]['owner_name']
    name = data_json["current"]['person_name']
    company = data_json["current"]['org_name']
    deal_email = data_json["current"]['deal_dropbox_bcc']
    activity_type = data_json["current"]['type']
    due_date = data_json["current"]['due_date']

    # 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 activity added."+"\n" + "The deal name : " + str(title) + "\nThe activity date:" \
                                   + str(due_date)
    attachment = MessageAttachmentsClass()

    button_get_activity = MessageButtonsClass()
    button_get_activity.name = "1"
    button_get_activity.value = "1"
    button_get_activity.text = "Get all activities"
    button_get_activity.command = {
        "service_application": service_application,
        "function_name": 'list_activities',
        "data": {
            'data': "test",
        }
    }

    attachment.attach_button(button_get_activity)
    webhook_message.attach(attachment)
    # print(integration_id)
    webhook_message.data = {
        "Handled by": handled_by,
        "Contact Person": name,
        "Due Date": due_date,
        "Deal Title": title,
        "Activity Type": activity_type,
        "Company": company,
        "Deal_email": deal_email
    }

    # 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_activity",
        **webhook_message.get_dict())
    return HttpResponse("OK", status=200)
Exemple #31
0
    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()
Exemple #32
0
def playComputer(args,user_integration):
    """
    Function to play against the Computer.
    """
    object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)
    board = chess.Board(object.board_state)
    dir_path = os.path.dirname(os.path.realpath(__file__))
    print(dir_path)
    engine = chess.uci.popen_engine("/app/stockfish/Linux/stockfish-9")
    #engine = chess.uci.popen_engine("/app/Stockfish-master/src/stockfish")
    col = color(object.board_state[-12])
    engine.position(board)
    move = engine.go(movetime=2000)
    board.push(chess.Move.from_uci(str(move[0])))
    m = MessageClass()
    if board.is_insufficient_material():
        print("Insufficient material")
        m.message_text = "Insufficient material"

        return m

    if board.is_stalemate():
        print("Stalemate")
        m.message_text = "Stalemate"


    if board.is_checkmate():
        print("Computer wins")
        m.message_text = "Checkmate !! \n"+col + " wins"

        return m

    object.board_state = board.fen()
    object.save()

    attachment = MessageAttachmentsClass()
    print(IMAGE_URL + board.fen()[:-13])
    attachment.image_url = IMAGE_URL + board.fen()[:-13]

    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)

    button2 = MessageButtonsClass()
    button2.text = "Accept Invitation"
    button2.value = "Accept Invitation"
    button2.name = "Accept Invitation"
    button2.command = {
                      "service_application" : str(user_integration.yellowant_integration_id),
                      "function_name" : "accept",
                      "data" : {"user_int": user_integration.yellowant_integration_id }
                     }
    attachment.attach_button(button2)


    m.attach(attachment)

    return m
def fetch_all_employees(args, user_integration):
    print(user_integration.yellowant_integration_id)
    print("user", user_integration.id)
    auth_token_object = UserIntegration.objects.get(
        yellowant_integration_id=user_integration.yellowant_integration_id)
    auth_token = auth_token_object.auth_token
    data = {'list': []}
    url = "https://people.zoho.com/people/api/forms/P_EmployeeView/records?authtoken=" + auth_token
    response = requests.post(url)
    response = response.json()
    m = MessageClass()
    for employee in response:
        attachment = MessageAttachmentsClass()
        for k, v in employee.items():
            if k == "First Name":
                field1 = AttachmentFieldsClass()
                field1.title = "First Name"
                field1.value = v
                attachment.attach_field(field1)
                first_name = v
            if k == "Last Name":
                field2 = AttachmentFieldsClass()
                field2.title = "Last Name"
                field2.value = v
                attachment.attach_field(field2)
                last_name = v
            if k == "EmployeeID":
                field3 = AttachmentFieldsClass()
                field3.title = "EmployeeID"
                field3.value = v
                attachment.attach_field(field3)
                employee_id = v
            if k == "recordId":
                record_id = v

        button = MessageButtonsClass()
        button.text = "Get details"
        button.value = "Get details"
        button.name = "Get details"
        button.command = {
            "service_application":
            str(user_integration.yellowant_integration_id),
            "function_name": "getemployee",
            "data": {
                "employee_id": employee_id
            },
        }
        attachment.attach_button(button)

        data['list'].append({
            "record_id": record_id,
            "employee_id": employee_id,
            "employee_name": first_name + " " + last_name
        })

        m.data = data
        m.attach(attachment)

    m.message_text = "Employee details are:"

    return m
Exemple #34
0
    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()