Exemple #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)
Exemple #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()
Exemple #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()
    #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)
bot.add_command('/routefilter', 'invokes route-filter shell script.',
                routefilter_message)
bot.add_command(
    '/link',
    'Returns the URL that matches the link name. Usage: /link LINK_NAME',
Exemple #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)
Exemple #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)
    """
    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)
Exemple #8
0
def leave(incoming_msg, the_bot):
    """
    Respond to a /leave message
    :param incoming_msg: The incoming message object from Spark
    :param the_botot: The bot which includes our spark api instance
    :return: A text or markdown based reply, and the format to send it in
    """
    # lets get the info about who sent this message
    memberships = the_bot.spark.memberships.list(roomId=incoming_msg.roomId)
    my_id = the_bot.spark.people.me().id
    my_membership = ''
    for m in memberships:
        if m.personId == my_id:
            my_membership = m.id
            break

    if my_membership:
        the_bot.spark.messages.create(roomId=incoming_msg.roomId, text="OK.  I know when I'm not wanted...")
        the_bot.spark.memberships.delete(my_membership)
    else:
        return "I don't know how to leave!", "text"

# Add new commands
bot.add_command('/hello', 'say hello to our bot', hello)
bot.add_command('/whoami', 'tell me who i am', whoami)
bot.add_command('/echo', 'repeat this back to me', send_echo)
bot.add_command('/leave', 'bot should leave the room', leave)

# Run Bot
bot.run(host='0.0.0.0', port=7000)
Exemple #9
0
            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(
    'search app',
    'This will return applications matching search criteria; if scope already set, it will also return the applications relevance level',
    search_app)
bot.add_command(
    'set relevance',
    'This will set the relevance level for the provided app; ex. set relevance facebook Business-Relevant',
Exemple #10
0
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():
    bot.add_command('/umbrella-health', 'Get health of Umbrella envrionment.',
                    cico_umbrella.get_umbrella_health_html)
    bot.add_command('/umbrella-check', 'Check Umbrella user status.',
                    cico_umbrella.get_umbrella_clients_html)
bot.add_command('/health', 'Get health of entire environment.',
                cico_combined.get_health)
bot.add_command('/check', 'Get user status.', cico_combined.get_clients)
Exemple #11
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)
    # 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.
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.',
            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)

# Run Bot
bot.run(host='0.0.0.0', port=5000)