Example #1
0
    def test_configuration_2(self):

        logging.info('*** configure 2 ***')

        settings = {
            'bot': {
                'on_enter': 'Hello!',
                'on_exit': 'Bye!',
            },
            'space': {
                'title': 'Support channel',
            },
            'server': {
                'url': 'http://to.nowhere/',
                'trigger': '/trigger',
                'hook': '/hook',
                'binding': '0.0.0.0',
                'port': 8080,
            },
        }

        clear_env('CHANNEL_DEFAULT_PARTICIPANTS')
        context = Context(settings)
        engine = Engine(context=context, configure=True)
        self.assertEqual(engine.get('bot.on_enter'), 'Hello!')
        self.assertEqual(engine.get('bot.on_exit'), 'Bye!')
        self.assertEqual(engine.get('space.title'), 'Support channel')
        self.assertEqual(engine.get('space.participants'), None)
        self.assertEqual(engine.get('server.url'), 'http://to.nowhere/')
        self.assertEqual(engine.get('server.hook'), '/hook')
        self.assertEqual(engine.get('server.trigger'), '/trigger')
        self.assertEqual(engine.get('server.binding'), None)
        self.assertEqual(engine.get('server.port'), 8080)
Example #2
0
 def setUp(self):
     self.context = Context()
     self.engine = Engine(context=self.context, mouth=Queue())
     self.space = LocalSpace(context=self.context, ears=self.engine.ears)
     self.store = MemoryStore(context=self.context)
     self.machine = MyMachine()
     self.bot = MyBot(engine=self.engine)
     self.bot.machine = None
Example #3
0
 def setUp(self):
     self.context = Context(settings=my_settings)
     self.engine = Engine(context=self.context, mouth=Queue())
     self.engine.factory = TodoFactory(self.engine.get('todos.items', []))
     self.engine.bus = Bus(self.context)
     self.engine.bus.check()
     self.engine.publisher = self.engine.bus.publish()
     self.bot = self.engine.get_bot()
Example #4
0
 def setUp(self):
     self.context = Context()
     self.engine = Engine(context=self.context, ears=Queue(), mouth=Queue())
     self.engine.bus = Bus(self.context)
     self.engine.bus.check()
     self.engine.publisher = self.engine.bus.publish()
     self.space = LocalSpace(context=self.context, ears=self.engine.ears)
     self.store = MemoryStore(context=self.context)
     self.bot = ShellBot(engine=self.engine,
                         space=self.space,
                         store=self.store)
     self.channel = Channel({'id': '*id', 'title': '*title'})
Example #5
0
    def test_start(self):

        logging.info('*** start ***')

        engine = Engine(context=self.context)
        engine.space = LocalSpace(context=self.context)

        engine.start_processes = mock.Mock()
        engine.on_start = mock.Mock()

        engine.start()
        self.assertTrue(engine.ears is not None)
        self.assertTrue(engine.mouth is not None)
        self.assertTrue(engine.start_processes.called)
        self.assertTrue(engine.on_start.called)
Example #6
0
  interactions, and reproduce them at will.


For example, if you run this script under Linux or macOs::

    python hello_simulator.py

"""

import logging
import os

from shellbot import Engine, Context, Command


class Hello(Command):
    keyword = 'hello'
    information_message = u"Hello, World!"


if __name__ == '__main__':

    Context.set_logger(level=logging.INFO)

    engine = Engine(command=Hello(), type='local')

    engine.space.push(['help', 'hello', 'help help'])

    engine.configure()
    engine.run()
Example #7
0
 def setUp(self):
     self.engine = Engine(mouth=Queue())
     self.engine.configure()
     self.engine.shell = Shell(engine=self.engine)
     self.bot = MyBot(engine=self.engine)
Example #8
0
        "because the sky is green.", "for a disease.",
        "to be able to make toast explode.", "to know more about archeology."
    ]

    return u"{} {} {} {}".format(random.choice(s_nouns),
                                 random.choice(s_verbs),
                                 random.choice(p_nouns).lower(),
                                 random.choice(infinitives))


if __name__ == '__main__':

    Context.set_logger()

    os.environ['CHAT_ROOM_TITLE'] = 'Notifications'
    engine = Engine(type='spark', configure=True)

    bot = engine.get_bot(reset=True)  # create a group channel

    for index in range(7):  # send notifications to the channel
        bot.say(some_message())
        time.sleep(5)

    bot.say(u"Nothing more to say")

    print("Press Ctl-C to stop this program")
    try:
        while True:
            time.sleep(0.01)
    except KeyboardInterrupt:
        pass
Example #9
0
For example, if you run this script under Linux or macOs::

    python input.py

"""

import os

from shellbot import Engine, Context
from shellbot.machines import Input, Sequence

if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(type='local', command='shellbot.commands.input')
    engine.configure()  # ensure that all components are ready

    bot = engine.get_bot()  # get generic group channel for this bot

    order_id = Input(  # use a mask to validate input
        bot=bot,
        question="PO number please?",
        mask="9999A",
        on_answer="Ok, PO number has been noted: {}",
        on_retry="PO number should have 4 digits and a letter",
        on_cancel="Ok, forget about the PO number",
        key='order.id')

    description = Input(  # free form
        bot=bot,
Example #10
0
 def setUp(self):
     self.engine = Engine(mouth=Queue())
     self.bot = ShellBot(engine=self.engine, channel_id='*id')
     self.rocket = MyRocket(bot=self.bot)
Example #11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import logging
import mock
from multiprocessing import Process, Queue
import os
import sys

from shellbot import Context, Engine, Shell, Vibes
from shellbot.commands import Command

my_engine = Engine(mouth=Queue())
my_engine.shell = Shell(engine=my_engine)


class Bot(object):
    def __init__(self, engine):
        self.engine = engine

    def say(self, text, content=None, file=None):
        self.engine.mouth.put(Vibes(text, content, file))


my_bot = Bot(engine=my_engine)


class BaseTests(unittest.TestCase):
    def test_init(self):
Example #12
0
 def setUp(self):
     self.context = Context()
     self.engine = Engine(context=self.context, mouth=Queue())
     self.store = MemoryStore(context=self.context)
     self.bot = Bot(engine=self.engine)
Example #13
0
    def test_init(self):

        logging.info('*** init ***')

        engine = Engine(context=self.context)

        self.assertEqual(engine.context, self.context)
        self.assertTrue(engine.mouth is None)
        self.assertTrue(engine.speaker is not None)
        self.assertTrue(engine.ears is None)
        self.assertTrue(engine.listener is not None)
        self.assertTrue(engine.fan is None)
        self.assertTrue(engine.observer is not None)
        self.assertTrue(engine.registered is not None)
        self.assertEqual(engine.bots, {})
        self.assertFalse(engine.space is None)
        self.assertTrue(engine.server is None)
        self.assertTrue(engine.shell is not None)
        self.assertEqual(engine.driver, ShellBot)
        self.assertEqual(engine.machine_factory, None)
        self.assertEqual(engine.updater_factory, None)

        del engine

        engine = Engine(context=self.context,
                        type='local',
                        mouth='m',
                        ears='e',
                        fan='f')

        self.assertEqual(engine.context, self.context)
        self.assertEqual(engine.mouth, 'm')
        self.assertTrue(engine.speaker is not None)
        self.assertEqual(engine.ears, 'e')
        self.assertTrue(engine.listener is not None)
        self.assertEqual(engine.fan, 'f')
        self.assertTrue(engine.observer is not None)
        self.assertTrue(engine.registered is not None)
        self.assertEqual(engine.bots, {})
        self.assertTrue(engine.space is not None)
        self.assertTrue(engine.server is None)
        self.assertTrue(engine.shell is not None)
        self.assertEqual(engine.driver, ShellBot)
        self.assertEqual(engine.machine_factory, None)
        self.assertEqual(engine.updater_factory, None)

        del engine

        engine = Engine(context=self.context,
                        space=self.space,
                        mouth='m',
                        ears='e',
                        fan='f')

        self.assertEqual(engine.context, self.context)
        self.assertEqual(engine.mouth, 'm')
        self.assertTrue(engine.speaker is not None)
        self.assertEqual(engine.ears, 'e')
        self.assertTrue(engine.listener is not None)
        self.assertEqual(engine.fan, 'f')
        self.assertTrue(engine.observer is not None)
        self.assertTrue(engine.registered is not None)
        self.assertEqual(engine.bots, {})
        self.assertEqual(engine.space, self.space)
        self.assertTrue(engine.server is None)
        self.assertTrue(engine.shell is not None)
        self.assertEqual(engine.driver, ShellBot)
        self.assertEqual(engine.machine_factory, None)
        self.assertEqual(engine.updater_factory, None)

        del engine

        engine = Engine(
            context=self.context,
            driver=FakeBot,
            machine_factory=MachineFactory,
            updater_factory=MyUpdaterFactory,
        )

        self.assertEqual(engine.context, self.context)
        self.assertEqual(engine.mouth, None)
        self.assertTrue(engine.speaker is not None)
        self.assertEqual(engine.ears, None)
        self.assertTrue(engine.listener is not None)
        self.assertTrue(engine.fan is None)
        self.assertTrue(engine.observer is not None)
        self.assertTrue(engine.registered is not None)
        self.assertEqual(engine.bots, {})
        self.assertTrue(engine.space is not None)
        self.assertTrue(engine.server is None)
        self.assertTrue(engine.shell is not None)
        self.assertEqual(engine.driver, FakeBot)
        self.assertEqual(engine.machine_factory, MachineFactory)
        self.assertEqual(engine.updater_factory, MyUpdaterFactory)

        self.context.apply({
            'bot': {
                'name': 'testy',
                'version': '17.4.1'
            },
        })
        engine = Engine(context=self.context)
        self.assertEqual(engine.name, 'testy')
        self.assertEqual(engine.version, '17.4.1')

        del engine
Example #14
0
        direct_channel = self.engine.space.get_by_person(received.actor_label)
        if direct_channel:
            direct_bot = self.engine.get_bot(direct_channel.id)
            if direct_bot.machine and not direct_bot.machine.is_running:
                direct_bot.machine.restart()

    def on_leave(self, received):
        print("LEAVE: {}".format(received))
        bot = self.engine.get_bot(received.channel_id)
        bot.say(u"Bye bye '{}', we will miss you in '{}'".format(
            received.actor_label, bot.title))


if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(type='spark',
                    command='shellbot.commands.input',
                    machine_factory=MyFactory())
    os.environ['CHAT_ROOM_TITLE'] = '*dummy'
    engine.configure()

    handler = Handler(engine)
    engine.register('enter', handler)
    engine.register('exit', handler)
    engine.register('join', handler)
    engine.register('leave', handler)

    engine.run()
Example #15
0
 def setUp(self):
     self.context = Context()
     self.engine = Engine(context=self.context, mouth=Queue())
     self.space = LocalSpace(context=self.context)
     self.engine.space = self.space
Example #16
0
        bot.say(self.information_message, file=self.information_file)


class Batsuicide(Command):  # a command only for group channels
    keyword = 'suicide'
    information_message = u"Go back to Hell"
    in_direct = False

    def execute(self, bot, arguments=None, **kwargs):
        bot.say(self.information_message)
        bot.dispose()


if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(  # use Cisco Spark and load shell commands
        type='spark',
        commands=[Batman(), Batcave(),
                  Batsignal(), Batsuicide()])

    os.environ['BOT_ON_ENTER'] = 'You can now chat with Batman'
    os.environ['BOT_ON_EXIT'] = 'Batman is now quitting the room, bye'
    os.environ['CHAT_ROOM_TITLE'] = 'Chat with Batman'
    engine.configure()  # ensure that all components are ready

    engine.bond(reset=True)  # create a group channel for this example
    engine.run()  # until Ctl-C
    engine.dispose()  # delete the initial group channel
Example #17
0
            },
            {
                'label': u'Terminated',
                'message': u'Process is closed, yet conversation can continue',
            },
        ],
    }

    context = Context(settings)
    context.check('server.trigger', '/trigger')
    context.check('server.hook', '/hook')

    engine = Engine(  # use Cisco Spark and setup the environment
        type='spark',
        context=context,
        configure=True,
        commands=['shellbot.commands.step', 'shellbot.commands.close'],
        machine_factory=MyFactory(steps=context.get('process.steps')),
        ears=Queue(),
    )

    server = Server(context=context, check=True)  # set web front-end

    server.add_route(
        Notifier(queue=engine.ears,
                 notification={
                     'type': 'event',
                     'trigger': 'click'
                 },
                 route=context.get('server.trigger')))

    server.add_route(
Example #18
0
        else:
            bot.say('Such a lovely place...')
            time.sleep(5)
            bot.add_participant(received.actor_address)
            bot.say((u"{}, you can check out any time you like, "
                     u"but you can never leave!").format(received.actor_label),
                     content=(u'<@personEmail:{}|{}>, you can **check out '
                              u'any time you like**, '
                              u'but you can **never** leave!').format(
                                received.actor_address, received.actor_label))


if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(type='spark', commands=[Open(), Close(), Hotel()])

    os.environ['BOT_ON_ENTER'] = 'On a dark desert highway, cool wind in my hair...'
    os.environ['CHAT_ROOM_TITLE'] = 'Hotel California'
    engine.configure()  # ensure that all components are ready

    magic = Magic(engine=engine)  # monitor newcomers and leavers
    engine.register('join', magic)
    engine.register('leave', magic)

    engine.bond(reset=True)  # create a group channel for this example
    engine.run()  # until Ctl-C
    engine.dispose()  # delete the initial group channel
Example #19
0
import os

from shellbot import Engine, Context
from todos import TodoFactory

if __name__ == '__main__':

    Context.set_logger()

    factory = TodoFactory([
        'write down the driving question',
        'gather facts and related information',
        'identify information gaps and document assumptions',
        'formulate scenarios',
        'select the most appropriate scenario',
    ])

    engine = Engine(  # use Cisco Spark and load shell commands
        type='spark',
        commands=TodoFactory.commands())
    engine.factory = factory

    os.environ['BOT_ON_ENTER'] = 'What do you want to do today?'
    os.environ['CHAT_ROOM_TITLE'] = 'Manage todos'
    engine.configure()  # ensure that all components are ready

    engine.bond(reset=True)  # create a group channel for this example
    engine.run()  # until Ctl-C
    engine.dispose()  # delete the initial group channel
Example #20
0
    def setUp(self):
        self.engine = Engine()
        self.store = MemoryStore()
        self.bot = ShellBot(engine=self.engine, store=self.store)

        self.raw_steps = [
            {
                'label':
                u'Level 1',
                'message':
                u'Initial capture of information',
                'content':
                u'**Initial** `capture` of _information_',
                'file':
                "https://upload.wikimedia.org/wikipedia/en/c/c6/Bat-signal_1989_film.jpg",
            },
            {
                'label': u'Level 2',
                'message': u'Escalation to technical experts',
                'participants': '*****@*****.**',
            },
            {
                'label': u'Level 3',
                'message': u'Escalation to decision stakeholders',
                'participants': '*****@*****.**',
            },
            {
                'label': u'Terminated',
                'message': u'Process is closed, yet conversation can continue',
            },
        ]

        self.steps = [
            Step(
                {
                    'label':
                    u'Level 1',
                    'message':
                    u'Initial capture of information',
                    'content':
                    u'**Initial** `capture` of _information_',
                    'file':
                    "https://upload.wikimedia.org/wikipedia/en/c/c6/Bat-signal_1989_film.jpg",
                }, 1),
            Step(
                {
                    'label': u'Level 2',
                    'message': u'Escalation to technical experts',
                    'participants': '*****@*****.**',
                    'machine': FakeMachine(running=False),
                }, 2),
            Step(
                {
                    'label': u'Level 3',
                    'message': u'Escalation to decision stakeholders',
                    'participants': '*****@*****.**',
                    'machine': FakeMachine(running=False),
                }, 3),
            Step(
                {
                    'label': u'Terminated',
                    'message':
                    u'Process is closed, yet conversation can continue',
                    'machine': FakeMachine(running=False),
                }, 4),
        ]

        self.running_steps = [
            Step(
                {
                    'label':
                    u'Level 1',
                    'message':
                    u'Initial capture of information',
                    'content':
                    u'**Initial** `capture` of _information_',
                    'file':
                    "https://upload.wikimedia.org/wikipedia/en/c/c6/Bat-signal_1989_film.jpg",
                }, 1),
            Step(
                {
                    'label': u'Level 2',
                    'message': u'Escalation to technical experts',
                    'participants': '*****@*****.**',
                    'machine': FakeMachine(running=True),
                }, 2),
            Step(
                {
                    'label': u'Level 3',
                    'message': u'Escalation to decision stakeholders',
                    'participants': '*****@*****.**',
                    'machine': FakeMachine(running=True),
                }, 3),
            Step(
                {
                    'label': u'Terminated',
                    'message':
                    u'Process is closed, yet conversation can continue',
                    'machine': FakeMachine(running=True),
                }, 4),
        ]
Example #21
0
    thanks_content = u"Thanks for the upload of `{}`"

    def execute(self, bot, arguments=None, attachment=None, url=None, **kwargs):

        bot.say(content=self.feedback_content.format(
            arguments if arguments else 'World'))

        if attachment:
            bot.say(content=self.thanks_content.format(attachment))


if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(type='spark', command=Hello())

    os.environ['CHAT_ROOM_TITLE'] = 'Hello tutorial'
    os.environ['BOT_BANNER_TEXT'] = u"Type '@{} help' for more information"
    os.environ['BOT_BANNER_CONTENT'] = (u"Hello there! "
                                        u"Type ``@{} help`` at any time "
                                        u"and get more information "
                                        u"on available commands.")
    os.environ['BOT_BANNER_FILE'] = \
        "http://skinali.com.ua/img/gallery/19/thumbs/thumb_m_s_7369.jpg"

    engine.configure()  # ensure that all components are ready

    engine.bond(reset=True)  # create a group channel for this example
    engine.run()  # until Ctl-C
    engine.dispose()  # delete the initial group channel
Example #22
0
 def setUp(self):
     self.fan = Queue()
     self.engine = Engine(updater_factory=FakeFactory(), fan=self.fan)
     self.engine.set('bots.ids', ['*id1'])
Example #23
0
from planets import PlanetFactory
from planets.rocket import Rocket


class FlyingBot(ShellBot):  # add a rocket to each bot
    def on_init(self):
        self.rocket = Rocket(self)
        self.rocket.start()


if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(
        type='spark',  # use Cisco Spark and setup flying envronment
        commands=PlanetFactory.commands(),
        driver=FlyingBot)

    os.environ['BOT_ON_ENTER'] = 'Hello Buzz, welcome to Cape Canaveral'
    os.environ['BOT_ON_EXIT'] = 'Batman is now quitting the room, bye'
    os.environ['CHAT_ROOM_TITLE'] = 'Buzz flights'
    engine.configure()  # ensure that all components are ready

    engine.set('bot.store.planets', [
        'Mercury',
        'Venus',
        'Moon',
        'Mars',
        'Jupiter',
        'Saturn',
        'Uranus',
Example #24
0
"""

import logging
from multiprocessing import Process, Queue
import os

from shellbot import Engine, Context
from shellbot.updaters import FileUpdater


class UpdaterFactory(object):  # create one updater per group channel
    def get_updater(self, id):
        return FileUpdater(path='./updater-{}.log'.format(id))


if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(  # use Cisco Spark and setup audit environment
        type='spark',
        command='shellbot.commands.audit',
        updater_factory=UpdaterFactory())

    os.environ['CHAT_ROOM_TITLE'] = 'Audit tutorial'
    engine.configure()  # ensure all components are ready

    engine.bond(reset=True)  # create a group channel for this example
    engine.run()  # until Ctl-C
    engine.dispose()  # delete the initial group channel
Example #25
0
 def setUp(self):
     self.context = Context()
     self.engine = Engine(context=self.context, mouth=Queue())
     self.engine.configure()
     self.bot = Bot(engine=self.engine)
Example #26
0
# -*- coding: utf-8 -*-

import unittest
import gc
import json
import logging
import mock
from multiprocessing import Process, Queue
import os
import sys

from shellbot import Context, Engine, ShellBot, Shell
from shellbot.events import Message
from shellbot.updaters import Updater

my_engine = Engine()


class BaseTests(unittest.TestCase):
    def tearDown(self):
        collected = gc.collect()
        logging.info("Garbage collector: collected %d objects." % (collected))

    def test_init(self):

        logging.info('***** init')

        u = Updater()
        self.assertEqual(u.engine, None)

    def test_on_init(self):
Example #27
0
                       on_retry="PO number should have 4 digits and a letter",
                       on_answer="Ok, PO number has been noted: {}",
                       on_cancel="Ok, forget about the PO number",
                       key='order.id')

    def get_machine_for_group_channel(self, bot):
        return None

    def get_default_machine(self, bot):
        return None


if __name__ == '__main__':

    Context.set_logger()

    engine = Engine(
        type='spark',  # use Cisco Spark and setup the environment
        commands=[
            'shellbot.commands.input',
            'shellbot.commands.start',
            'shellbot.commands.close',
        ],
        machine_factory=MyMachineFactory())

    os.environ['CHAT_ROOM_TITLE'] = '*dummy'
    engine.configure()  # ensure that all components are ready

    print(u"Go to Cisco Spark and engage with the bot in a direct channel")
    engine.run()  # until Ctl-C