42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
import asyncio
|
|
from nio import AsyncClient, MatrixRoom, RoomMessageText
|
|
from config import settings
|
|
|
|
class MatrixBot:
|
|
def __init__(self):
|
|
self.client = AsyncClient(settings.homeserver_url, settings.matrix_user)
|
|
self.room_id = settings.default_room_id
|
|
|
|
async def login(self):
|
|
if settings.matrix_access_token:
|
|
self.client.access_token = settings.matrix_access_token
|
|
# We still need device_id maybe, but let's assume simple setup or login fallback
|
|
else:
|
|
resp = await self.client.login(settings.matrix_password)
|
|
if hasattr(resp, 'access_token'):
|
|
print(f"Logged in as {resp.user_id}")
|
|
else:
|
|
print(f"Failed to login: {resp}")
|
|
raise Exception("Login failed")
|
|
|
|
async def send_message(self, message: str, html_message: str = None, room_id: str = None):
|
|
target_room = room_id or self.room_id
|
|
|
|
content = {
|
|
"msgtype": "m.text",
|
|
"body": message
|
|
}
|
|
|
|
if html_message:
|
|
content["format"] = "org.matrix.custom.html"
|
|
content["formatted_body"] = html_message
|
|
|
|
await self.client.room_send(
|
|
room_id=target_room,
|
|
message_type="m.room.message",
|
|
content=content
|
|
)
|
|
|
|
async def close(self):
|
|
await self.client.close()
|