本文整理汇总了Python中rivescript.RiveScript类的典型用法代码示例。如果您正苦于以下问题:Python RiveScript类的具体用法?Python RiveScript怎么用?Python RiveScript使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RiveScript类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bot
class bot():
"""This is a bare minimal example for how to write your own RiveScript bot!
For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.
example.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.
Type /quit when you're done to exit this example.
"""
def __init__(self):
self.currentOperation = None
self.rs = RiveScript()
self.rs.load_directory(os.path.dirname(__file__) + "/rep_src")
self.rs.sort_replies()
def sanitizeUserQuery(self, userQuery):
return userQuery
def identifyOperation(self, userQuery):
"""
function identifyOperation(string: userQuery)
Output: ([keywords_in_input], [action_in_input])
"""
userQuery = self.sanitizeUserQuery(userQuery)
queryTokens = nltk.word_tokenize(userQuery)
pos = nltk.pos_tag(queryTokens)
keywords = []
verbs = []
adjective = []
for w in pos:
if w[1] == 'NN' or w[1] == 'NNP':
keywords.append(str(w[0]))
if w[1] == 'VB' or w[1] == 'VBD' or w[1] == 'VBN':
verbs.append(w[0])
if w[1] == 'JJ':
adjective.append(w[0])
# print(str(keywords).rsplit() + " " + str(verbs).rsplit() + " " + str(adjective).rsplit())
return (keywords, verbs, adjective)
def reply(self, user, msg):
# t = self.identifyOperation(msg)
# print(' '.join(t[0] + t[1] + t[2]))
return self.rs.reply(user, msg)
示例2: reload_brain
def reload_brain(self):
"""(Re)load the RiveScript brain for the bot."""
self.log.info("Loading RiveScript brain from {}".format(
self.c.personality.replies
))
self.rs = RiveScript(
debug=self.c.debug.rivescript,
utf8=True,
)
self.rs.load_directory(self.c.personality.replies)
self.rs.sort_replies()
示例3: Agente
def Agente(self):
self.agente = RiveScript()
self.agente.load_directory("./recursos")
self.agente.sort_replies()
self.lector = Dispatch("SAPI.SpVoice")
if time.localtime().tm_hour < 12:
self.agente.set_variable("time", "dia")
else:
if time.localtime().tm_hour < 18:
self.agente.set_variable("time", "tarde")
else:
self.agente.set_variable("time", "noche")
示例4: RiveScriptTestCase
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 = "localuser"
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)
示例5: bot_talk
def bot_talk():
from rivescript import RiveScript
import sys, os
bot = RiveScript(utf8=True)
bot.load_directory("/home/mate/Downloads/web2py/applications/saria/static/riverscript/brain/")
#bot.load_directory("/home/relsi/Projetos/Web2py/pris/applications/saria/static/riverscript/brain")
bot.sort_replies()
msg = request.post_vars.chat_text
reply = bot.reply("localuser", msg.decode('utf-8'))
return reply
示例6: __init__
def __init__(self, script_dir, user, ss, debug=False):
self._user = user
self._redirect = None
# init RiveScript
self._rs = RiveScript(debug=debug)
self._rs.load_directory(script_dir)
self._rs.sort_replies()
# restore session
if isinstance(ss, SessionStore):
self._ss = ss
else:
raise RuntimeError("RiveBot init error: provided session store object is not a SessionStore instance.")
self._restore_session()
# register event callbacks
self._rs.on('topic', self._topic_cb)
self._rs.on('uservar', self._uservar_cb)
示例7: RiveScript
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 rivescript_redis import RedisSessionManager
bot = RiveScript(
session_manager=RedisSessionManager(),
)
bot.load_directory("../brain")
bot.sort_replies()
print("""RiveScript Redis Session Storage Example
This example uses a Redis server to store user variables. For the sake of the
example, choose a username to store your variables under. You can re-run this
script with the same username (or a different one!) and verify that your
variables are kept around!
Type '/quit' to quit.
""")
username = input("What is your username? ").strip()
示例8: Aplicacion
class Aplicacion(wx.Frame):
def __init__(self):
self.Ventana()
self.Agente()
# self.Respuesta("begin")
def Agente(self):
self.agente = RiveScript()
self.agente.load_directory("./recursos")
self.agente.sort_replies()
self.lector = Dispatch("SAPI.SpVoice")
if time.localtime().tm_hour < 12:
self.agente.set_variable("time", "dia")
else:
if time.localtime().tm_hour < 18:
self.agente.set_variable("time", "tarde")
else:
self.agente.set_variable("time", "noche")
def Ventana(self):
wx.Frame.__init__(self, None, style= wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)
self.panel = wx.Panel(self)
self.texto = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_READONLY, size= (293,350), pos = (5,5))
self.linea = wx.TextCtrl(self.panel, style=wx.TE_NO_VSCROLL | TE_PROCESS_ENTER, size= (200,50), pos = (10,365))
self.boton = wx.BitmapButton(self.panel, bitmap = wx.Bitmap("recursos\_enviar.png"), pos = (220, 360))
self.etiqueta = wx.StaticText(self.panel, label = "Proyecto Inteligencia Artificial - ULA, A2012 ", pos = (5, 425))
self.Bind(wx.EVT_TEXT_ENTER, self.Pregunta, self.linea)
self.Bind(wx.EVT_BUTTON, self.Pregunta, self.boton)
self.linea.SetFocus()
self.SetTitle("Representante de Atencion al Cliente")
self.SetSize((320,480))
self.Centre()
self.Show()
def Pregunta(self, evento):
self.texto.AppendText(" "+ str(self.linea.GetValue()).capitalize() + "\n")
self.Respuesta(self.linea.GetValue().__str__())
def Respuesta(self, texto):
bot = self.agente.reply("rac", texto)
self.linea.Clear()
self.texto.AppendText(str(bot) + "\n")
self.lector.Speak(bot)
示例9: RiveBot
class RiveBot(object):
"""An example RiveScript bot using callbacks to manage user session data.
This example assumes single user per RiveScript instance and as
such it's suitable for use in stateless services (e.g. in web apps
receiving webhooks). Just init, get reply and teardown. Of course,
it will also work in RTM implementations with custom longer-lived
bot threads.
Session state is persisted to a single JSON file. This wouldn't be
thread-safe in a concurrent environment (e.g. web server). In such
case it would be recommended to subclass SessionStore and implement
database persistence (preferably via one of great Python ORMs such
as SQLAlchemy or peewee).
"""
def __init__(self, script_dir, user, ss, debug=False):
self._user = user
self._redirect = None
# init RiveScript
self._rs = RiveScript(debug=debug)
self._rs.load_directory(script_dir)
self._rs.sort_replies()
# restore session
if isinstance(ss, SessionStore):
self._ss = ss
else:
raise RuntimeError("RiveBot init error: provided session store object is not a SessionStore instance.")
self._restore_session()
# register event callbacks
self._rs.on('topic', self._topic_cb)
self._rs.on('uservar', self._uservar_cb)
def _topic_cb(self, user, topic, redirect=None):
"""Topic callback.
This is a single-user-per-rive (stateless instance) scenario; in a multi-user
scenario within a single thread, callback functions should delegate the
execution to proper user session objects.
"""
log.debug("Topic callback: user={}, topic={}, redirect={}".format(user, topic, redirect))
self._session.set_topic(topic, redirect)
def _uservar_cb(self, user, name, value):
"""Topic callback. See comment for `_topic_cb()`"""
log.debug("User variable callback: user={}, name={}, value={}".format(user, name, value))
self._session.set_variable(name, value)
def _restore_session(self):
self._session = self._ss.load(self._user)
# set saved user variables
for name, value in self._session.variables():
self._rs.set_uservar(self._user, name, value)
# set saved topic
topic = self._session.get_topic()
if topic:
if '/' in topic:
topic, self._redirect = topic.split('/')
self._rs.set_topic(self._user, topic)
def _save_session(self):
self._ss.save(self._session)
def run(self):
log.info("RiveBot starting...")
if self._redirect:
# Repeat saved redirect so that the user gets the context
# after session restart.
redir_reply = self._rs.redirect(self._user, self._redirect)
print("bot> Welcome back!")
print("bot>", redir_reply)
while True:
msg = raw_input("{}> ".format(self._user))
if msg == '/quit':
self.stop()
break
reply = self._rs.reply(self._user, msg)
print("bot>", reply)
def stop(self):
log.info("RiveBot shutting down...")
print("\nbot> Bye.")
self._save_session()
示例10: new
def new(self, code, **kwargs):
"""Make a bot and stream in the code."""
self.rs = RiveScript(**kwargs)
self.extend(code)
示例11: interactive_mode
#.........这里部分代码省略.........
In JSON mode, input and output is done using JSON data structures. The
format for incoming JSON data is as follows:
{
'username': 'localuser',
'message': 'Hello bot!',
'vars': {
'name': 'Aiden'
}
}
The format that would be expected from this script is:
{
'status': 'ok',
'reply': 'Hello, human!',
'vars': {
'name': 'Aiden'
}
}
If the calling program sends an EOF signal at the end of their JSON data,
this script will print its response and exit. To keep a session going,
send the string '__END__' on a line by itself at the end of your message.
The script will do the same after its response. The pipe can then be used
again for further interactions.""")
quit()
# Given a directory?
if len(remainder) == 0:
print("Usage: rivescript [options] <directory>")
print("Try rivescript --help")
quit()
root = remainder[0]
# Make the bot.
bot = RiveScript(
debug=debug,
strict=strict,
depth=depth,
utf8=utf8,
log=log
)
bot.load_directory(root)
bot.sort_replies()
# Interactive mode?
if with_json:
# Read from standard input.
buffer = ""
stateful = False
while True:
line = ""
try:
line = _input()
except EOFError:
break
# Look for the __END__ line.
end = re.match(r'^__END__$', line)
if end:
# Process it.
stateful = True # This is a stateful session
json_in(bot, buffer, stateful)
buffer = ""
continue
else:
buffer += line + "\n"
# We got the EOF. If the session was stateful, just exit,
# otherwise process what we just read.
if stateful:
quit()
json_in(bot, buffer, stateful)
quit()
print("""RiveScript Interpreter (Python) -- Interactive Mode"
---------------------------------------------------"
rivescript version: %s
Reply Root: %s
You are now chatting with the RiveScript bot. Type a message and press Return"
to send it. When finished, type '/quit' to exit the program."
Type '/help' for other options."
""" % (str(bot.VERSION()), root))
while True:
msg = _input("You> ")
# Commands
if msg == '/help':
print("> Supported Commands:")
print("> /help - Displays this message.")
print("> /quit - Exit the program.")
elif msg == '/quit':
exit()
else:
reply = bot.reply("localuser", msg)
print("Bot>", reply)
示例12: RiveScript
from rivescript import RiveScript
bot = RiveScript(utf8=True)
bot.load_directory("./replies")
bot.sort_replies()
示例13: RiveScript
#!/usr/bin/python3
# Python 3 example
from rivescript import RiveScript
rs = RiveScript()
rs.load_directory("./brain")
rs.sort_replies()
print("""This is a bare minimal example for how to write your own RiveScript bot!
For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.
example3.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.
Type /quit when you're done to exit this example.
""")
while True:
msg = input("You> ")
if msg == '/quit':
quit()
reply = rs.reply("localuser", msg)
print("Bot>", reply)
# vim:expandtab
示例14: RiveScript
#!/usr/bin/python
from rivescript import RiveScript
rs = RiveScript()
rs.load_file("replies.rive")
rs.sort_replies()
print """This is a bare minimal example for how to write your own RiveScript bot!
For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.
example.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.
Type /quit when you're done to exit this example.
"""
while True:
msg = raw_input("You> ")
if msg == '/quit':
quit()
reply = rs.reply("localuser", msg)
print "Bot>", reply
# vim:expandtab
示例15: Flask
from rivescript import RiveScript
from bot_interface.bot_interface import BotInterface
from message_processor.message_processor import MessageProcessor, ExternalApiParser
from nyt_interface.nyt_interface import NytimesApi
app = Flask(__name__)
mongo = PyMongo(app)
app.config.from_object("config.DevelopmentConfig")
app.config.from_pyfile("local.cfg")
bot = BotInterface(app.config['FB_API_VERSION'], app.config['FB_ACCESS_TOKEN'])
nyt_api = NytimesApi(app.config['NYT_KEY'])
rive = RiveScript()
rive.load_directory(
os.path.join(os.path.dirname(__file__), "message_processor", "rivescripts")
)
rive.sort_replies()
# external_api_parser = ExternalApiParser(app.config['WIT_KEY'], app.config['API_AI_KEY'], bot, nyt_api)
external_api_parser = ExternalApiParser(app.config['WIT_KEY'], rive, bot, nyt_api, mongo)
msgproc = MessageProcessor(bot, external_api_parser, app.config)
@app.route("/")
def index():
return render_template('messenger.html')
# return success(status=200, message="Hello world from climatechangebot!")