本文整理汇总了Python中rivescript.RiveScript.sort_replies方法的典型用法代码示例。如果您正苦于以下问题:Python RiveScript.sort_replies方法的具体用法?Python RiveScript.sort_replies怎么用?Python RiveScript.sort_replies使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rivescript.RiveScript
的用法示例。
在下文中一共展示了RiveScript.sort_replies方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RiveScriptTestCase
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [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 sort_replies [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 sort_replies [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 sort_replies [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 sort_replies [as 别名]
#.........这里部分代码省略.........
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)
示例6: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [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: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [as 别名]
#!/usr/bin/python3
# Python 3 example
from pprint import pprint
from rivescript import RiveScript
rs = RiveScript(True)
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.
""")
user = "localuser"
while True:
msg = input("You> ")
if msg == '/quit':
quit()
elif msg == '/dump':
示例8: AdmiralBot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [as 别名]
class AdmiralBot(object):
"""Chatbot instance for Admiral."""
###
# Initialization and Configuration
###
def __init__(self, debug=False, config="settings.yml",
defaults="defaults.yml", log_console=True):
"""Initialize the Admiral chatbot.
Parameters:
* debug: Enable debug logging to the console.
* config: The configuration file to use (default settings.yml)
* defaults: The name of the default config file (defaults.yml)
* log_console: Write logs to the console (STDOUT) as well as to the
log file on disk (default True).
"""
# Configurable parameters.
self.debug = debug
self.config = config
self.config_defaults = defaults
# Internal state variables.
self.running = False # Whether we're up and running
self.c = dict() # App configuration
self.bots = dict() # Individual bot interfaces
self.rs = None # RiveScript brain
# Load the bot's config.
self.load_config()
self.log = Logger(filename=self.c.logging.status,
console=log_console,
log_format=self.c.logging.format)
if debug:
self.log.set_level(logging.DEBUG)
self.log.debug("Debug logging enabled.")
# Run post-config initialization routines.
self.setup()
def load_config(self):
"""Load the configuration file from disk."""
project_settings = YamlSettings(self.config_defaults, self.config,
default_section="admiral")
self.c = project_settings.get_settings()
###
# Initial Setup Steps
###
def setup(self):
"""Run the setup steps."""
self.log.info("Welcome to Admiral.")
# Initialize the RiveScript brain.
self.reload_brain()
# Scan through the interfaces and find active bots.
self.log.info("Setting up interfaces...")
for interface in self.c.interfaces:
if not interface.enabled:
continue
if interface.id in self.bots:
self.panic("Duplicate ID: you have two or more interfaces "
"that use the ID name `{}` in your bot settings. You "
"should pick a unique ID name for each interface!")
self.bots[interface.id] = interface
# Get the interface class.
module = Interface.import_interface(interface.interface)
self.bots[interface.id].inst = module(master=self)
self.bots[interface.id].inst.setup(interface)
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()
###
# Start, stop, run commands.
###
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
#.........这里部分代码省略.........
示例9: Flask
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [as 别名]
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!")
@app.route("/privacy")
def privacy():
return render_template('privacy.html')
示例10: onMessage
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [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)
示例11: RiveBot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [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()
示例12: interactive_mode
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import sort_replies [as 别名]
#.........这里部分代码省略.........
"'__END__' depending on how you ended your input.",
action="store_true",
)
parser.add_argument("--utf8", "-u",
help="Enable UTF-8 mode (default is disabled)",
action="store_true",
)
parser.add_argument("--log",
help="The path to a log file to send debugging output to (when debug "
"mode is enabled) instead of standard output.",
type=text_type,
)
parser.add_argument("--nostrict",
help="Disable strict mode (where syntax errors are fatal)",
action="store_true",
)
parser.add_argument("--depth",
help="Override the default recursion depth limit when fetching a reply "
"(default 50)",
type=int,
default=50,
)
parser.add_argument("path",
help="A directory containing RiveScript files (*.rive) to load.",
type=text_type,
# required=True,
)
args = parser.parse_args()
# Make the bot.
bot = RiveScript(
debug=args.debug,
strict=not args.nostrict,
depth=args.depth,
utf8=args.utf8,
log=args.log
)
bot.load_directory(args.path)
bot.sort_replies()
# Interactive mode?
if args.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(
" . . \n"
" .:...:: RiveScript Interpreter (Python)\n"
" .:: ::. Library Version: v{version}\n"
" ..:;;. ' .;;:.. \n"
" . ''' . Type '/quit' to quit.\n"
" :;,:,;: Type '/help' for more options.\n"
" : : \n"
"\n"
"Using the RiveScript bot found in: {path}\n"
"Type a message to the bot and press Return to send it.\n"
.format(version=bot.VERSION(), path=args.path)
)
while True:
msg = input("You> ")
if PY2:
# For Python 2 only: cast the message to Unicode.
msg = msg.decode("utf-8")
# 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)