當前位置: 首頁>>代碼示例>>Python>>正文


Python RiveScript.set_uservar方法代碼示例

本文整理匯總了Python中rivescript.RiveScript.set_uservar方法的典型用法代碼示例。如果您正苦於以下問題:Python RiveScript.set_uservar方法的具體用法?Python RiveScript.set_uservar怎麽用?Python RiveScript.set_uservar使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rivescript.RiveScript的用法示例。


在下文中一共展示了RiveScript.set_uservar方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: AdmiralBot

# 需要導入模塊: from rivescript import RiveScript [as 別名]
# 或者: from rivescript.RiveScript import set_uservar [as 別名]

#.........這裏部分代碼省略.........
                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,
                message=message,
                bot=self.c.personality.name,
                reply=reply,
                ))

    def load_uservars(self, username):
        """Load a user's variables from disk."""
        if not os.path.isdir("users"):
            os.mkdir("users")

        sanitized = re.sub(r'[^A-Za-z0-9_\[email protected]]+', '', username)
        filename = "users/{}.json".format(sanitized)
        if not os.path.isfile(filename):
            return

        with open(filename, "r", encoding="utf-8") as fh:
            data = fh.read()
            try:
                params = json.loads(data)
                print(params)
                for key, value in params.items():
                    if type(value) is str:
                        self.rs.set_uservar(username, key, value)
                        print("SET VAR:", username, key, value)
            except:
                pass

    def save_uservars(self, username):
        """Save a user's variables to disk."""
        if not os.path.isdir("users"):
            os.mkdir("users")

        sanitized = re.sub(r'[^A-Za-z0-9_\[email protected]]+', '', username)
        filename = "users/{}.json".format(sanitized)

        with open(filename, "w", encoding="utf-8") as fh:
            fh.write(json.dumps(self.rs.get_uservars(username)))

    ###
    # Utility/Misc functions.
    ###

    def panic(self, error):
        """Exit with a fatal error message."""
        self.log.error(error)
        raise RuntimeError(error)
開發者ID:aichaos,項目名稱:admiral,代碼行數:104,代碼來源:bot.py

示例2: RiveBot

# 需要導入模塊: from rivescript import RiveScript [as 別名]
# 或者: from rivescript.RiveScript import set_uservar [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()
開發者ID:flogiston,項目名稱:rivescript-python,代碼行數:91,代碼來源:example.py


注:本文中的rivescript.RiveScript.set_uservar方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。