Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chat #10

Merged
merged 2 commits into from
Sep 28, 2024
Merged

Chat #10

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Code/api/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .chat import ChatClientModule

__all__ = ["ChatClientModule"]
136 changes: 136 additions & 0 deletions Code/api/chat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
from typing import List, Literal, Optional

import dearpygui.dearpygui as dpg
import dpg_tools
from DMBotNetwork import Client
from systems.loc import Localization as loc


class ChatMessageType:
__slots__ = ["_message_type", "message", "sender"]

def __init__(
self,
message_type: Literal["ooc", "admin"],
message: str,
sender: Optional[str] = None,
) -> None:
self._message_type: str = message_type
self.message: str = message
self.sender: Optional[str] = sender

@property
def message_type(self) -> str:
return self._message_type

@message_type.setter
def message_type(self, value: Literal["ooc", "admin"]) -> None:
self._message_type = value


class ChatClientModule:
messages: List[ChatMessageType] = []
filters = {"ooc": True, "admin": True}
current_chat_type: str = "ooc" # Текущий выбранный чат по умолчанию

@staticmethod
async def send_chat_message(chat_message_type: ChatMessageType) -> None:
"""Отправляет сообщение через сеть."""
await Client.req_net_func(
"send_message",
message=chat_message_type.message,
message_type=chat_message_type.message_type,
)

@staticmethod
async def net_get_chat_message(
message: str, message_type: str, sender: Optional[str] = None
) -> None:
"""Получает сообщение и добавляет его в чат."""
ChatClientModule.messages.append(ChatMessageType(message_type, message, sender)) # type: ignore
ChatClientModule.update_chat_display()

@classmethod
async def _iternal_send_message(cls, sender, app_data, user_data) -> None:
"""Асинхронная отправка сообщения через UI."""
raw_message = dpg_tools.decode_string(dpg.get_value("chat_input"))
message_type = dpg.get_value("chat_type_selector")
chat_message = ChatMessageType(message_type, raw_message.strip()) # type: ignore
await cls.send_chat_message(chat_message)
dpg.set_value("chat_input", "")

@classmethod
def create_window(cls, sender, app_data, user_data):
"""Создание основного окна чата с фильтрацией и отправкой сообщений."""
if dpg.does_item_exist("chat_window"):
dpg.focus_item("chat_window")
return

with dpg.window(
label=loc.get_string("chat_window_lable"),
tag="chat_window",
width=400,
height=400,
):
with dpg.menu_bar():
with dpg.menu(label=loc.get_string("chat_filter")):
dpg.add_menu_item(
label="OOC",
callback=cls.update_filter,
user_data="ooc",
check=True,
default_value=True,
)
dpg.add_menu_item(
label="Admin",
callback=cls.update_filter,
user_data="admin",
check=True,
default_value=True,
)

dpg.add_child_window(
label="Chat Display", autosize_x=True, height=200, tag="chat_display"
)

with dpg.group(horizontal=True):
dpg.add_combo(
items=["ooc", "admin"],
default_value="ooc",
tag="chat_type_selector",
width=80,
)

dpg.add_input_text(
width=270,
tag="chat_input",
hint=loc.get_string("chat_input_hint"),
on_enter=True,
callback=cls._iternal_send_message,
)

dpg.add_key_press_handler(
parent="main_registry", callback=cls.key_press_callback
)

@classmethod
def key_press_callback(cls, sender, app_data):
"""Обрабатывает нажатие клавиш."""
if app_data == ord("T"): # TODO Сделать ебаные настройки уже
dpg.focus_item("chat_input")

@classmethod
def update_filter(cls, sender, app_data, user_data):
"""Обновляет фильтры в зависимости от состояния чекбоксов."""
cls.filters[user_data] = app_data
cls.update_chat_display()

@classmethod
def update_chat_display(cls):
"""Обновляет отображение сообщений в чате на основе фильтров."""
dpg.delete_item("chat_display", children_only=True)

for chat_message in cls.messages:
if cls.filters[chat_message.message_type]:
display_message = f"[{chat_message.message_type}] {chat_message.sender}: {chat_message.message}"
dpg.add_text(display_message, parent="chat_display", wrap=0)
12 changes: 9 additions & 3 deletions Code/gui/dm_client_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
from systems.loc import Localization as loc

from .fonts_setup import FontManager
from .windows.admin import admin_main_window
from .windows.admin import admin_menu_setup
from .windows.user import user_menu_setup


class DMClientApp:
Expand Down Expand Up @@ -213,6 +214,9 @@ async def setup_start_windows(cls) -> None:
)
)
access = await Client.req_get_data("get_access", None, login=Client.get_login())

dpg.add_handler_registry(tag='main_registry')

dpg.add_viewport_menu_bar(tag="main_bar")

dpg.add_menu_item(
Expand All @@ -221,9 +225,11 @@ async def setup_start_windows(cls) -> None:
enabled=False,
)

# При всём желании, проверка прав проходит на сервере. Даже не пытайтесь.
# При всём желании, проверка прав проходит на сервере. Даже не пытайтесь якобы взломать игру.
if "full_access" in access:
await admin_main_window()
await admin_menu_setup()

await user_menu_setup()

@classmethod
async def download_content_from_server(cls) -> None:
Expand Down
2 changes: 1 addition & 1 deletion Code/gui/windows/admin/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .main import admin_main_window
from .main import admin_menu_setup
2 changes: 1 addition & 1 deletion Code/gui/windows/admin/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from .manage_users import user_management


async def admin_main_window():
async def admin_menu_setup():
dpg.add_menu(
label=loc.get_string("admin_control_menu"),
tag="admin_control_menu_bar",
Expand Down
1 change: 1 addition & 0 deletions Code/gui/windows/user/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .main import user_menu_setup
23 changes: 23 additions & 0 deletions Code/gui/windows/user/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import dearpygui.dearpygui as dpg
from api import ChatClientModule
from systems.loc import Localization as loc


async def user_menu_setup():
dpg.add_menu(
label=loc.get_string("user_menu"),
tag="user_menu_bar",
parent="main_bar",
)

dpg.add_menu_item(
label=loc.get_string("toggle_viewport_fullscreen"),
parent="user_menu_bar",
callback=lambda: dpg.toggle_viewport_fullscreen(),
)

dpg.add_menu_item(
label=loc.get_string("chat_window_lable"),
parent="user_menu_bar",
callback=ChatClientModule.create_window,
)
6 changes: 5 additions & 1 deletion Code/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
from pathlib import Path

from api import ChatClientModule
from DMBotNetwork import Client
from gui.dm_client_app import DMClientApp
from root_path import ROOT_PATH
Expand All @@ -14,11 +15,14 @@ def format(self, record):
record.levelname = f"{record.levelname:<7}"
return super().format(record)


def init_classes() -> None:
pass
Client.register_methods_from_class([ChatClientModule])


def main() -> None:
loc.load_translations(Path(ROOT_PATH / "Content" / "Client" / "loc" / "rus"))
init_classes()
DiscordRPC()

Client()
Expand Down
3 changes: 1 addition & 2 deletions Content/Client/loc/rus/admin.loc
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# For main
admin_control_menu = Админ панель


# For user managment
confirm_deletion_text = Вы уверены что хотите удалить пользователя? Это действие не обратимо
Expand Down
3 changes: 3 additions & 0 deletions Content/Client/loc/rus/chat.loc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
chat_window_lable = Чат
chat_filter = Фильтр
chat_input_hint = Введите сообщение
4 changes: 4 additions & 0 deletions Content/Client/loc/rus/menu.loc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# For main
admin_control_menu = Админ панель
user_menu = Меню пользователя
toggle_viewport_fullscreen = Переключить полный экран
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
dearpygui
dearpygui-async
DMBotNetwork==0.2.8
DMBotNetwork==0.3.0
DMBotTools
msgpack
Pillow
Expand Down
Loading