Ejemplo n.º 1
0
class RiveScriptTestCase(unittest.TestCase):
    """Base class for all RiveScript test cases, with helper functions."""

    def setUp(self, **kwargs):
        self.rs = None # Local RiveScript bot object
        self.username = "******"


    def tearDown(self):
        pass


    def new(self, code, **kwargs):
        """Make a bot and stream in the code."""
        self.rs = RiveScript(**kwargs)
        self.extend(code)


    def extend(self, code):
        """Stream code into the bot."""
        self.rs.stream(code)
        self.rs.sort_replies()


    def reply(self, message, expected):
        """Test that the user's message gets the expected response."""
        reply = self.rs.reply(self.username, message)
        self.assertEqual(reply, expected)


    def uservar(self, var, expected):
        """Test the value of a user variable."""
        value = self.rs.get_uservar(self.username, var)
        self.assertEqual(value, expected)
Ejemplo n.º 2
0
class ChatBot:
    def __init__(self, replies, **botvars):
        self.logs = io.StringIO()
        self.brain = RiveScript(debug=True, log=self.logs)

        self.brain.load_directory(replies)
        self.brain.sort_replies()

        for key, value in botvars.items():
            self.brain.set_variable(key, str(value))

    def get_response(self, message, name, ID):
        if self.brain.get_uservar(ID,
                                  "name") is None or self.brain.get_uservar(
                                      ID, "name") == "undefined":
            self.brain.set_uservar(ID, "name", name)

        try:
            return self.brain.reply(ID, message, False), None
        except Exception as exc:
            return None, exc
Ejemplo n.º 3
0
class RiveScriptTestCase(unittest.TestCase):
    """Base class for all RiveScript test cases, with helper functions."""
    def setUp(self, **kwargs):
        self.rs = None  # Local RiveScript bot object
        self.username = "******"

    def tearDown(self):
        pass

    def new(self, code, **kwargs):
        """Make a bot and stream in the code."""
        self.rs = RiveScript(**kwargs)
        self.extend(code)

    def extend(self, code):
        """Stream code into the bot."""
        self.rs.stream(code)
        self.rs.sort_replies()

    def reply(self, message, expected):
        """Test that the user's message gets the expected response."""
        reply = self.rs.reply(self.username, message)
        self.assertEqual(reply, expected)

    def uservar(self, var, expected):
        """Test the value of a user variable."""
        value = self.rs.get_uservar(self.username, var)
        self.assertEqual(value, expected)

    def assertContains(self, big, small):
        """Ensure everything from "small" is in "big" """
        self.assertIsInstance(small, big.__class__)
        if isinstance(small, dict):
            for k, v in small.items():
                self.assertIn(k, big)
                self.assertContains(big[k], v)
        elif isinstance(small, str):  # Strings are iterable, but let's not!
            self.assertEqual(big, small)
        else:  # pragma: no cover
            try:
                iterator = iter(small)
                for it in iterator:
                    self.assertIn(it, big)
            except TypeError:
                self.assertEqual(big, small)
Ejemplo n.º 4
0
class TestCase:
    def __init__(self, file, name, opts):
        self.file = file
        self.name = name
        self.rs = RiveScript(
            debug=opts.get("debug", False),
            utf8=opts.get("utf8", False),
        )
        self.username = opts.get("username", "localuser")
        self.steps = opts["tests"]

    def run(self):
        errors = False
        for step in self.steps:
            try:
                if "source" in step:
                    self.source(step)
                elif "input" in step:
                    self.input(step)
                elif "set" in step:
                    self.set(step)
                elif "assert" in step:
                    self.get(step)
                else:
                    self.warn("Unsupported test step")
            except Exception as e:
                self.fail(e)
                errors = True
                break

        sym = "×" if errors else "✓"
        print(sym + " " + self.file + "#" + self.name)

    def source(self, step):
        self.rs.stream(step["source"])
        self.rs.sort_replies()

    def set(self, step):
        self.rs.set_uservars(self.username, step["set"])

    def get(self, step):
        for key, expect in step["assert"].items():
            cmp = self.rs.get_uservar(self.username, key)
            if cmp != expect:
                raise AssertionError("Did not get expected user variable: {}\n"
                                     "Expected: {}\n"
                                     "     Got: {}".format(key, expect, cmp))

    def input(self, step):
        try:
            reply = self.rs.reply(self.username,
                                  step["input"],
                                  errors_as_replies=False)
        except RiveScriptError as e:
            error = re.sub(r'[\[\]]+', '', e.error_message)
            if error != step["reply"]:
                raise AssertionError(
                    "Got unexpected exception from reply() for input: {}\n"
                    "Expected: {}\n"
                    "     Got: {}".format(
                        step["input"],
                        repr(step["reply"]),
                        repr(error),
                    ))
            return

        if type(step["reply"]) is list:
            ok = False
            for candidate in step["reply"]:
                if candidate == reply:
                    ok = True
                    break

            if not ok:
                raise AssertionError(
                    "Did not get expected reply for input: {}\n"
                    "Expected one of: {}\n"
                    "            Got: {}".format(
                        step["input"],
                        repr(step["reply"]),
                        repr(reply),
                    ))
        else:
            if reply != step["reply"].strip():
                raise AssertionError(
                    "Did not get expected reply for input: {}\n"
                    "Expected: {}\n"
                    "     Got: {}".format(
                        step["input"],
                        repr(step["reply"]),
                        repr(reply),
                    ))

    def fail(self, e):
        banner = "Failed: {}#{}".format(self.file, self.name)
        banner += "\n" + "=" * len(banner) + "\n"
        print(banner + str(e) + "\n\n")

    def warn(self, message):
        print(message)
Ejemplo n.º 5
0
]
creds = ServiceAccountCredentials.from_json_keyfile_name(
    'Chatbot-Attendance-aeb274912a52.json', scope)

client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Attendance").sheet1

# Extract and print all of the values
attendance = sheet.get_all_records()
pp.pprint(attendance)

bot = RiveScript()
bot.load_directory("./brain")
bot.sort_replies()
id = "undefined"
name = "undefined"

while True:
    msg = str(input('You> '))
    print('Bot>' + bot.reply('localuser', msg))
    id = bot.get_uservar('localuser', 'id')
    name = bot.get_uservar('localuser', 'name')
    if (id != "undefined" and name != "undefined"):
        row = [id, name]
        index = len(attendance) + 2
        sheet.insert_row(row, index)
        break