1
0

chat_room.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import asyncio
  2. from pywebio import start_server
  3. from pywebio.input import *
  4. from pywebio.output import *
  5. from pywebio.session import defer_call, info as session_info, run_async
  6. MAX_MESSAGES_CNT = 10 ** 4
  7. chat_msgs = [] # The chat message history. The item is (name, message content)
  8. online_users = set()
  9. def t(eng, chinese):
  10. """return English or Chinese text according to the user's browser language"""
  11. return chinese if 'zh' in session_info.user_language else eng
  12. async def refresh_msg(my_name):
  13. """send new message to current session"""
  14. global chat_msgs
  15. last_idx = len(chat_msgs)
  16. while True:
  17. await asyncio.sleep(0.5)
  18. for m in chat_msgs[last_idx:]:
  19. if m[0] != my_name: # only refresh message that not sent by current user
  20. put_markdown('`%s`: %s' % m, sanitize=True, scope='msg-box')
  21. # remove expired message
  22. if len(chat_msgs) > MAX_MESSAGES_CNT:
  23. chat_msgs = chat_msgs[len(chat_msgs) // 2:]
  24. last_idx = len(chat_msgs)
  25. async def main():
  26. """PyWebIO chat room
  27. You can chat with everyone currently online.
  28. """
  29. global chat_msgs
  30. put_markdown(t("## PyWebIO chat room\nWelcome to the chat room, you can chat with all the people currently online. You can open this page in multiple tabs of your browser to simulate a multi-user environment. This application uses less than 90 lines of code, the source code is [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/chat_room.py)", "## PyWebIO聊天室\n欢迎来到聊天室,你可以和当前所有在线的人聊天。你可以在浏览器的多个标签页中打开本页面来测试聊天效果。本应用使用不到90行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/dev/demos/chat_room.py)"))
  31. put_scrollable(put_scope('msg-box'), height=300, keep_bottom=True)
  32. nickname = await input(t("Your nickname", "请输入你的昵称"), required=True, validate=lambda n: t('This name is already been used', '昵称已被使用') if n in online_users or n == '📢' else None)
  33. online_users.add(nickname)
  34. chat_msgs.append(('📢', '`%s` joins the room. %s users currently online' % (nickname, len(online_users))))
  35. put_markdown('`📢`: `%s` join the room. %s users currently online' % (nickname, len(online_users)), sanitize=True, scope='msg-box')
  36. @defer_call
  37. def on_close():
  38. online_users.remove(nickname)
  39. chat_msgs.append(('📢', '`%s` leaves the room. %s users currently online' % (nickname, len(online_users))))
  40. refresh_task = run_async(refresh_msg(nickname))
  41. while True:
  42. data = await input_group(t('Send message', '发送消息'), [
  43. input(name='msg', help_text=t('Message content supports inline Markdown syntax', '消息内容支持行内Markdown语法')),
  44. actions(name='cmd', buttons=[t('Send', '发送'), t('Multiline Input', '多行输入'), {'label': t('Exit', '退出'), 'type': 'cancel'}])
  45. ], validate=lambda d: ('msg', 'Message content cannot be empty') if d['cmd'] == t('Send', '发送') and not d['msg'] else None)
  46. if data is None:
  47. break
  48. if data['cmd'] == t('Multiline Input', '多行输入'):
  49. data['msg'] = '\n' + await textarea('Message content', help_text=t('Message content supports Markdown syntax', '消息内容支持Markdown语法'))
  50. put_markdown('`%s`: %s' % (nickname, data['msg']), sanitize=True, scope='msg-box')
  51. chat_msgs.append((nickname, data['msg']))
  52. refresh_task.close()
  53. toast("You have left the chat room")
  54. if __name__ == '__main__':
  55. start_server(main, debug=True, port=8080)