added deck.chat modules
This commit is contained in:
+17
-4
@@ -10,11 +10,10 @@ except:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def _echo(msg, state):
|
def _echo(msg, state):
|
||||||
print(msg)
|
return msg, state
|
||||||
return state
|
|
||||||
|
|
||||||
class DeckChat:
|
class DeckChat:
|
||||||
def __init__(self, start_state={}, chat_prefix='> ', command_prefix='/'):
|
def __init__(self, start_state={}, chat_prefix='> ', command_prefix='/', paginate=0):
|
||||||
"""Init the chat class"""
|
"""Init the chat class"""
|
||||||
self.command_prefix = command_prefix # prefix that commands start with
|
self.command_prefix = command_prefix # prefix that commands start with
|
||||||
self.chat_prefix = chat_prefix # prefix to write before input
|
self.chat_prefix = chat_prefix # prefix to write before input
|
||||||
@@ -22,6 +21,7 @@ class DeckChat:
|
|||||||
'default': _echo # echo handler by default
|
'default': _echo # echo handler by default
|
||||||
}
|
}
|
||||||
self.state = start_state # internal state object (impl-specific)
|
self.state = start_state # internal state object (impl-specific)
|
||||||
|
self.paginate_n = paginate # paginate the responses exceeding N>0 lines
|
||||||
|
|
||||||
def command(self, command, handler):
|
def command(self, command, handler):
|
||||||
"""
|
"""
|
||||||
@@ -46,13 +46,26 @@ class DeckChat:
|
|||||||
res = (cmd, arg)
|
res = (cmd, arg)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
def _paginate_output(self, text):
|
||||||
|
"""Splits output for small terminals."""
|
||||||
|
lines = text.split('\n')
|
||||||
|
for i in range(0, len(lines), self.paginate_n):
|
||||||
|
chunk = lines[i:i + self.paginate_n]
|
||||||
|
for line in chunk: print(line)
|
||||||
|
if i + self.paginate_n < len(lines):
|
||||||
|
input("-- Press Enter --")
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
"""Start the chat loop"""
|
"""Start the chat loop"""
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
input_msg = input('\n' + self.chat_prefix).strip()
|
input_msg = input('\n' + self.chat_prefix).strip()
|
||||||
cmd, msg = self._detect_command(input_msg)
|
cmd, msg = self._detect_command(input_msg)
|
||||||
self.state = self.command_handlers[cmd](msg, self.state)
|
output, self.state = self.command_handlers[cmd](msg, self.state)
|
||||||
|
if self.paginate_n > 0:
|
||||||
|
self._paginate_output(output.strip())
|
||||||
|
else:
|
||||||
|
print(output)
|
||||||
if self.state is None:
|
if self.state is None:
|
||||||
break
|
break
|
||||||
except KeyboardInterrupt: break
|
except KeyboardInterrupt: break
|
||||||
|
|||||||
Reference in New Issue
Block a user