示例#1
0
def SearchGif(incoming_msg, search_term):
    """
    Function to retrieve a meme on brooklyn99.
    :param incoming_msg: The incoming message object from Teams
    ;param search_term: What to search for
    :return: A text or markdown based reply
    """

    # get the top 8 GIFs for the search term
    r = requests.get("https://api.tenor.com/v1/random?q=%s&key=%s&limit=%s" %
                     (search_term, apikey, lmt))

    if r.status_code == 200:
        top_gif = json.loads(r.content)
        print(json.dumps(top_gif, indent=4, sort_keys=True))
        for i in range(len(top_gif['results'])):
            url = top_gif['results'][i]['media'][0]['gif']['url']
            print("Found url ", i, ": ", url)
    else:
        top_gif = None

    response = Response()
    response.files = url

    return response
示例#2
0
def need_comic(incoming_msg):
    """
    Sample function that uses a Response object for more options.
    :param incoming_msg: The incoming message object from Teams
    :return: A Response object based reply
    """
    # Create a object to create a reply.
    response = Response()

    # Set the text of the reply.
    response.text = "Clearly its time for some comic relief"

    get_url = 'http://xkcd.com/info.0.json'

    get_response = requests.get(get_url)

    if get_response.status_code != 200:
        response.text = response.text + "\nEven the Comic Relief is tired!"
        raise Exception("Status code: " + str(get_response.status_code) + " for url: " + get_url)

    else:

        #response.files ="https://imgs.xkcd.com/comics/stack.png" 
        data = get_response.json()
        u = str(data["img"])
        response.files = u

    return response
示例#3
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
示例#4
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
示例#5
0
def capturescreen(incoming_msg):

    response = Response()
    datetime_object = datetime.datetime.now()
    print(datetime_object)
    response.text = "Here is your current Network Health as of " + str(
        datetime_object)

    #im1 = pyautogui.screenshot()
    #im1.save (r"C:\Users\aykorri\OneDrive - Cisco\Desktop\SE Hack\screenshot.png")

    path = (
        r"C:\Users\aykorri\OneDrive - Cisco\Desktop\SE Hack\screenshot.png")
    #titles = pygetwindow.getAllTitles()

    #x1, y1, width, height = pygetwindow.getWindowGeometry('How to screenshot a specific window using Python')
    #x2 = x1 + width
    #y2 = y1 + height

    #pyautogui.screenshot(path)

    #im = Image.open(path)
    #im = im.crop((x1, y1, x2, y2))
    #im.save(path)
    #im.show(path)

    u = r"C:\Users\aykorri\OneDrive - Cisco\Desktop\SE Hack\screenshot.png"
    response.files = u
    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
示例#7
0
def meme_func(incoming_msg):
    response = Response()
    for x in range(1):
        response.files = "https://media.giphy.com/media/jKWVkeDxquixAE1gDW/giphy.gif"  #jojo dora
        return response

    Response.text = "Food for your chronic meme addiction"
示例#8
0
def ret_message(incoming_msg):
    checkregistereduser(incoming_msg.personEmail, incoming_msg.roomId)
    # Create a object to create a reply.
    response = Response()
    response.text = "Happy birthday and have a nice day."
    response.files = "https://thumbs.dreamstime.com/b/happy-birthday-cheerful-colleagues-office-congratulate-vector-full-color-graphics-cute-characters-156278742.jpg"
    # response.files = "https://static.officeholidays.com/images/1280x853c/india-flag-01.jpg"
    return response
示例#9
0
def memberadded(api, incoming_msg):
    print(incoming_msg)
    response = Response()

    # Set the text of the reply.
    response.text = "Hi " + (
        (incoming_msg['data'])['personDisplayName']
    ) + ". On behalf of all of us, welcome onboard! We believe you will be a terrific asset to our team, and we look forward to your input! We are so excited about having you on our team!"
    return response
示例#10
0
def listhelpdeskemployees(incoming_msg):
    r = requests.get(URL + 'listhelpdeskemployees')
    data = json.loads(r.text)
    response = Response()
    response.text = ""
    for x in data.keys():
        response.text += "Email : " + data[x][0] + " Contact Number:  " + data[
            x][1] + " Name : " + x + '\n'
    return response
示例#11
0
def listbirthdays(incoming_msg):
    r = requests.get(URL + 'listbirthdays')
    data = json.loads(r.text)
    response = Response()
    response.text = ""
    for x in data.keys():
        response.text = x + " Birthday is  " + data[x][
            0] + " and team members are" + data[x][1] + '\n' + response.text
    return response
示例#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. ".format(sender.firstName)
    response.markdown += "See what I can do by asking for **/help**."
    return response
示例#13
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
示例#14
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
示例#15
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
示例#16
0
def listholidays(incoming_msg):
    r = requests.get(URL + 'listholidays')
    data = json.loads(r.text)
    response = Response()
    response.text = ""
    sorted_d = dict(
        sorted(data.items(), key=operator.itemgetter(1), reverse=True))
    for x in sorted_d.keys():
        response.text = data[x] + " " + x + '\n' + response.text
    return response
示例#17
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
示例#18
0
def ret_message(incoming_msg):
    """
    :param incoming_msg:
    :return:
    """
    response = Response()
    response.text = "Here's a fun little meme."

    u = "https://sayingimages.com/wp-content/uploads/"
    u = u + "aaaaaalll-righty-then-alrighty-meme.jpg"
    response.files = u
    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
示例#20
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
示例#21
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
示例#22
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
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 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
示例#26
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
示例#27
0
def ret_message(incoming_msg):
    """
    Sample function that uses a Response object for more options.
    :param incoming_msg: The incoming message object from Teams
    :return: A Response object based reply
    """
    # Create a object to create a reply.
    response = Response()

    # Set the text of the reply.
    response.text = "Here's a fun little meme."

    # Craft a URL for a file to attach to message
    u = "https://sayingimages.com/wp-content/uploads/"
    u = u + "aaaaaalll-righty-then-alrighty-meme.jpg"
    response.files = u
    return response
示例#28
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
示例#29
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
示例#30
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