Skip to main content

Chatbot / Events/ Scroll

Infinite scroll for previous messages.

from h2o_wave import main, app, Q, ui, data

prev_messages = [{'content': f'Message {i}', 'from_user': i % 2 == 0} for i in range(100)]

async def serve(q: Q):
if not q.client.initialized:
q.client.current_load_page = len(prev_messages)
# Use list buffer to allow easy streaming. Must have exactly 2 fields - msg and from_user.['example'] = ui.chatbot_card(
box='1 1 5 5',
data=data(fields='content from_user', t='list', rows=[
['Hello', True],
['Hi', False],
['Hello', True],
['Hi', False],
['Hello', True],
['Hi', False],
['Hello', True],
['Hi', False],
q.client.initialized = True

# A new message arrived.
if q.args.chatbot:
# Append user message.['example'].data += [q.args.chatbot, True]
# Append bot response.['example'].data += ['I am a fake chatbot. Sorry, I cannot help you.', False]

# User scrolled up, load chat history.
if and
if q.client.current_load_page == 0:
# If we reached the end, signal it to Wave by setting prev_items to empty list.['example'].prev_items = []
end = q.client.current_load_page - LOAD_SIZE['example'].prev_items = prev_messages[end:q.client.current_load_page]
q.client.current_load_page = end
await q.sleep(0.5) # Simulate network latency.


Tags:  chatbotinfinitescroll