Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Fix Telegram release note formatting

Lelonio684d8c331b2c
diff --git a/.github/workflows/telegram-release.yml b/.github/workflows/telegram-release.yml
index ec95f6f..bbae28f 100644
--- a/.github/workflows/telegram-release.yml
+++ b/.github/workflows/telegram-release.yml
@@ -9,6 +9,10 @@ on:
description: Published release tag to announce
required: true
type: string
+ edit_messages:
+ description: Optional existing notes message IDs [channel, group]; edits notes only
+ default: ''
+ type: string
dry_run:
description: Preview without sending to Telegram
default: true
@@ -41,5 +45,6 @@ jobs:
TELEGRAM_CHANNEL: ${{ vars.TELEGRAM_CHANNEL || '@SquareAppOfficial' }}
TELEGRAM_GROUP: ${{ vars.TELEGRAM_GROUP || '-1003964165935' }}
TELEGRAM_THREAD_ID: ${{ vars.TELEGRAM_THREAD_ID }}
+ TELEGRAM_EDIT_MESSAGES: ${{ inputs.edit_messages }}
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
run: python3 scripts/telegram-release.py "$RUNNER_TEMP/telegram-release.json"
diff --git a/docs/TELEGRAM.md b/docs/TELEGRAM.md
index 0970d35..65c89aa 100644
--- a/docs/TELEGRAM.md
+++ b/docs/TELEGRAM.md
@@ -4,6 +4,8 @@ The `Telegram release` workflow announces a release after its GitHub draft is
published. It posts the full release notes, followed by the ARM64, ARMv7 and
universal APKs, to both `@SquareAppOfficial` and the community's News & Releases
topic. It checks that all three attachments are uploaded before posting.
+GitHub headings and bold text become Telegram bold, links are clickable,
+and inline code and fenced code blocks retain their formatting.
## One-time setup
@@ -44,6 +46,12 @@ Do not rerun a successful announcement: rerunning sends it again. If a run
fails after some messages were sent, check Telegram before rerunning to avoid
partial duplicate announcements. Sending to two destinations is not atomic.
+To correct formatting without duplicating attachments, run the workflow with
+`edit_messages` set to `[channel_message_id, group_message_id]` and dry_run
+disabled. This edits only the existing notes, and supports releases whose notes
+fit in one message. New announcements log their notes message IDs. Leave this
+input empty for normal publishing.
+
If publication is later automated using GitHub's default `GITHUB_TOKEN`, that
publication will not trigger another workflow. Publish with an appropriate
user/GitHub App token, or explicitly dispatch this workflow after publication.
diff --git a/scripts/telegram-release.py b/scripts/telegram-release.py
index db7e8b4..9b70236 100644
--- a/scripts/telegram-release.py
+++ b/scripts/telegram-release.py
@@ -1,6 +1,7 @@
"""Send a published Square release to its announcement channel and forum topic."""
import json
import os
+import re
from pathlib import Path
import sys
import tempfile
@@ -15,27 +16,105 @@ LABELS = {
}
+def units(text):
+ return len(text.encode("utf-16-le")) // 2
+
+
+def formatted_markdown(markdown):
+ """Render release-note Markdown as Telegram text and UTF-16 entities."""
+ output = []
+ entities = []
+ offset = 0
+
+ def append(text):
+ nonlocal offset
+ output.append(text)
+ offset += units(text)
+
+ def inline(text):
+ pattern = r"(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\(https?://[^\s)]+\))"
+ for token in re.split(pattern, text):
+ start = offset
+ kind = None
+ extra = {}
+ if token.startswith('`') and token.endswith('`') and len(token) > 2:
+ token, kind = token[1:-1], 'code'
+ elif token.startswith('**') and token.endswith('**') and len(token) > 4:
+ token, kind = token[2:-2], 'bold'
+ else:
+ link = re.fullmatch(r"\[([^\]]+)\]\((https?://[^\s)]+)\)", token)
+ if link:
+ token, kind = link[1], 'text_link'
+ extra = {'url': link[2]}
+ append(token)
+ if kind:
+ entities.append({'type': kind, 'offset': start, 'length': offset - start, **extra})
+
+ code_start = None
+ language = ''
+ for line in markdown.splitlines(keepends=True):
+ content = line.rstrip('\r\n')
+ newline = '\n' if line.endswith('\n') else ''
+ if content.startswith('```'):
+ if code_start is None:
+ code_start = offset
+ language = content[3:].strip()
+ else:
+ if offset > code_start:
+ entities.append({'type': 'pre', 'offset': code_start,
+ 'length': offset - code_start, 'language': language})
+ code_start = None
+ continue
+ if code_start is not None:
+ append(content + newline)
+ continue
+ heading = re.match(r'^#{1,6}\s+(.+)$', content)
+ if heading:
+ start = offset
+ inline(heading[1])
+ entities.append({'type': 'bold', 'offset': start, 'length': offset - start})
+ else:
+ bullet = re.match(r'^\s*[-*]\s+(.+)$', content)
+ if bullet:
+ append('• ')
+ inline(bullet[1])
+ else:
+ inline(content)
+ append(newline)
+ if code_start is not None and offset > code_start:
+ entities.append({'type': 'pre', 'offset': code_start, 'length': offset - code_start, 'language': language})
+ return ''.join(output), entities
+
+
def messages(release):
- title = release.get("name") or release["tag_name"]
- text = f"Square {title}\n\n{release['html_url']}\n\n{release.get('body') or 'Release notes are available on GitHub.'}"
- # Leave room below Telegram's 4096-character limit, including emoji pairs.
+ title = release.get('name') or release['tag_name']
+ text, entities = formatted_markdown(
+ f"# Square {title}\n\n[View release on GitHub]({release['html_url']})\n\n"
+ + (release.get('body') or 'Release notes are available on GitHub.'))
chunks = []
- while len(text.encode("utf-16-le")) // 2 > 3500:
- end = 0
- units = 0
+ start_units = 0
+ while text:
+ end, used = 0, 0
for char in text:
- size = len(char.encode("utf-16-le")) // 2
- if units + size > 3500:
+ if used + units(char) > 3500:
break
- units += size
+ used += units(char)
end += 1
- newline = text.rfind("\n", 0, end)
- if newline > end // 2:
- end = newline + 1
- chunks.append(text[:end])
+ if end < len(text):
+ newline = text.rfind('\n', 0, end)
+ if newline > end // 2:
+ end = newline + 1
+ chunk = text[:end]
+ stop_units = start_units + units(chunk)
+ chunk_entities = []
+ for entity in entities:
+ left = max(start_units, entity['offset'])
+ right = min(stop_units, entity['offset'] + entity['length'])
+ if right > left:
+ chunk_entities.append({**entity, 'offset': left - start_units, 'length': right - left})
+ chunks.append({'text': chunk, 'entities': chunk_entities})
text = text[end:]
- if text:
- chunks.append(text)
+ start_units = stop_units
return chunks
@@ -104,6 +183,17 @@ def main():
token = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
if not token:
raise ValueError("Set the TELEGRAM_BOT_TOKEN repository secret first")
+ edits = os.environ.get('TELEGRAM_EDIT_MESSAGES', '')
+ if edits:
+ ids = json.loads(edits)
+ if len(notes) != 1 or len(ids) != len(destinations):
+ raise ValueError('Editing requires one notes message and an ID for each destination')
+ for destination, message_id in zip(destinations, ids):
+ telegram(token, 'editMessageText', {'chat_id': destination['chat_id'],
+ 'message_id': int(message_id), **notes[0],
+ 'link_preview_options': {'is_disabled': True}})
+ print('Updated release-note formatting in both destinations; APKs unchanged.')
+ return
# Download and validate every attachment before publishing anything.
with tempfile.TemporaryDirectory() as tmp:
files = []
@@ -115,9 +205,10 @@ def main():
raise ValueError(f"Incomplete download: {asset['name']}")
files.append((path, label))
for destination in destinations:
- for text in notes:
- telegram(token, "sendMessage", {**destination, "text": text,
+ for message in notes:
+ sent = telegram(token, "sendMessage", {**destination, **message,
"link_preview_options": {"is_disabled": True}})
+ print(f"Notes message ID for {destination['chat_id']}: {sent['message_id']}")
for path, label in files:
telegram(token, "sendDocument", {**destination, "caption": label}, file=path)
print(f"Published {release['tag_name']} notes and {len(files)} APKs to both Telegram destinations.")
diff --git a/scripts/tests/test_telegram_release.py b/scripts/tests/test_telegram_release.py
index ed737bf..b423363 100644
--- a/scripts/tests/test_telegram_release.py
+++ b/scripts/tests/test_telegram_release.py
@@ -24,8 +24,27 @@ class ReleaseTests(unittest.TestCase):
value = release()
value['body'] = '🧪 test\n' * 3000
chunks = module.messages(value)
- self.assertTrue(all(len(c.encode('utf-16-le')) // 2 <= 3500 for c in chunks))
- self.assertEqual(''.join(chunks), f"Square 2.4.5\n\n{value['html_url']}\n\n{value['body']}")
+ self.assertTrue(all(len(c['text'].encode('utf-16-le')) // 2 <= 3500 for c in chunks))
+ self.assertEqual(''.join(c['text'] for c in chunks), f"Square 2.4.5\n\nView release on GitHub\n\n{value['body']}")
+
+ def test_markdown_formats_headings_lists_links_and_code(self):
+ text, entities = module.formatted_markdown('## Fixed\n- **Playback** and `track.apk`\n[Release](https://github.com/Lelonio/Square)\n```sh\nadb shell cmd\n```\n')
+ self.assertEqual(text, 'Fixed\n• Playback and track.apk\nRelease\nadb shell cmd\n')
+ self.assertEqual({e['type'] for e in entities}, {'bold', 'code', 'text_link', 'pre'})
+ for entity in entities:
+ part = text.encode('utf-16-le')[entity['offset'] * 2:(entity['offset'] + entity['length']) * 2].decode('utf-16-le')
+ self.assertTrue(part)
+
+ def test_entities_remain_valid_across_long_unicode_messages(self):
+ value = release()
+ value['body'] = '- **🧪 Audio effects** work well.\n' * 400
+ for message in module.messages(value):
+ length = module.units(message['text'])
+ for entity in message['entities']:
+ self.assertGreater(entity['length'], 0)
+ self.assertLessEqual(entity['offset'] + entity['length'], length)
+ encoded = message['text'].encode('utf-16-le')
+ encoded[entity['offset'] * 2:(entity['offset'] + entity['length']) * 2].decode('utf-16-le')
def test_all_three_apks_required(self):
value = release()
@@ -64,6 +83,23 @@ class ReleaseTests(unittest.TestCase):
module.main()
network.assert_not_called()
+ def test_edit_updates_existing_notes_without_downloading_apks(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / 'release.json'
+ path.write_text(json.dumps(release()))
+ with patch.dict(os.environ, {'TELEGRAM_BOT_TOKEN': 'test', 'TELEGRAM_EDIT_MESSAGES': '[5,23]'}, clear=True), \
+ patch('sys.argv', ['telegram-release.py', str(path)]), \
+ patch.object(module.request, 'urlopen') as network, \
+ patch.object(module, 'telegram') as api, patch('builtins.print'):
+ module.main()
+ network.assert_not_called()
+ self.assertEqual(api.call_count, 2)
+ for call, message_id in zip(api.call_args_list, (5, 23)):
+ self.assertEqual(call.args[1], 'editMessageText')
+ self.assertEqual(call.args[2]['message_id'], message_id)
+ self.assertTrue(call.args[2]['entities'])
+ self.assertNotIn('##', call.args[2]['text'])
+
if __name__ == '__main__':
unittest.main()