Skip to content

Commit

Permalink
Merge pull request #26 from sudoskys/dev
Browse files Browse the repository at this point in the history
expandable citation
sudoskys authored Sep 27, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
2 parents ec9adcb + 6874b34 commit 92293af
Showing 9 changed files with 191 additions and 43 deletions.
Binary file added .github/result-6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 16 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -48,13 +48,13 @@ pdm add telegramify-markdown
- [x] Block Quotes `>`
- [x] Strikethrough `~~Strikethrough~~`
- [x] Spoilers `||Spoiler||`
- [ ] Task Lists
- [x] Task Lists
- [x] Expanded Citation
- [ ] Strikethrough `~Strikethrough~`
- [ ] Telegram Emojis
- [ ] Telegram User Mentions

> [!NOTE]
> Since mistletoe doesn't parse `- [ ] TODO`, we can't implement it.
> [!NOTE]
> Despite `~Strikethrough~` being mentioned in Telegram's official documentation, it can't be parsed as strikethrough.
## Use case
@@ -65,7 +65,8 @@ from telegramify_markdown import customize

customize.markdown_symbol.head_level_1 = "📌" # If you want, Customizing the head level 1 symbol
customize.markdown_symbol.link = "🔗" # If you want, Customizing the link symbol
customize.strict_markdown = True # If you want to use __underline__ as underline, set it to False or it will be converted to bold.
customize.strict_markdown = True # If you want to use __underline__ as underline, set it to False, or it will be converted to bold.
customize.cite_expandable = True # If you want to enable expandable citation, set it to True.
markdown_text = """
# Title
## Subtitle
@@ -89,6 +90,13 @@ __underline italic bold__
> Quote
> Multiline Quote In Markdown it's not possible to send multiline quote in telegram without using code block or html tag but telegramify_markdown can do it.
> If you quote is too long, it will be automatically set in expandable citation.
> This is the second line of the quote.
> This is the third line of the quote.
> This is the fourth line of the quote.
> This is the fifth line of the quote.
```python
print("Hello, World!")
```
@@ -110,4 +118,7 @@ print(converted)

output as follows:

![.github/result.png](.github/result-5.png)
| Exp 1 | Exp 2 |
|---------------------------------|---------------------------------|
| ![result](.github/result-5.png) | ![result](.github/result-6.png) |

139 changes: 113 additions & 26 deletions pdm.lock

Large diffs are not rendered by default.

25 changes: 20 additions & 5 deletions playground/show_send.py
Original file line number Diff line number Diff line change
@@ -15,6 +15,13 @@
## Subtitle
### Subsubtitle
#### Subsubsubtitle
\(TEST
\\(TEST
\\\(TEST
\\\\(TEST
\\\\\(TEST
'\_', '\*', '\[', '\]', '\(', '\)', '\~', '\`', '\>', '\#', '\+', '\-', '\=', '\|', '\{', '\}', '\.', '\!'
_ , * , [ , ] , ( , ) , ~ , ` , > , # , + , - , = , | , { , } , . , !
We will remove the \ symbol from the original text.
@@ -28,15 +35,18 @@
*bold _italic bold ~~italic bold strikethrough ||italic bold strikethrough spoiler||~~ __underline italic bold___ bold*
__underline italic bold__
[link](https://www.google.com)
- [ ] Uncompleted task list item
- [ ] __Underline__ ~~Strikethrough~~ _italic_ Item
- [x] Completed task list item
- [x] **Bold** ||Spoiler|| `Inline Code` Item
> Quote
> Multiline Quote In Markdown it's not possible to send multiline quote in telegram without using code block or html tag but telegramify_markdown can do it.
> If you quote is too long, it will be automatically set in expandable citation.
> This is the second line of the quote.
> This is the third line of the quote.
> This is the fourth line of the quote.
> This is the fifth line of the quote.
```python
print("Hello, World!")
```
@@ -47,8 +57,13 @@
- Another item.
1. Actual numbers don't matter, just that it's a number
"""
converted = telegramify_markdown.convert(md)
converted = telegramify_markdown.markdownify(
md,
max_line_length=None, # If you want to change the max line length for links, images, set it to the desired value.
normalize_whitespace=False
)
print(converted)
# export Markdown to Telegram MarkdownV2 style.
load_dotenv()
telegram_bot_token = os.getenv("TELEGRAM_BOT_TOKEN", None)
chat_id = os.getenv("TELEGRAM_CHAT_ID", None)
8 changes: 7 additions & 1 deletion playground/telegram_exp.py
Original file line number Diff line number Diff line change
@@ -26,7 +26,13 @@ def ignore(a):
"""__Hello, World\!__"""
ignore(formatting.mstrikethrough("Hello, World!"))
"""~Hello, World\!~"""
ignore(formatting.mcite("Hello, World!"))
ignore(formatting.mcite("Hello, World!\n2Hello, World!\n3Hello, World!", expandable=True))
"""
**>Hello, World\!
>2Hello, World\!
>3Hello, World\!||
"""
ignore(formatting.mcite("Hello, World!", expandable=True))
""">Hello, World\!"""
ignore(formatting.escape_markdown("Hello, World!"))
"""Hello, World\!"""
7 changes: 6 additions & 1 deletion playground/use_case.py
Original file line number Diff line number Diff line change
@@ -11,7 +11,12 @@
quote = """>test"""
task = """
- [x] task1?
- [x] task2?
-- [x] task2?
\\\\( T\\(n\\) \\= 100^\\{10\\} \\\\) 用大 O 记号表示。\\~\\[RULE\\]\n\n观察此函数可知,它是一个常数
>1231
"""
test_md = """
**bold text**
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
[project]
name = "telegramify-markdown"
version = "0.1.12"
version = "0.1.13"
description = "Convert Markdown to a format usable by Telegram."
authors = [
{ name = "sudoskys", email = "coldlando@hotmail.com" },
]
dependencies = [
"mistletoe==1.4.0",
"pytelegrambotapi>=4.18.1",
"pytelegrambotapi>=4.22.0",
]
requires-python = ">=3.8"
readme = "README.md"
1 change: 1 addition & 0 deletions src/telegramify_markdown/customize.py
Original file line number Diff line number Diff line change
@@ -18,5 +18,6 @@ class Symbol(object):


markdown_symbol = Symbol()
cite_expandable = True
strict_markdown = True
unescape_html = False
29 changes: 26 additions & 3 deletions src/telegramify_markdown/render.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import html
import re
from itertools import chain
from itertools import chain, tee
from typing import Iterable

from mistletoe import block_token, span_token
@@ -9,7 +9,7 @@
from mistletoe.span_token import SpanToken
from telebot import formatting

from .customize import markdown_symbol, strict_markdown
from .customize import markdown_symbol, strict_markdown, cite_expandable


class Spoiler(SpanToken):
@@ -90,12 +90,35 @@ def __init__(self, *extras, **kwargs):
def render_quote(
self, token: block_token.Quote, max_line_length: int
) -> Iterable[str]:
def add_expanded_suffix(iterable: Iterable[str]) -> Iterable[str]:
iterator = iter(iterable)
try:
previous_item = next(iterator)
except StopIteration:
return iter([])
for current_item in iterator:
yield previous_item
previous_item = current_item
yield f"{previous_item}||"

max_child_line_length = max_line_length - 2 if max_line_length else None
lines = self.blocks_to_lines(
token.children, max_line_length=max_child_line_length
)
lines, counter = tee(lines)
total_characters = sum(len(s) for s in counter)
# NOTE: Remove the space after the > , but it is not standard markdown
return self.prefix_lines(lines or [""], ">")
append_expanded_cite = cite_expandable and total_characters > 200
if append_expanded_cite:
first_line_prefix = "**>"
lines = add_expanded_suffix(lines)
else:
first_line_prefix = ">"
yield from self.prefix_lines(
lines or [""],
first_line_prefix=first_line_prefix,
following_line_prefix=">"
)

def render_heading(
self, token: block_token.Heading, max_line_length: int

0 comments on commit 92293af

Please sign in to comment.