added deck.chat modules
This commit is contained in:
@@ -0,0 +1,58 @@
|
|||||||
|
# deck.chat: T-Deck generic chat UI helper library for CircuitPython
|
||||||
|
# Depends on tdeck_repl for providing working input on T-Decks
|
||||||
|
#
|
||||||
|
# Created by Luxferre in 2025, released into public domain
|
||||||
|
|
||||||
|
# init the tdeck_repl input where applicable
|
||||||
|
try:
|
||||||
|
from tdeck_repl import input
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _echo(msg, state):
|
||||||
|
print(msg)
|
||||||
|
return state
|
||||||
|
|
||||||
|
class DeckChat:
|
||||||
|
def __init__(self, start_state={}, chat_prefix='> ', command_prefix='/'):
|
||||||
|
"""Init the chat class"""
|
||||||
|
self.command_prefix = command_prefix # prefix that commands start with
|
||||||
|
self.chat_prefix = chat_prefix # prefix to write before input
|
||||||
|
self.command_handlers = { # command handler storage
|
||||||
|
'default': _echo # echo handler by default
|
||||||
|
}
|
||||||
|
self.state = start_state # internal state object (impl-specific)
|
||||||
|
|
||||||
|
def command(self, command, handler):
|
||||||
|
"""
|
||||||
|
Register a new handler inside the chat instance.
|
||||||
|
The handler accepts a single parameter, which is the state object.
|
||||||
|
"""
|
||||||
|
cmd = command.strip().lower()
|
||||||
|
if cmd.startswith(self.command_prefix):
|
||||||
|
cmd = cmd[1:]
|
||||||
|
self.command_handlers[cmd] = handler
|
||||||
|
|
||||||
|
def _detect_command(self, msg):
|
||||||
|
"""
|
||||||
|
Split a chat line into the command (or None if none detected)
|
||||||
|
and the rest of the message.
|
||||||
|
"""
|
||||||
|
res = ('default', msg)
|
||||||
|
if msg.startswith(self.command_prefix):
|
||||||
|
parts = msg.split(maxsplit=1)
|
||||||
|
cmd, arg = parts[0].lower().strip()[1:], parts[1].strip() if len(parts) > 1 else None
|
||||||
|
if cmd in self.command_handlers:
|
||||||
|
res = (cmd, arg)
|
||||||
|
return res
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
"""Start the chat loop"""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
input_msg = input('\n' + self.chat_prefix).strip()
|
||||||
|
cmd, msg = self._detect_command(input_msg)
|
||||||
|
self.state = self.command_handlers[cmd](msg, self.state)
|
||||||
|
if self.state is None:
|
||||||
|
break
|
||||||
|
except KeyboardInterrupt: break
|
||||||
Reference in New Issue
Block a user