58 lines
2.1 KiB
Python
58 lines
2.1 KiB
Python
from nio import AsyncClient, LoginResponse
|
|
|
|
from .commands import CommandHandler
|
|
from .events import EventHandler
|
|
from .utils import save_sync_token, load_sync_token
|
|
|
|
|
|
class PingPongBot:
|
|
def __init__(self, config):
|
|
self.config = config
|
|
self.client = AsyncClient(config["homeserver_url"], config["bot_user"])
|
|
self.sync_token_file = "data/sync_token.txt"
|
|
|
|
# Инициализация подсистем
|
|
self.command_handler = CommandHandler(self)
|
|
self.event_handler = EventHandler(self)
|
|
|
|
async def send_text(self, room_id, text):
|
|
"""Отправка текстового сообщения"""
|
|
await self.client.room_send(
|
|
room_id=room_id,
|
|
message_type="m.room.message",
|
|
content={"msgtype": "m.text", "body": text}
|
|
)
|
|
|
|
async def start(self):
|
|
"""Запуск основного цикла бота"""
|
|
# Логин
|
|
login_response = await self.client.login(self.config["bot_password"])
|
|
if not isinstance(login_response, LoginResponse):
|
|
print("[ERROR] Login failed")
|
|
return
|
|
print(f"[INFO] Logged in as {self.client.user_id}")
|
|
|
|
# Регистрация обработчиков событий
|
|
self.event_handler.register_callbacks()
|
|
|
|
# Загрузка токена синхронизации
|
|
sync_token = load_sync_token(self.sync_token_file)
|
|
|
|
# Запуск бесконечного sync
|
|
try:
|
|
await self.client.sync_forever(
|
|
timeout=30000,
|
|
since=sync_token,
|
|
full_state=False,
|
|
set_presence="online",
|
|
loop_sleep_time=1500
|
|
)
|
|
except KeyboardInterrupt:
|
|
print("[INFO] Stopping bot...")
|
|
finally:
|
|
await self.client.close()
|
|
|
|
async def on_sync(self, response):
|
|
"""Обработчик синхронизации (сохранение токена)"""
|
|
if hasattr(response, "next_batch") and response.next_batch:
|
|
save_sync_token(self.sync_token_file, response.next_batch) |