Esempio n. 1
0
def planets(input):
    # Extract string following trigger; Set to lowercase to allow for uppercase/lowercase data
    entry = bot.extract_message("/planets", input.text).strip().lower()
    response = Response()
    # Set general response if no data or "all" is entered
    if entry == "" or entry == "all":
        response.markdown = "Here are the 8 planets in order:  \n"
        response.markdown += "  1. Mercury  \n"
        response.markdown += "  2. Venus  \n"
        response.markdown += "  3. Earth  \n"
        response.markdown += "  4. Mars  \n"
        response.markdown += "  5. Jupiter  \n"
        response.markdown += "  6. Saturn  \n"
        response.markdown += "  7. Uranus  \n"
        response.markdown += "  8. Neptune  \n"
        return response
    else:
        # Set help response if "help" or "?" is entered
        if entry == "help" or input == "?":
            response.markdown = "Enter **/planets** followed by a planet name or a number to find the corresponding value.  \n"
            response.markdown += "Type **/planets** or **/planets all** to list all planets."
            return response
        else:
            # Call swtichers to retrieve planet name/number and picture
            response.markdown = planet_switch(entry)
            response.files = picture_switch(entry)
            return response
Esempio n. 2
0
def greeting(incoming_msg):
    sender = bot.teams.people.get(incoming_msg.personId)
    response = Response()

    if close_enough(incoming_msg.text.lower(),
                    "what is the answer to the big question"):
        response.markdown = "42 obviously! "
        response.markdown += "<br/>So long and thank you for all the fish!"
        return response
    elif close_enough(incoming_msg.text.lower(), "how are you"):
        response.markdown = "I'm fine thank you, I hope you are having a wonderful day! "
        response.markdown += "<br/>See what I can do by asking for **/help**."
        return response
    elif close_enough(incoming_msg.text.lower(), "by which laws do you exist"):
        response.markdown = "The three laws of robotics guide my actions: "
        response.markdown += "<br/> - A robot may not injure a human being or," \
                             " through inaction, allow a human being to come to harm."
        response.markdown += "<br/> - A robot must obey the orders given it by human beings" \
                             " except where such orders would conflict with the First Law."
        response.markdown += "<br/> - A robot must protect its own existence as long as such" \
                             " protection does not conflict with the First or Second Laws."
        return response
    else:
        response.markdown = "Hello {}, I'm a chat bot. ".format(
            sender.displayName)
        response.markdown += "<br/>See what I can do by asking for **/help**."
        return response
def vlan_list(incoming_msg):
    """Return the list of VLANs configured on device
    """
    response = Response()
    vlan_list = get_vlans(device)

    response.markdown = "I have the following VLANs configured: "
    for vlan, details in vlan_list.items():
        response.markdown += "`{} - {}`, ".format(vlan, details["name"])
    # Trim the last comma
    response.markdown = response.markdown[:-2]
    return response
def arp_list(incoming_msg):
    """Return the arp table from device
    """
    response = Response()
    arps = get_arps(device)

    if len(arps) == 0:
        response.markdown = "I don't have any entries in my ARP table."
    else:
        response.markdown = "Here is the ARP information I know. \n\n"
        for arp, details in arps.items():
            response.markdown += "* IP {} and MAC {} are available on interface {}.\n".format(
                arp, details["MAC Address"], details["Interface"])

    return response
def netmiko_interface_details(incoming_msg):
    """Retrieve the interface details from the configuration
       using netmiko example
    """
    response = Response()

    # Find the interface to check from the incoming message
    interface_to_check = bot.extract_message("/interface-config",
                                             incoming_msg.text).strip()
    interface_to_check = interface_to_check.split()[0]

    # Use the netmiko function
    interface = get_interface_details(
        device_address,
        device_type,
        device_username,
        device_password,
        interface_to_check,
    )
    print(interface)

    # Create and Return the message
    response.markdown = """
    {}
    """.format(interface)
    return response
Esempio n. 6
0
def l3_sum(incoming_msg):
    """
    Main function called by the Bot Menu to generate L3 Subnet Summary report.
    This function calls the bot_functions.conn_matrix function for the actual processing

    :param incoming_msg:
    :return:
    """

    # Lookup details about sender
    sender = app.teams.people.get(incoming_msg.personId)
    room = app.teams.rooms.get(incoming_msg.roomId)

    room_title = room.title

    l3_device, l3_int_list, resp, fn = bot_functions.l3_ints(incoming_msg)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = f"### Layer 3 Interfaces for device {l3_device}\n"
    response.markdown += f"Intf      Network/Mask          IP          VRF\n"

    for line in l3_int_list:
        response.markdown += f"{line}\n"

    # response.files = f"./{l3_device}_int_report.txt"
    response.files.append('./Interface_Diagram.png')

    return response
Esempio n. 7
0
def cfgdiff_report(incoming_msg):
    """
    Main function called by the Bot Menu to generate a Config Diff Report.
    This function calls the bot_functions.xxxxx function for the actual processing

    :param incoming_msg:
    :return:
    """

    app.logger.info('Processing config diff request')

    # Get sent message
    msg = ''
    message = incoming_msg.text.split()

    # Loopkup details about sender
    sender = app.teams.people.get(incoming_msg.personId)
    room = app.teams.rooms.get(incoming_msg.roomId)

    # if length of split message is greater than 2 elements then the function is being passed a site id parameter
    if len(message) > 3:
        siteid = message[2]
        room_title = siteid
        dev_action = message[3]

    # Otherwise extract site id from room information
    else:
        site_id, id_match = get_siteid(room)
        room_title = room.title
        dev_action = message[2]

    regexp = r"\d{4}"
    match = re.search(regexp, room_title)


    f1 = "srv01.txt"
    f2 = "srv02.txt"

    if match:
        site_id = match.group()
        response_data = bot_functions.diff_config_processing(dev_action, site_id)
    else:
        site_id = f"ERROR"
        response_data = f"ERROR:  Bot function was passed something that was not understood: {incoming_msg.text}.  " \
            f"\n\rIf you are not in an NT3 space please provide the 4 digit site code."

    # response_data += f"match is {match}\nsite_id is {site_id}\n room_title is {room_title}"

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = f"```\n{response_data}\n```"

    if not re.search(r'ERROR',response_data):
        response.markdown += f"\n The provided HTML file at the top of this response will provide a side by side " \
            f"color coded comparison."

        if match:
            response.files.append("./diff_report.html")

    return response
def check_crc_errors(incoming_msg):
    """See if any interfaces have CRC Errors
    """
    response = Response()
    device_crc_errors = crc_errors(device)

    if len(device_crc_errors) > 0:
        response.markdown = "The following interfaces have CRC errors:\n\n"
        for interface, counters in device_crc_errors.items():
            crc = counters["in_crc_errors"]
            response.markdown += "Interface {} has {} errors.".format(
                interface, crc)
    else:
        response.markdown = "No CRC Errors found"

    return response
Esempio n. 9
0
def greeting(incoming_msg):
    # Loopkup details about sender
    sender = bot.teams.people.get(incoming_msg.personId)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = "Hello {}, I'm a chat bot. ".format(sender.firstName)
    response.markdown += "See what I can do by asking for **/help**."
    return response
Esempio n. 10
0
def greeting(incoming_msg):
    # Loopkup details about sender

    sender = bot.teams.people.get(incoming_msg.personId)
    if incoming_msg.text == "what outstanding assignments do i have":
        answer = Response()
        answer.markdown = "Hey {}, Here is what you have to do".format(
            sender.firstName) + work2do(incoming_msg)

        return answer
    else:
        # Create a Response object and craft a reply in Markdown.
        response = Response()

        response.markdown = "Hello {}, I'm a chat bot. ".format(
            sender.firstName)
        response.markdown += "See what I can do by asking for **/help**."
        return response
Esempio n. 11
0
def aci_health(incoming_msg):
    """
    Sample function to check overall health of DevNet Always On Sandbox APIC via REST call.
    :param incoming_msg: The incoming message object from Teams
    :return: A text or markdown based reply
    """

    # Split incoming message into a list of its component so we can strip off Bot Name, command, and get to the
    # parameters.  In this case any additional parameter will be interpreted as debug.

    message = incoming_msg.text.split()


    url = "https://sandboxapicdc.cisco.com/api/aaaLogin.json"
    # payload = "{\"aaaUser\": {\"attributes\": {\"name\": \"admin\", \"pwd\": \"ciscopsdt\"}}}"

    # payload = {
    #    "aaaUser":{
    #       "attributes":{
    #          "name": os.getenv('APIC_USER'),
    #          "pwd": os.getenv('APIC_PWD')
    #       }
    #    }
    # }

    p1 = r'{"aaaUser": {"attributes": {"name": "'
    p2 = os.getenv('APIC_USER')
    p3 = r'", "pwd": "'
    p4 = os.getenv('APIC_PWD')
    p5 = r'"}}}'

    payload = p1 + p2 + p3 + p4 + p5

    c = bot_functions.rest_api_call(url, payload=payload, type="POST")
    cjson = c.json()

    status_code = c.status_code
    token = cjson['imdata'][0]['aaaLogin']['attributes']['token']

    url = "https://sandboxapicdc.cisco.com/api/node/mo/topology/HDfabricOverallHealth5min-0.json"
    payload = {}
    cookie = f"APIC-cookie={token}"
    health_obj = bot_functions.rest_api_call(url, payload=payload, cookie=cookie)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    health_obj_json = health_obj.json()
    response.markdown = f"### DevNet ACI Sandbox Fabric Health is: " \
                        f"\n\tDN:\t{health_obj_json['imdata'][0]['fabricOverallHealthHist5min']['attributes']['dn']}" \
                        f"\n\tMax:\t{health_obj_json['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthMax']}" \
                        f"\n\tMin:\t{health_obj_json['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthMin']}" \
                        f"\n\tAvg:\t{health_obj_json['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthAvg']}"

    if len(message) > 2:
        response.markdown += f"\nDebug: \n```{json.dumps(health_obj.json(), indent=4, sort_keys=True)}\n"

    return response
Esempio n. 12
0
def greeting(incoming_msg):
    # Loopkup details about sender
    sender = bot.teams.people.get(incoming_msg.personId)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = "Hello {}, I'm a chat bot.  \n".format(
        sender.displayName)
    response.markdown += "You can use:  \n /holidays : To list the manditory holidays  \n /floaters : To list the floaters  \n /helpdesk : To get helpdesk contact"
    return response
Esempio n. 13
0
def greeting(incoming_msg):
    # Loopkup details about sender
    sender = bot.teams.people.get(incoming_msg.personId)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = "Olá {}, eu sou o Smartz. Um dos robôs inteligentes desenvolvidos pela 2S baseado em Python".format(
        sender.firstName)
    response.markdown += "Você pode escolher em que posso ajudá-lo inserindo o comando: **/help**."
    return response
Esempio n. 14
0
def botgreeting(incoming_msg):

    sender = bot.teams.people.get(incoming_msg.personId)

    response = Response()
    #welome message
    response.markdown = "Hi {}, The Suite Life of Hack and Codey Bot here! ".format(
        sender.firstName)

    response.markdown += "Check out the bot features available by typing **/help**."
    return response
Esempio n. 15
0
def current_time(incoming_msg):
    """
    Sample function that returns the current time for a provided timezone
    :param incoming_msg: The incoming message object from Teams
    :return: A Response object based reply
    """

    reply = bot_functions.get_time(incoming_msg)

    response = Response()
    response.markdown = f"\n{reply}\n"

    return response
Esempio n. 16
0
def greeting(incoming_msg):
    # Loopkup details about sender
    sender = app.teams.people.get(incoming_msg.personId)
    room = app.teams.rooms.get(incoming_msg.roomId)
    # site_id, match = get_siteid(room)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = f"\nHello {sender.displayName} in room {room.title}! \nI'm your SparkBot and I'm here to help!\n "

    response.markdown += f"\nSee what I can do by asking for **/help**.\n"
    #response.markdown += f"\n===Start Data Structure Output\nincoming_msg:\n{incoming_msg} \nsender object:\n {sender}\nroom object:\n {room}\n===END Data Structure Output"
    return response
Esempio n. 17
0
def aci_faults(incoming_msg):
    """
    Sample function to check Fault Summary of DevNet Always On Sandbox APIC via REST call.
    :param incoming_msg: The incoming message object from Teams
    :return: A text or markdown based reply
    """

    # Split incoming message into a list of its component so we can strip off Bot Name, command, and get to the
    # parameters.  In this case any additional parameter will be interpreted as debug.

    message = incoming_msg.text.split()


    url = "https://sandboxapicdc.cisco.com/api/aaaLogin.json"

    p1 = r'{"aaaUser": {"attributes": {"name": "'
    p2 = os.getenv('APIC_USER')
    p3 = r'", "pwd": "'
    p4 = os.getenv('APIC_PWD')
    p5 = r'"}}}'

    payload = p1 + p2 + p3 + p4 + p5

    c = bot_functions.rest_api_call(url, payload=payload, type="POST")
    cjson = c.json()

    status_code = c.status_code
    token = cjson['imdata'][0]['aaaLogin']['attributes']['token']

    url = "https://sandboxapicdc.cisco.com/api/node/class/faultSummary.json?order-by=faultSummary.severity|desc&page=0&page-size=15"
    payload = {}
    cookie = f"APIC-cookie={token}"
    health_obj = bot_functions.rest_api_call(url, payload=payload, cookie=cookie)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    health_obj_json = health_obj.json()

    response.markdown = f"### DevNet ACI Sandbox Fabric Top 15 Faults: \nTotal Faults: {health_obj_json['totalCount']}"
    for line in health_obj_json['imdata']:
        response.markdown += f"\n#### {line['faultSummary']['attributes']['code']} " \
                             f"{line['faultSummary']['attributes']['cause']} " \
                             f"{line['faultSummary']['attributes']['severity']} " \
                             f"\n\t * {line['faultSummary']['attributes']['descr']}"

    # if len(message) > 2:
    #     response.markdown += f"\nDebug: \n```{json.dumps(health_obj.json(), indent=4, sort_keys=True)}```\n"

    return response
def greeting(incoming_msg):
    # Loopkup details about sender
    sender = bot.teams.people.get(incoming_msg.personId)

    # Retrieve Platform details
    platform = get_platform_info(device)

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = "Hello {}, I'm a friendly network switch.  ".format(
        sender.firstName)
    response.markdown += "My name is **{}**, and my serial number is **{}**. ".format(
        platform.device.name, platform.chassis_sn)
    response.markdown += "\n\nSee what I can do by asking for **/help**."
    return response
Esempio n. 19
0
def sdwan_report(incoming_msg):
    """
    Main function called by the Bot Menu to generate SD WAN report.
    This function calls the bot_functions.conn_matrix function for the actual processing

    :param incoming_msg:
    :return:
    """

    # Get sent message
    msg = ''
    message = incoming_msg.text.split()

    # Lookup details about sender
    sender = app.teams.people.get(incoming_msg.personId)
    room = app.teams.rooms.get(incoming_msg.roomId)

    # if length of split message is greater than 2 elements then the function is being passed a site id parameter
    if len(message) > 2:
        siteid = message[2]
        room_title = siteid
    # Otherwise extract site id from room information
    else:
        site_id, id_match = get_siteid(room)
        room_title = room.title

    regexp = r"\d{4}"
    match = re.search(regexp, room_title)

    if match:
        site_id = match.group()
        response_data = bot_functions.conn_matrix(site_id)
    else:
        site_id = f"ERROR"
        response_data = f"ERROR:  Bot function was passed something that was not understood: {incoming_msg.text}.  " \
            f"\n\rIf you are not in an NT3 space please provide the 4 digit site code."

    # response_data += f"match is {match}\nsite_id is {site_id}\n room_title is {room_title}"

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = f"\n{response_data}\n"

    if match:
        response.files = f"./{site_id}_sdwan_report.txt"

    return response
Esempio n. 20
0
def generate_report(incoming_msg):
    """
    Sample function to do some action.
    :param incoming_msg: The incoming message object from Teams
    :return: A text or markdown based reply
    """
    conn = sqlite3.connect('/home/toobradsosad/enablement-buddy/tracking.db')
    df = pd.read_sql_query(
        "SELECT activityType, description, duration, activityDate FROM tracking WHERE user='******';", conn)
    export_excel = df.to_excel(
        '/home/toobradsosad/enablement-buddy/exports/activities.xlsx',
        index=None,
        header=True)  #Don't forget to add '.xlsx' at the end of the path
    # export_csv = df.to_csv('/home/toobradsosad/enablement-buddy/exports/temp.csv', index = None, header=True) #Don't forget to add '.csv' at the end of the path
    num_enablements = df.shape[0]
    response = Response()
    response.markdown = "You've logged **" + str(
        num_enablements) + "** activities! Here's a report for your records."
    response.files = "/home/toobradsosad/enablement-buddy/exports/activities.xlsx"
    return response
Esempio n. 21
0
def debug_data(incoming_msg):
    # Loopkup details about sender
    sender = app.teams.people.get(incoming_msg.personId)
    room = app.teams.rooms.get(incoming_msg.roomId)

    regexp = r"test"
    room_title = room.title
    match = re.search(regexp, room_title, re.IGNORECASE)
    if match:
        is_test = "This is a TEST Space!"
    else:
        is_test = match.group()

    # Create a Response object and craft a reply in Markdown.
    response = Response()
    response.markdown = f"Hello {sender.displayName} in room {room.title}.\n "
    if match:
        response.markdown += f"\nThe Teams Space {is_test} is a Test space!\n"
    else:
        response.markdown += f"\nThis is Teams Space {is_test}\n"
    response.markdown += f"\nLets look at some DEBUG Info...\n"
    response.markdown += f"\n===Start Data Structure Output\nincoming_msg:\n{incoming_msg} \nsender object:\n {sender}\nroom object:\n {room}\n===END Data Structure Output"
    return response
def vlan_interfaces(incoming_msg):
    """Return the interfaces configured for a given vlan.
       Will look for a VLAN id as the FIRST contents following the command in
       the message.
    """
    response = Response()

    vlan_to_check = bot.extract_message("/vlan-interfaces",
                                        incoming_msg.text).strip()
    vlan_to_check = vlan_to_check.split()[0]

    # Get VLAN details from device
    vlans = get_vlans(device)

    # If the vlan provided is configured
    if vlan_to_check in list(vlans.keys()):
        # Reply back with the list of interfaces in a vlan
        response.markdown = "The following interfaces are configured for VLAN ID {}.\n\n".format(
            vlan_to_check)
        for interface in vlans[vlan_to_check]["interfaces"]:
            response.markdown += "* {}\n".format(interface)

    # Next get vlan list, and process for given vlan.
    return response
Esempio n. 23
0
 def test_response_markdown(self):
     r = Response()
     r.markdown = "**some markdown**"
     self.assertEqual(r.markdown, "**some markdown**")
Esempio n. 24
0
def greeting(input):
    sender = bot.teams.people.get(input.personId)
    response = Response()
    response.markdown = "Hello **{}**! Welcome to this chat bot!  \n".format(sender.displayName)
    response.markdown += "You can get a list of commands by typing **/help**."
    return response