From d6d971eb3de5b43227b0fa0aaf30668f1a276041 Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 30 Mar 2026 13:46:53 +0000 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2=20=C2=AB?= =?UTF-8?q?/=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- localchat_webio.py | 73 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 localchat_webio.py diff --git a/localchat_webio.py b/localchat_webio.py new file mode 100644 index 0000000..d75a014 --- /dev/null +++ b/localchat_webio.py @@ -0,0 +1,73 @@ +from pywebio import * +from pywebio.input import * +from pywebio.output import * +from pywebio.session import * + +import asyncio + +chat_msgs = [] +online_users = set() + +MAX_MESSAGES_COUNT = 100 + + +async def main(): + global chat_msgs + + put_markdown("## Welcome to online chat") + + msg_box = output() + put_scrollable(msg_box, height=300, keep_bottom=True) + + nickname = await input("Log in chat", required=True, placeholder="Your name", validate=lambda + n: "This nickname is already in use" if n in online_users or n == '' else None) + online_users.add(nickname) + + chat_msgs.append(f"`{nickname}` joined the chat!") + msg_box.append(put_markdown(f"`{nickname}` joined the chat!")) + + refresh_task = run_async(refresh_msg(nickname, msg_box)) + + while True: + data = await input_group(" New message", [ + input(placeholder="Message text", name="msg"), + actions(name="cmd", buttons=["Send", {'label': "Leave the chat", 'type': 'cancel'}]) + ], validate=lambda m: ('msg', "Enter your message!") if m["cmd"] == "Send" and not m["msg"] else None) + + if data is None: + break + + msg_box.append(put_markdown(f"`{nickname}`: {data['msg']}")) + chat_msgs.append((nickname, data['msg'])) + + # exit chat + refresh_task.close() + + online_users.remove(nickname) + toast("You left chat!") + msg_box.append(put_markdown(f" User `{nickname}` leave the chat!")) + chat_msgs.append(('', f"User `{nickname}` leave the chat!")) + + put_buttons(['Back to chat'], onclick=lambda btn:run_js('window.location.reload()')) + + +async def refresh_msg(nickname, msg_box): + global chat_msgs + last_idx = len(chat_msgs) + + while True: + await asyncio.sleep(1) + + for m in chat_msgs[last_idx:]: + if m[0] != nickname: + msg_box.append(put_markdown(f"`{m[0]}`: {m[1]}")) + + # remove expired + if len(chat_msgs) > MAX_MESSAGES_COUNT: + chat_msgs = chat_msgs[len(chat_msgs) // 2:] + + last_idx = len(chat_msgs) + + +if __name__ == "__main__": + start_server(main, debug=True, port=8080, cdn=False, host="192.168.0.14") \ No newline at end of file