Skip to content

Commit

Permalink
Merge pull request aichaos#84 from aichaos/feature/sessions
Browse files Browse the repository at this point in the history
Add official Redis driver for RiveScript Sessions
  • Loading branch information
kirsle authored Feb 21, 2017
2 parents 4c3d82a + d158523 commit 3a8ad97
Show file tree
Hide file tree
Showing 13 changed files with 247 additions and 87 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
__pycache__
*.pyc
build/
dist/
*.egg-info/
6 changes: 6 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

Revision history for the Python package RiveScript.

## 1.14.5 - Feb 20 2017

- Bugfix when storing the user's `last_match` variable when a `%Previous` is
active (it was storing a regexp object and not a string), to help third party
session drivers (e.g. Redis) to work.

## 1.14.4 - Dec 14 2016

- Fix the `last_match()` function so that it returns `None` when there was no
Expand Down
21 changes: 21 additions & 0 deletions contrib/redis/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Noah Petherbridge

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
57 changes: 57 additions & 0 deletions contrib/redis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Redis Sessions for RiveScript

This module installs support for using a [Redis cache](https://redis.io/) to
store user variables for RiveScript.

```bash
pip install rivescript-redis
```

By default, RiveScript keeps user variables in an in-memory dictionary. This
driver allows for using a Redis cache instead. All user variables will then be
persisted to Redis automatically, which enables the bot to remember users after
a reboot.

## Quick Start

```python
from rivescript import RiveScript
from rivescript_redis import RedisSessionManager

# Initialize RiveScript like normal but give it the RedisSessionManager.
bot = RiveScript(
session_manager=RedisSessionManager(
# You can customize the key prefix: this is the default. Be sure to
# include a separator like '/' at the end so the keys end up looking
# like e.g. 'rivescript/username'
prefix='rivescript/',

# All other options are passed directly through to redis.StrictRedis()
host='localhost',
port=6379,
db=0,
),
)

bot.load_directory("eg/brain")
bot.sort_replies()

# Get a reply. The user variables for 'alice' would be persisted in Redis
# at the (default) key 'rivescript/alice'
print(bot.reply("alice", "Hello robot!"))
```

## Example

An example bot that uses this driver can be found in the
[`eg/sessions`](https://github.com/aichaos/rivescript-python/tree/master/eg/sessions)
directory of the `rivescript-python` project.

## See Also

* Documentation for [redis-py](https://redis-py.readthedocs.io/en/latest/),
the Redis client module used by this driver.

## License

This module is licensed under the same terms as RiveScript itself (MIT).
2 changes: 2 additions & 0 deletions contrib/redis/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
redis
rivescript
108 changes: 108 additions & 0 deletions contrib/redis/rivescript_redis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# RiveScript-Python
#
# This code is released under the MIT License.
# See the "LICENSE" file for more information.
#
# https://www.rivescript.com/

from __future__ import unicode_literals
import json
import redis
from rivescript.sessions import SessionManager

__author__ = 'Noah Petherbridge'
__copyright__ = 'Copyright 2017, Noah Petherbridge'
__license__ = 'MIT'
__status__ = 'Beta'
__version__ = '0.1.0'

class RedisSessionManager(SessionManager):
"""A Redis powered session manager for RiveScript."""

def __init__(self, prefix="rivescript/", *args, **kwargs):
"""Initialize the Redis session driver.
Apart from the ``prefix`` parameter, all other options are passed
directly to the underlying Redis constructor, ``redis.StrictRedis()``.
See the documentation of redis-py for more information. Commonly used
arguments are listed below for convenience.
Args:
prefix (string): the key to prefix all the Redis keys with. The
default is ``rivescript/``, so that for a username of ``alice``
the key would be ``rivescript/alice``.
host (string): Hostname of the Redis server.
port (int): Port number of the Redis server.
db (int): Database number in Redis.
"""
self.client = redis.StrictRedis(*args, **kwargs)
self.prefix = prefix
self.frozen = "frozen:" + prefix

def _key(self, username, frozen=False):
"""Translate a username into a key for Redis."""
if frozen:
return self.frozen + username
return self.prefix + username

def _get_user(self, username):
"""Custom helper method to retrieve a user's data from Redis."""
data = self.client.get(self._key(username))
if data is None:
return None
return json.loads(data.decode())

# The below functions implement the RiveScript SessionManager.

def set(self, username, new_vars):
data = self._get_user(username)
if data is None:
data = self.default_session()
data.update(new_vars)
self.client.set(self._key(username), json.dumps(data))

def get(self, username, key):
data = self._get_user(username)
if data is None:
return None
return data.get(key, "undefined")

def get_any(self, username):
return self._get_user(username)

def get_all(self):
users = self.client.keys(self.prefix + "*")
result = dict()
for user in users:
username = users.replace(self.prefix, "")
result[username] = self._get_user(username)
return result

def reset(self, username):
self.client.delete(self._key(username))

def reset_all(self):
users = self.client.keys(self.prefix + "*")
for user in users:
self.c.delete(user)

def freeze(self, username):
data = self._get_user(username)
if data is not None:
self.client.set(self._key(username, True), json.dumps(data))

def thaw(self, username, action="thaw"):
data = self.client.get(self.key(username, True))
if data is not None:
data = json.loads(data.decode())
if action == "thaw":
self.reset(username)
self.set(username, data)
self.c.delete(self.key(username, True))
elif action == "discard":
self.c.delete(self.key(username, True))
elif action == "keep":
self.reset(username)
self.set(username, data)
else:
raise ValueError("unsupported thaw action")
2 changes: 2 additions & 0 deletions contrib/redis/setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[metadata]
description-file = README.md
29 changes: 29 additions & 0 deletions contrib/redis/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# rivescript-python setup.py

import rivescript_redis
from setuptools import setup

setup(
name = 'rivescript_redis',
version = rivescript_redis.__version__,
description = 'Redis driver for RiveScript',
long_description = 'Stores user variables for RiveScript in a Redis cache',
author = 'Noah Petherbridge',
author_email = '[email protected]',
url = 'https://github.com/aichaos/rivescript-python',
license = 'MIT',
py_modules = ['rivescript_redis'],
keywords = ['rivescript'],
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
install_requires = [ 'setuptools', 'redis', 'rivescript' ],
)

# vim:expandtab
18 changes: 16 additions & 2 deletions eg/sessions/redis_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,25 @@
from __future__ import unicode_literals, print_function, absolute_import
from six.moves import input
import sys

# Manipulate sys.path to be able to import rivescript from this local git
# repository.
import os
sys.path.append(os.path.join(
os.path.dirname(__file__),
"..", "..",
))
sys.path.append(os.path.join(
os.path.dirname(__file__),
"..", "..",
"contrib", "redis",
))

from rivescript import RiveScript
from redis_storage import RedisSessionStorage
from rivescript_redis import RedisSessionManager

bot = RiveScript(
session_manager=RedisSessionStorage(),
session_manager=RedisSessionManager(),
)
bot.load_directory("../brain")
bot.sort_replies()
Expand Down
82 changes: 0 additions & 82 deletions eg/sessions/redis_storage.py

This file was deleted.

2 changes: 1 addition & 1 deletion eg/sessions/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
redis
rivescript-redis
2 changes: 1 addition & 1 deletion rivescript/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
__docformat__ = 'plaintext'

__all__ = ['rivescript']
__version__ = '1.14.4'
__version__ = '1.14.5'

from .rivescript import RiveScript
from .exceptions import (
Expand Down
2 changes: 1 addition & 1 deletion rivescript/brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def _getreply(self, user, msg, context='normal', step=0, ignore_object_errors=Tr
if match:
self.say("Found a match!")
matched = trig[1]
matchedTrigger = subtrig
matchedTrigger = user_side["trigger"]
foundMatch = True

# Get the stars!
Expand Down

0 comments on commit 3a8ad97

Please sign in to comment.