Created Sending spoilers and custom emoji (markdown)

Lonami 2022-10-21 11:05:11 +02:00
parent 1e017a0cbb
commit f40c4408b2

@ -0,0 +1,47 @@
Telethon's v1 `markdown` parser does not offer a way to send spoiler (hidden text) or custom emoji. However, it's easy to add support for them.
Telethon's [`parse_mode`](https://docs.telethon.dev/en/stable/modules/client.html#telethon.client.messageparse.MessageParseMethods.parse_mode) supports using a custom object with `parse` and `unparse` functions to work. This means it's possible to leverage the current markdown implementation and extend it with custom functionality.
Copy the following code into your own:
```python
from telethon.extensions import markdown
from telethon import types
class CustomMarkdown:
@staticmethod
def parse(text):
text, entities = markdown.parse(text)
for i, e in enumerate(entities):
if isinstance(e, types.MessageEntityTextUrl):
if e.url == 'spoiler':
entities[i] = types.MessageEntitySpoiler(e.offset, e.length)
elif e.url.startswith('emoji/'):
entities[i] = types.MessageEntityCustomEmoji(e.offset, e.length, int(e.url.split('/')[1]))
return text, entities
@staticmethod
def unparse(text, entities):
return markdown.unparse(text, entities)
```
This creates a custom class with `parse` and `unparse`. `CustomMarkdown.parse` uses `markdown.parse` (so it works just like the default markdown), but before returning, it scans the parsed text for the following inline URLs:
```python
message = 'this is a [link text](spoiler) and [❤️](emoji/10002345) too'
```
Here, the message contains a `link text` with URL `spoiler`. The above code will replace the URL with [`MessageEntitySpoiler`](https://tl.telethon.dev/constructors/message_entity_spoiler.html). It also contains a URL with `emoji/10002345`, which will be replaced with [`MessageEntityCustomEmoji`](https://tl.telethon.dev/constructors/message_entity_custom_emoji.html). Effectively sending those instead of the URL.
To use the class, you must change your `client.parse_mode` to it (be sure to use an instance, because the type is callable and the library would attempt to create an instance to parse it):
```python
client.parse_mode = CustomMarkdown()
```
Now, in your message text, you can use inline links which become spoilers and custom emoji! (Note that for custom emoji to work, the inline link text **must** be a normal emoji):
```python
client.send_message('me', 'hello this is a [hidden text](spoiler), with custom emoji [❤️](emoji/10002345) !')
```
You may have noticed the emoji URL is followed by a number. This number is a `document_id`. To find it, the easiest way is to send a message to your own chat with the premium emoji you want to use using an official client, and then use Telethon to print the `message.entities`. It will contain the `document_id` you need to use.