aboutsummaryrefslogtreecommitdiff
path: root/models/rich_text.py
blob: e5441b6ff032356e3b6d84f89c5b6825b652a1ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from typing import Self

from aiogram import Bot
from aiogram.types import Message, MessageEntity
from pydantic import BaseModel


class RichText(BaseModel):
    text: str
    entities: list[MessageEntity] = []

    @classmethod
    def from_message(cls, msg: Message) -> Self:
        assert msg.text is not None
        return cls(
            text=msg.text,
            entities=[] if msg.entities is None else msg.entities,
        )

    @classmethod
    def from_text(cls, *text: RichText | str) -> Self:
        result = cls(text="", entities=[])

        for t in text:
            if isinstance(t, RichText):
                entities = t.entities.copy()
                for e in entities:
                    e.offset += len(result.text)
                result.entities += entities

                result.text += t.text
            else:
                result.text += t

        return result

    async def send(self, bot: Bot, chat_id: int) -> Message:
        return await bot.send_message(
            chat_id=chat_id,
            text=self.text,
            entities=self.entities,
            parse_mode=None,
        )