Multi-Channel Message Router with Pluggable Responders
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate a command-driven chat engine that dispatches messages to registered responders, keeps per-channel logs and per-responder state, and returns the resulting logs.
You are building a small in-memory chat engine and a driver function that runs a scripted sequence of commands against it. The engine routes each incoming message to every registered responder ("bot"), and keeps an independent history for each channel.
Implement simulate_chat(commands, params). The two lists have the same length; commands[i] is the name of a command and params[i] is the list of its arguments. Process the commands in order and return a list with one result per command.
Commands
register_counter, params [bot_id]
Registers a counter bot under the identifier bot_id. Result: None.
register_keyword, params [bot_id, keyword, reply]
Registers a keyword bot under bot_id. Result: None.
send, params [channel_id, sender, text]
Delivers a user message to the channel channel_id, then returns the full log of that channel (see below).
get_log, params [channel_id]
Returns the current log of the channel without changing anything.
Behavior
- Bots are global: every registered bot sees messages from every channel. Bots are consulted in the order they were registered.
- A channel springs into existence the first time a
sendtargets it. Before that,get_logon it returns an empty list[], andget_logmust not create the channel. - When a message is sent, first append the user message to the channel's log. Then, for each registered bot in registration order, give the bot the original user message together with that bot's own state for that channel. If the bot produces a reply, append the reply to the log immediately. Bot replies are not passed to other bots.
- Each bot's state is kept separately per
(channel, bot_id)pair, starting out empty. A bot registered after a channel already exists simply starts with empty state in that channel. - Registering a bot never changes any existing log.
Bot types
Counter bot. It replies to every message. It keeps a count in its state for the channel, starting at 0. On each message it increments the count first, then replies with sender "counter" and text "Message N: T", where N is the new count and T is the text of the user message.
Keyword bot. It is configured with a keyword and a reply. It replies only if keyword appears in the message text, compared case-insensitively (substring match). The reply has sender "keyword" and text equal to reply. Otherwise it stays silent. It does not need any state.
Log format
A log is a list of dictionaries, one per entry in chronological order, each of the form {"sender": <str>, "text": <str>}. The result of send and get_log is a fresh list of such dictionaries.
An unrecognized command name should raise ValueError.
Constraints
len(commands) == len(params), and at most a few thousand commands.bot_id,channel_id,sender,text,keyword,replyare strings.- Multiple bots may be registered; the same bot type may be registered more than once with different ids.
- Single-threaded, in-memory processing only.
Examples
Example 1
Input: simulate_chat(['register_counter', 'send', 'send', 'send', 'get_log'], [['counter-1'], ['general', 'alice', 'hello'], ['general', 'bob', 'again'], ['dm', 'alice', 'private'], ['general']])
Output: [None, [{'sender': 'alice', 'text': 'hello'}, {'sender': 'counter', 'text': 'Message 1: hello'}], [{'sender': 'alice', 'text': 'hello'}, {'sender': 'counter', 'text': 'Message 1: hello'}, {'sender': 'bob', 'text': 'again'}, {'sender': 'counter', 'text': 'Message 2: again'}], [{'sender': 'alice', 'text': 'private'}, {'sender': 'counter', 'text': 'Message 1: private'}], [{'sender': 'alice', 'text': 'hello'}, {'sender': 'counter', 'text': 'Message 1: hello'}, {'sender': 'bob', 'text': 'again'}, {'sender': 'counter', 'text': 'Message 2: again'}]]
Example 2
Input: simulate_chat(['register_keyword', 'send', 'get_log'], [['help-1', 'help', 'How can I help?'], ['support', 'sam', 'I need HELP'], ['support']])
Output: [None, [{'sender': 'sam', 'text': 'I need HELP'}, {'sender': 'keyword', 'text': 'How can I help?'}], [{'sender': 'sam', 'text': 'I need HELP'}, {'sender': 'keyword', 'text': 'How can I help?'}]]
Hints
Hint 1
Separate the engine from the individual bot types: define one common reply contract that takes the message and a state dictionary, so the dispatch loop never inspects bot types.
Hint 2
Keep a per-channel record holding the log and a dictionary mapping bot_id to that bot's state; create it lazily on the first send, but never in get_log.
Hint 3
Remember to append each bot reply right after it is produced, pass the original user message to every bot, and convert log entries to plain dictionaries when returning.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the system with a few small pieces:
- Responder contract. Every bot implements a single method
respond(message, state)that returns a reply message orNone. The engine only ever calls this method, so it never needs to know which concrete bot type it is talking to. Adding a new bot type means writing a new class and registering it, with no edits to the engine. - Per-channel record. Each channel owns a message log and a dictionary mapping
bot_idto that bot's state dictionary. The record is created lazily on the firstsend. - Dispatch loop. On
send, append the user message to the channel log, then iterate over the globally registered bots in registration order. For each bot, fetch (or create) its state for this channel, callrespondwith the original user message, and append any reply to the log right away. Replies are not fed back to other bots. - Driver.
simulate_chatcreates an engine, walks through the commands in order, and maps each command name to the matching engine call. Registrations returnNone;sendandget_logreturn lists of plain dictionaries. Unknown commands raiseValueError.
Why it is correct
- Bot state is owned by the channel and passed into the bot, so the same bot instance gives different counts in different channels, and bots stay reusable.
get_loguses.get, so reading an unknown channel returns[]without creating it.- A bot registered late has no entry in existing channels, so its state is created empty on the first message after registration, which matches the stated rule.
- Because every reply is generated from the original user message, and is appended in registration order, the log order matches the specification.
Complexity
For a send with B registered bots and a channel log of length L, the dispatch costs O(B), and building the returned log copy costs O(L). Overall time is O(sum over sends of (B + L)). Space is O(total log entries + number of (channel, bot) state entries).
Reference solution
from typing import List
class Message:
def __init__(self, sender, text):
self.sender = sender
self.text = text
def to_dict(self):
return {"sender": self.sender, "text": self.text}
class Responder:
def respond(self, message, state):
raise NotImplementedError
class CounterResponder(Responder):
def respond(self, message, state):
state["count"] = state.get("count", 0) + 1
return Message("counter", f"Message {state['count']}: {message.text}")
class KeywordResponder(Responder):
def __init__(self, keyword, reply):
self.keyword = keyword
self.reply = reply
def respond(self, message, state):
if self.keyword.lower() in message.text.lower():
return Message("keyword", self.reply)
return None
class ChannelRecord:
def __init__(self):
self.log = []
self.bot_states = {}
class Engine:
def __init__(self):
self.bots = []
self.channels = {}
def register(self, bot_id, bot):
self.bots.append((bot_id, bot))
def send(self, channel_id, message):
channel = self.channels.setdefault(channel_id, ChannelRecord())
channel.log.append(message)
for bot_id, bot in self.bots:
state = channel.bot_states.setdefault(bot_id, {})
reply = bot.respond(message, state)
if reply is not None:
channel.log.append(reply)
return [m.to_dict() for m in channel.log]
def get_log(self, channel_id):
channel = self.channels.get(channel_id)
if channel is None:
return []
return [m.to_dict() for m in channel.log]
def simulate_chat(commands: List[str], params: List[List]) -> List:
engine = Engine()
results = []
for command, args in zip(commands, params):
if command == "register_counter":
(bot_id,) = args
engine.register(bot_id, CounterResponder())
results.append(None)
elif command == "register_keyword":
bot_id, keyword, reply = args
engine.register(bot_id, KeywordResponder(keyword, reply))
results.append(None)
elif command == "send":
channel_id, sender, text = args
results.append(engine.send(channel_id, Message(sender, text)))
elif command == "get_log":
(channel_id,) = args
results.append(engine.get_log(channel_id))
else:
raise ValueError(f"Unknown operation: {command}")
return results