Beispiel #1
0
    def test_process_incoming_membership_check_sender_pass(self, m):
        m.get('https://api.ciscospark.com/v1/webhooks',
              json=MockSparkAPI.list_webhooks())
        m.post('https://api.ciscospark.com/v1/webhooks',
               json=MockSparkAPI.create_webhook())
        m.post('//api.ciscospark.com/v1/messages', json={})
        bot_email = "*****@*****.**"
        spark_token = "somefaketoken"
        bot_url = "http://fakebot.com"
        bot_app_name = "testbot"
        # Create a new bot
        bot = SparkBot(bot_app_name,
                       spark_bot_token=spark_token,
                       spark_bot_url=bot_url,
                       spark_bot_email=bot_email,
                       debug=True,
                       wh_resource="memberships",
                       wh_event="all")

        # Add new command
        bot.add_command('memberships',
                        '*',
                        self.check_membership)
        bot.testing = True
        self.app = bot.test_client()

        resp = self.app.post('/',
                             data=MockSparkAPI.incoming_membership_pass(),
                             content_type="application/json")
        self.assertEqual(resp.status_code, 200)
        print(resp.data)
        self.assertIn(b"success", resp.data)
Beispiel #2
0
    def setUp(self, m):
        m.get('https://api.ciscospark.com/v1/webhooks',
              json=MockSparkAPI.list_webhooks())
        m.post('https://api.ciscospark.com/v1/webhooks',
               json=MockSparkAPI.create_webhook())
        bot_email = "*****@*****.**"
        spark_token = "somefaketoken"
        bot_url = "http://fakebot.com"
        bot_app_name = "testbot"
        # Create a new bot
        bot = SparkBot(bot_app_name,
                       spark_bot_token=spark_token,
                       spark_bot_url=bot_url,
                       spark_bot_email=bot_email,
                       debug=True)

        # Add new command
        bot.add_command('/dosomething',
                        'help for do something',
                        self.do_something)
        bot.testing = True
        self.app = bot.test_client()
Beispiel #3
0
    def test_bad_config_raises_valueerror(self, m):
        with self.assertRaises(ValueError):
            m.get('https://api.ciscospark.com/v1/webhooks',
                  json=MockSparkAPI.list_webhooks_exist())
            m.post('https://api.ciscospark.com/v1/webhooks',
                   json=MockSparkAPI.create_webhook())

            bot_email = None
            spark_token = "somefaketoken"
            bot_url = "http://fakebot.com"
            bot_app_name = "testbot"
            # Create a new bot
            bot = SparkBot(bot_app_name,
                           spark_bot_token=spark_token,
                           spark_bot_url=bot_url,
                           spark_bot_email=bot_email,
                           debug=True)

            # Add new command
            bot.add_command('/dosomething',
                            'help for do something',
                            self.do_something)
            bot.testing = True
            self.app = bot.test_client()
    incomingtext = incoming_msg.text
    destroute = incomingtext.split(' ')[-1]
    ipaddr = incomingtext.split(' ')[-2]
    commstring = "./routefilter.sh " + ipaddr + " " + destroute
    output = subprocess.check_output(commstring, shell=True)
    #output = subprocess.check_output(subprocess.call(['./routefilter.sh', ipaddr, destroute]))
    output = output.decode('utf-8')
    return output


print(bot_app_name, spark_token, bot_url, bot_email)

# Create a new bot
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email,
               debug=True)

# Add new command
bot.add_command('/dosomething', 'help for do something', do_something)
bot.add_command('/demo', 'sample that allows spark message to be returned',
                ret_message)
bot.add_command(
    '/showping',
    'Returns ping results with packet count set to 1. Usage: /showping DESTINATION',
    ping_message)
bot.add_command(
    '/pingip',
    'checks if IP address is up/down (valid/invalid). Usage: /pingip DESTINATION',
    pingip_message)
Beispiel #5
0
# Get Bot Identity from Environment Variables
bot_email = os.getenv("SPARK_BOT_EMAIL")
spark_token = os.getenv("SPARK_BOT_TOKEN")
bot_url = os.getenv("SPARK_BOT_URL")
bot_app_name = os.getenv("SPARK_BOT_APP_NAME")


def chuck_joke(message):
    # Use urllib to get a random joke
    import urllib2
    import json

    response = urllib2.urlopen('http://api.icndb.com/jokes/random')
    joke = json.loads(response.read())["value"]["joke"]

    # Return the text of the joke
    return joke


# Create New Bot Object
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email)

# Teach bot to tell Chuck Norris Jokes
bot.add_command("/chuck", "Get a random Chuck Norris Joke", chuck_joke)

# Start Your Bot
bot.run(host='0.0.0.0', port=5000)
Beispiel #6
0
        # query (string)    The search term to query by.
        # offset (number)   For use to add pagenation for search results e.g. 10 to start with the 11th result. Default is 0.
        # limit (number)    The number of results to return. Default is 10.
        conn.request("GET", "/grocery/products/?query={}&offset={}&limit={}&".format(query,offset,limit), "{body}", tesco_headers)
        response = conn.getresponse()
        search_response_data = response.read()
        print(search_response_data)
        conn.close()
    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))

    # Turn raw JSON results into a string res_str
    res_str = json.loads(search_response_data)

    #return results nicely formatted with indent=2
    return "Grocery search results from devportal.tescolabs.com in raw JSON:\n ``` {}".format(json.dumps(res_str, indent=2))



# Create a new bot
tescobot = SparkBot(bot_app_name, spark_bot_token=spark_token,
               spark_bot_url=bot_url, spark_bot_email=bot_email, debug=True)

# Add new command
tescobot.add_command('/search', 'Look up a product on tesco.com', grocery_search)
tescobot.add_command('/jsearch', 'Return raw JSON output of grocery search [/jsearch query offset limit]', json_grocery_search)


# Run Bot
tescobot.run(host='0.0.0.0', port=5000)
def do_something(incoming_msg):
    """
    Sample function to do some action.
    :param incoming_msg: The incoming message object from Spark
    :return: A text or markdown based reply
    """
    return "i did what you said - {}".format(incoming_msg.text)


# Create a new bot
# Let's check if the user wants us to talk to a specific
# Spark API endpoint.  This can be useful if testing with an emulator
if os.getenv("SPARK_API_URL"):
    bot = SparkBot(bot_app_name,
                   spark_bot_token=spark_token,
                   spark_api_url=os.getenv("SPARK_API_URL"),
                   spark_bot_url=bot_url,
                   spark_bot_email=bot_email,
                   debug=True)
else:
    bot = SparkBot(bot_app_name,
                   spark_bot_token=spark_token,
                   spark_bot_url=bot_url,
                   spark_bot_email=bot_email,
                   debug=True)

# Add new command
bot.add_command('/dosomething', 'help for do something', do_something)

# Run Bot
bot.run(host='0.0.0.0', port=7000)
Beispiel #8
0
import os
from ciscosparkbot import SparkBot

# Retrieve required details from environment variables
bot_email = os.getenv("SPARK_BOT_EMAIL")
spark_token = os.getenv("SPARK_BOT_TOKEN")
bot_url = os.getenv("SPARK_BOT_URL")
bot_app_name = os.getenv("SPARK_BOT_APP_NAME")

# Create a new bot
# Let's check if the user wants us to talk to a specific
# Spark API endpoint.  This can be useful if testing with an emulator
if os.getenv("SPARK_API_URL"):
    bot = SparkBot(bot_app_name, spark_bot_token=spark_token,
                   spark_api_url=os.getenv("SPARK_API_URL"),
                   spark_bot_url=bot_url, spark_bot_email=bot_email, debug=True)
else:
    bot = SparkBot(bot_app_name, spark_bot_token=spark_token,
                   spark_bot_url=bot_url, spark_bot_email=bot_email, debug=True)

# Define the commands
# (note that /help is created automatically in the SparkBot framework)

def hello(incoming_msg, the_bot):
    """
    Respond to a /hello message
    :param incoming_msg: The incoming message object from Spark
    :param the_bot: The bot which includes our spark api instance
    :return: A text or markdown based reply, and the format to send it in
    """
Beispiel #9
0
import sys

# Retrieve required details from environment variables
bot_email = os.getenv("SPARK_BOT_EMAIL")
spark_token = os.getenv("SPARK_BOT_TOKEN")
bot_url = os.getenv("SPARK_BOT_URL")
bot_app_name = os.getenv("SPARK_BOT_APP_NAME")

if not bot_email or not spark_token or not bot_url or not bot_app_name:
    print("Missing Environment Variable.")
    sys.exit()

# Create a new bot
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email,
               debug=True)

# Add new command
if cico_common.meraki_support():
    bot.add_command('/meraki-health', 'Get health of Meraki environment.',
                    cico_meraki.get_meraki_health_html)
    bot.add_command('/meraki-check', 'Check Meraki user status.',
                    cico_meraki.get_meraki_clients_html)
if cico_common.spark_call_support():
    bot.add_command('/spark-health', 'Get health of Spark environment.',
                    cico_spark_call.get_spark_call_health_html)
    bot.add_command('/spark-check', 'Check Spark user status.',
                    cico_spark_call.get_spark_call_clients_html)
if cico_common.umbrella_support():
Beispiel #10
0
    current_relevance = get_app_relevance(scope, app)
    if current_relevance == relevance:
        return "{} is already set to {}; no action needed".format(
            app, current_relevance)
    else:
        task_id = set_app_relevance(scope, app, relevance)
        if task_id:
            message = "Success; {} has been set to {}".format(app, relevance)
    return message


#
# Initialize bot
#
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email)

# Add bot commands
bot.commands = dict()
bot.add_command('list policy tags',
                'This will list the policy tags configured on APIC EM',
                list_policy_tags)
bot.add_command(
    'set policy scope',
    'This will set the policy scope that you wish to modify for the session',
    set_policy_scope)
bot.add_command('current policy scope',
                'This will return the current policy scope for the session',
                current_policy_scope)
bot.add_command(
Beispiel #11
0
# Retrieve required details from environment variables
bot_email = os.getenv("*****@*****.**")
spark_token = os.getenv(
    "Njk3M2UwOWItMjJmYi00MjY3LWFhZDEtMjA5YjQyMWEzYTQ3ZjE0NWZkMzItMDdi")
bot_url = os.getenv("scoutst.herokuapp.com")
bot_app_name = os.getenv("HerokuBot")


def do_something(incoming_msg):
    """
    Sample function to do some action.
    :param incoming_msg: The incoming message object from Spark
    :return: A text or markdown based reply
    """
    return "i did what you said - {}".format(incoming_msg.text)


# Create a new bot
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email,
               debug=True)

# Add new command
bot.add_command('/dosomething', 'help for do something', do_something)

# Run Bot
bot.run(host='0.0.0.0', port=5000)
Beispiel #12
0
    """
    Sample function to do some action.
    :param incoming_msg: The incoming message object from Spark
    :return: A text or markdown based reply
    """
    return "i did what you said - {}".format(incoming_msg.text)


def ret_message(incoming_msg):
    m = Response()
    u = 'https://sayingimages.com/wp-content/uploads/'
    u = u + 'aaaaaalll-righty-then-alrighty-meme.jpg'
    m.files = u
    return m


# Create a new bot
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email,
               debug=True)

# Add new command
bot.add_command('/dosomething', 'help for do something', do_something)
bot.add_command('/demo', 'sampel that allows spark message to be returned',
                ret_message)

# Run Bot
bot.run(host='0.0.0.0', port=5000)
import os
from ciscosparkbot import SparkBot

# Get Bot Identity from Environment Variables
bot_email = os.getenv("SPARK_BOT_EMAIL")
spark_token = os.getenv("SPARK_BOT_TOKEN")
bot_url = os.getenv("SPARK_BOT_URL")
bot_app_name = os.getenv("SPARK_BOT_APP_NAME")


def chuck_joke(message):
    # Use urllib to get a random joke
    import urllib
    import json

    response = urllib.request.urlopen('http://api.icndb.com/jokes/random')
    joke = json.loads(response.read())["value"]["joke"]

    # Return the text of the joke
    return joke


# Create New Bot Object
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email)

# Start Your Bot
bot.run(host='0.0.0.0', port=5000)
Beispiel #14
0
    cron.start()
    job = cron.add_job(job_function, 'interval', minutes=5)
    print("Beginning Umbrella Log Collection...")
    job_function()

    # Shutdown your cron thread if the web process is stopped
    atexit.register(lambda: cron.shutdown(wait=False))

# ========================================================
# Initialize Bot - Register commands and start web server
# ========================================================

# Create a new bot
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=bot_url,
               spark_bot_email=bot_email,
               default_action="help",
               debug=True)

bot.add_command('help', 'Get help.', bot.send_help)
bot.remove_command('/echo')
bot.remove_command('/help')

# Add bot commands.
# If Meraki environment variables have been enabled, add Meraki-specifc commands.
if cico_common.meraki_support():
    bot.add_command('meraki-health', 'Get health of Meraki environment.',
                    cico_meraki.get_meraki_health_html)
    bot.add_command('meraki-check', 'Check Meraki user status.',
                    cico_meraki.get_meraki_clients_html)
# If Spark Call environment variables have been enabled, add Spark Call-specifc commands.
Beispiel #15
0
        .format(
            d['date'], d['flightNumber'], d['airportName1'],
            d['scheduledTime'], 'estimated **{}**'.format(d['estimatedTime'])
            if d['estimatedTime'] else '', d['terminal'], d['gate'],
            'Status **{}**'.format(d['statusName']) if d['statusName'] else '')
        for d in departures))
    return markup


ngrok = ngrokhelper.NgrokHelper(port=5000)
ngrok_url = ngrok.start()

# Create a new bot
bot = SparkBot(bot_app_name,
               spark_bot_token=spark_token,
               spark_bot_url=ngrok_url,
               spark_bot_email=bot_email,
               debug=True)

# Spark API
api = ciscosparkapi.CiscoSparkAPI(spark_token)

# Add new command
bot.add_command('/chuck', 'get Chuck Norris joke', get_joke)
bot.add_command('/traffic', 'show traffic cams',
                functools.partial(traffic, api))
bot.add_command('/tram',
                'show information about trams departing from MCEC stop',
                tram_info)
bot.add_command('/departures', 'show Melbourne airport departures', departures)