本文整理汇总了Python中rivescript.RiveScript.reply方法的典型用法代码示例。如果您正苦于以下问题:Python RiveScript.reply方法的具体用法?Python RiveScript.reply怎么用?Python RiveScript.reply使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rivescript.RiveScript
的用法示例。
在下文中一共展示了RiveScript.reply方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RiveScriptTestCase
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
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)
示例2: bot_talk
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
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
示例3: bot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
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)
示例4: Aplicacion
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
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)
示例5: interactive_mode
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
def interactive_mode():
# Get command line options.
options, remainder = [], []
try:
options, remainder = getopt.getopt(sys.argv[1:], 'dju', ['debug',
'json',
'utf8',
'log=',
'strict',
'nostrict',
'depth=',
'help'])
except:
print("Unrecognized options given, try " + sys.argv[0] + " --help")
exit()
# Handle the options.
debug, depth, strict = False, 50, True
with_json, help, log = False, False, None
utf8 = False
for opt in options:
if opt[0] == '--debug' or opt[0] == '-d':
debug = True
elif opt[0] == '--strict':
strict = True
elif opt[0] == '--nostrict':
strict = False
elif opt[0] == '--json':
with_json = True
elif opt[0] == '--utf8' or opt[0] == '-u':
utf8 = True
elif opt[0] == '--help' or opt[0] == '-h':
help = True
elif opt[0] == '--depth':
depth = int(opt[1])
elif opt[0] == '--log':
log = opt[1]
# Help?
if help:
print("""Usage: rivescript [options] <directory>
Options:
--debug, -d
Enable debug mode.
--log FILE
Log debug output to a file (instead of the console). Use this instead
of --debug.
--json, -j
Communicate using JSON. Useful for third party programs.
--strict, --nostrict
Enable or disable strict mode (enabled by default).
--depth=50
Set the recursion depth limit (default is 50).
--help
Display this help.
JSON 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]
#.........这里部分代码省略.........
示例6: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
from rivescript import RiveScript
bot = RiveScript()
bot.load_directory("../public/brain/")
bot.load_directory("../public/brain/commands")
bot.sort_replies()
while True:
msg = input("You> ")
if msg == "/quit":
quit()
reply = bot.reply("localuser", msg)
print("Bot>", reply)
示例7: input
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
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.
""")
user = "localuser"
while True:
msg = input("You> ")
if msg == '/quit':
quit()
elif msg == '/dump':
rs._dump()
elif msg.startswith('/user '):
user = msg[6:].strip()
print("User changed to: " + user)
elif msg.startswith('/exec '):
eval(msg[6:].strip(), globals(), locals())
else:
reply = rs.reply(user, msg, False)
print("Bot>", reply)
# vim:expandtab
示例8: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
# 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
示例9: print
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
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()
if len(username) == 0:
print("You need to enter one! This script will exit now.")
sys.exit(1)
while True:
message = input("You> ").strip()
if len(message) == 0:
continue
if message.startswith("/quit"):
sys.exit(1)
reply = bot.reply(username, message)
print("Bot>", reply)
示例10: AdmiralBot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
#.........这里部分代码省略.........
def start(self):
"""Start up all the bots."""
if not self.running:
for name, bot in self.bots.items():
bot.inst.connect()
self.running = True
def run(self):
"""Start and run the bot's main loop."""
self.start()
while self.running:
for name, bot in self.bots.items():
bot.inst.do_one_loop()
###
# Event handlers.
###
def on_message(self, bot, username, remote_username, message):
"""Handle a message from an end user.
Parameters:
* bot: A reference to the interface that received the message.
* username: A unique name for the end user, typically with the
interface name prefixed, like `SLACK-kirsle`
* remote_username: The 'real' username, as the interface knows it.
* message: The text of the user's message.
"""
# Load this user's variables.
self.load_uservars(username)
# Get a reply for the user.
reply = self.rs.reply(username, message)
# Log the transaction.
self.log_chat(username, message, reply)
# Store the user's variables.
self.save_uservars(username)
# Send the response back.
# TODO: handle queueing and delayed responses.
bot.send_message(remote_username, reply)
def log_chat(self, username, message, reply):
"""Log the chat transaction to disk."""
# Each user gets their own log directory.
sanitized = re.sub(r'[^A-Za-z0-9_\[email protected]]+', '', username)
outdir = os.path.join("logs", "chats", sanitized)
outfile = os.path.join(outdir, "{}.log".format(sanitized))
if not os.path.isdir(outdir):
os.makedirs(outdir, mode=0o755)
self.log.info("[{}] {}".format(username, message))
self.log.info("[{}] {}".format(self.c.personality.name, reply))
with open(outfile, "a", encoding="utf-8") as fh:
today = datetime.datetime.today()
ts = today.strftime(self.c.logging.date_format)
fh.write("{today}\n"
"[{username}] {message}\n"
"[{bot}] {reply}\n\n".format(
today=ts,
username=username,
示例11: error_check
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
from rivescript import RiveScript
def error_check(reply):
if "[ERR:" in reply:
return "I'm sorry, something went wrong."
else:
return reply
bot = RiveScript()
bot.load_directory("./Ania")
bot.sort_replies()
user = "localuser"
while True:
msg = input('You> ')
if msg == '/quit':
quit()
reply = bot.reply(user, msg)
reply = error_check(reply)
print("{}{}{}{}".format("\033[96m", "Ania> ", reply, "\033[0m"))
示例12: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
#!/usr/bin/python
# -*- coding: utf-8 -*-
from rivescript import RiveScript
rs = RiveScript(utf8 = True)
rs.load_directory("./cerveau")
rs.sort_replies()
while True:
msg = raw_input("Vous > ")
if msg == '/quit':
quit()
reply = u"{0}".format(rs.reply("localuser", msg))
print(u"Aria > {0}".format(reply))
示例13: onMessage
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
def onMessage(self, messageProtocolEntity):
#send receipt otherwise we keep receiving the same message over and over
client = MongoClient()
db = client.data
if True:
rs=RiveScript()
rs.load_directory("./brain")
rs.sort_replies()
messageOut = ""
#print(messageProtocolEntity.getType() )
if messageProtocolEntity.getType() == "text":
#self.output(message.getBody(), tag = "%s [%s]"%(message.getFrom(), formattedDate))
"""
c = check()
para = messageProtocolEntity.getBody()
messageOut =c.func(para)
"""
messageOut = messageProtocolEntity.getBody()+' '
print(messageOut)
elif messageProtocolEntity.getType() == "media":
#self.getMediaMessageBody(messageProtocolEntity)
if self.onMediaMessage(messageProtocolEntity) == 1:
messageOut = "location code one "
elif self.onMediaMessage(messageProtocolEntity) == 2:
messageOut = "image code one "
elif self.onMediaMessage(messageProtocolEntity) == 3:
messageOut = "vcard recieved "
else:
messageOut = "location code zero "
else:
messageOut = "Unknown message type %s " % messageProtocolEntity.getType()
print(messageOut.toProtocolTreeNode())
messageOut=formstring(messageOut)
print(messageOut)
reply=rs.reply("localuser",messageOut)
receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant())
result = db.session.find({"from":messageProtocolEntity.getFrom()})
if result.count() == 1:
stime= datetime.datetime.now().hour*60+datetime.datetime.now().minute
print(stime)
if stime<=result[0]['expiry']:
#Customer in citizen
r = db.session.find({"from":messageProtocolEntity.getFrom()})
qid = r[0]['qid']
if messageProtocolEntity.getType() == "text":
db.query.update({"_id":qid},{"$set":{"text":db.query.find({"_id":qid})[0]['text']+[messageProtocolEntity.getBody()]}})
elif messageProtocolEntity.getMediaType() == "image":
db.query.update({"_id":qid},{"$set":{"image":db.query.find({"_id":qid})[0]['image']+[messageProtocolEntity.url]}})
elif messageProtocolEntity.getMediaType() == "location":
db.query.update({"_id":qid},{"$set":{"location":db.query.find({"_id":qid})[0]['location']+[[messageProtocolEntity.getLatitude(), messageProtocolEntity.getLongitude()]]}})
elif messageProtocolEntity.getMediaType() == "vcard":
db.query.update({"_id":qid},{"$set":{"vcard":db.query.find({"_id":qid})[0]['vcard']+[messageProtocolEntity.getCardData()]}})
else:
db.query.update({"_id":qid},{"$set":{"text":db.query.find({"_id":qid})[0]['text']+[messageProtocolEntity.getBody()]}})
outgoingMessageProtocolEntity = TextMessageProtocolEntity(reply,
to = messageProtocolEntity.getFrom())
self.toLower(receipt)
self.toLower(outgoingMessageProtocolEntity)
else:
r = db.session.find({"from":messageProtocolEntity.getFrom()})
qid = r[0]['qid']
db.session.remove({"from":messageProtocolEntity.getFrom()})
outgoingMessageProtocolEntity = TextMessageProtocolEntity("Your complaint id:"+str(qid)+"\n\nYour session has been expired!!\nYou need to register again.",to = messageProtocolEntity.getFrom())
self.toLower(receipt)
self.toLower(outgoingMessageProtocolEntity)
else:
outgoingMessageProtocolEntity = TextMessageProtocolEntity("I need your location to register you",
to = messageProtocolEntity.getFrom())
self.toLower(receipt)
self.toLower(outgoingMessageProtocolEntity)
示例14: RiveBot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
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()
示例15: interactive_mode
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import reply [as 别名]
def interactive_mode():
"""The built-in RiveScript Interactive Mode.
This feature of RiveScript allows you to test and debug a chatbot in your
terminal window. There are two ways to invoke this mode::
# By running the Python RiveScript module directly:
python rivescript eg/brain
# By running the shell.py in the source distribution:
python shell.py eg/brain
The only required command line parameter is a filesystem path to a directory
containing RiveScript source files (with the ``*.rive`` file extension).
Additionally, it accepts command line flags.
Parameters:
--utf8: Enable UTF-8 mode.
--json: Use JSON to communicate with the bot instead of plain text.
See the JSON Mode documentation below for advanced details.
--debug: Enable verbose debug logging.
--log (str): The path to a text file you want the debug logging to
be written to. This is to be used in conjunction with ``--debug``,
for the case where you don't want your terminal window to be flooded
with debug messages.
--depth (int): Override the recursion depth limit (default ``50``).
--nostrict: Disable strict syntax checking when parsing the RiveScript
files. By default a syntax error raises an exception and will
terminate the interactive mode.
--help: Show the documentation of command line flags.
path (str): The path to a directory containing ``.rive`` files.
**JSON Mode**
By invoking the interactive mode with the ``--json`` (or ``-j``) flag,
the interactive mode will communicate with you via JSON messages. This
can be used as a "bridge" to enable the use of RiveScript from another
programming language that doesn't have its own native RiveScript
implementation.
For example, a program could open a shell pipe to the RiveScript interactive
mode and send/receive JSON payloads to communicate with the bot.
In JSON mode, you send a message to the bot in the following format::
{
"username": "str username",
"message": "str message",
"vars": {
"topic": "random",
"name": "Alice"
}
}
The ``username`` and ``message`` keys are required, and ``vars`` is a
key/value object of all the variables about the user.
After sending the JSON payload over standard input, you can either close the
input file handle (send the EOF signal; or Ctrl-D in a terminal), or send
the string ``__END__`` on a line of text by itself. This will cause the bot
to parse your payload, get a reply for the message, and respond with a
similar JSON payload::
{
"status": "ok",
"reply": "str response",
"vars": {
"topic": "random",
"name": "Alice"
}
}
The ``vars`` structure in the response contains all of the key/value pairs
the bot knows about the username you passed in. This will also contain a
lot of internal data, such as the user's history and last matched trigger.
To keep a stateful session, you should parse the ``vars`` returned by
RiveScript and pass them in with your next request so that the bot can
remember them for the next reply.
If you closed the filehandle (Ctrl-D, EOF) after your input payload, the
interactive mode will exit after giving the response. If, on the other
hand, you sent the string ``__END__`` on a line by itself after your
payload, the RiveScript interactive mode will do the same after its response
is returned. This way, you can re-use the shell pipe to send and receive
many messages over a single session.
"""
parser = argparse.ArgumentParser(description="RiveScript interactive mode.")
parser.add_argument("--debug", "-d",
help="Enable debug logging within RiveScript.",
action="store_true",
)
parser.add_argument("--json", "-j",
help="Enable JSON mode. In this mode, you communicate with the bot by "
"sending a JSON-encoded object with keys 'username', 'message' and "
"'vars' (an object of user variables) over standard input, and "
"then close the input (^D) or send the string '__END__' on a line "
"by itself. The bot will respond with a similarly formatted JSON "
#.........这里部分代码省略.........