Skip to content

Commit

Permalink
Add release note format
Browse files Browse the repository at this point in the history
  • Loading branch information
JanisV committed Oct 8, 2024
1 parent fd4fe89 commit 184e823
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 11 deletions.
42 changes: 31 additions & 11 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from github import Github, Auth
from telegram.constants import MessageLimit
from telegram.constants import MessageLimit, ParseMode
# TODO: Use md2tgmd instead telegramify_markdown
from telegramify_markdown import markdownify

from config import Config

Expand Down Expand Up @@ -102,20 +104,38 @@ def poll_github():
"\\1",
release_body
)
release_body = release_body[:MessageLimit.MAX_TEXT_LENGTH-256]

message = (f"<a href='{repo.html_url}'>{repo.full_name}</a>:\n"
f"<b>{release.title}</b>"
f" <code>{repo_obj.current_tag}</code>"
f"{" <i>pre-release</i>" if release.prerelease else ""}\n"
f"<blockquote>{release_body}</blockquote>"
f"<a href='{release.html_url}'>release note...</a>")
release_body = release_body[:MessageLimit.MAX_TEXT_LENGTH - 256]

for chat in repo_obj.chats:
if chat.release_note_format == "quote":
parse_mode = ParseMode.HTML
message = (f"<a href='{repo.html_url}'>{repo.full_name}</a>:\n"
f"<b>{release.title}</b>"
f" <code>{repo_obj.current_tag}</code>"
f"{" <i>pre-release</i>" if release.prerelease else ""}\n"
f"<blockquote>{release_body}</blockquote>"
f"<a href='{release.html_url}'>release note...</a>")
elif chat.release_note_format == "pre":
parse_mode = ParseMode.HTML
message = (f"<a href='{repo.html_url}'>{repo.full_name}</a>:\n"
f"<b>{release.title}</b>"
f" <code>{repo_obj.current_tag}</code>"
f"{" <i>pre-release</i>" if release.prerelease else ""}\n"
f"<pre>{release_body}</pre>"
f"<a href='{release.html_url}'>release note...</a>")
else:
parse_mode = ParseMode.MARKDOWN_V2
message = markdownify(f"[{repo.full_name}]({repo.html_url})\n"
f"*{release.title}*"
f" `{repo_obj.current_tag}`"
f"{" _pre-release_" if release.prerelease else ""}\n\n"
f"{release_body + "\n\n" if release_body else ""}"
f"[release note...]({release.html_url})")

try:
asyncio.run(telegram_bot.send_message(chat_id=chat.id,
text=message,
parse_mode='HTML',
parse_mode=parse_mode,
disable_web_page_preview=True))
except telegram.error.Forbidden as e:
app.logger.info('Bot was blocked by the user')
Expand All @@ -134,7 +154,7 @@ def poll_github():
try:
asyncio.run(telegram_bot.send_message(chat_id=chat.id,
text=message,
parse_mode='HTML',
parse_mode=ParseMode.HTML,
disable_web_page_preview=True))
except telegram.error.Forbidden as e:
app.logger.info('Bot was blocked by the user')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Add release_note_format field to Chat
Revision ID: a0844bd90308
Revises: 0f02a7a57103
Create Date: 2024-10-08 15:15:42.555006
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'a0844bd90308'
down_revision = '0f02a7a57103'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat', schema=None) as batch_op:
batch_op.add_column(sa.Column('release_note_format', sa.String(), nullable=True))

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat', schema=None) as batch_op:
batch_op.drop_column('release_note_format')

# ### end Alembic commands ###
1 change: 1 addition & 0 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Chat(db.Model):
id = db.Column(db.Integer, primary_key=True)
lang = db.Column(db.String(2), default='en')
github_username = db.Column(db.String)
release_note_format = db.Column(db.String)
created_at = db.Column(db.DateTime, default=aware_utcnow)

repos = db.relationship('Repo', secondary='chat_repo', back_populates='chats')
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ alembic~=1.13.1
SQLAlchemy~=2.0.30
python-telegram-bot~=21.6
PyGithub~=2.4.0
telegramify_markdown~=0.1.13
38 changes: 38 additions & 0 deletions telegram_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def __init__(self, token):
self.application.add_handler(CommandHandler("list", self.list_command))
self.application.add_handler(CommandHandler("editlist", self.edit_list_command))
self.application.add_handler(CommandHandler("starred", self.starred_command))
self.application.add_handler(CommandHandler("settings", self.settings_command))
self.application.add_handler(CommandHandler("stats", self.stats_command))
self.application.add_handler(MessageHandler(filters.COMMAND, self.unknown_command))
self.application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.message))
Expand Down Expand Up @@ -228,6 +229,34 @@ async def button(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
await self.add_starred_repos(user, github_user, update.callback_query.get_bot())

await query.delete_message()
elif query.data == "release_note_format":
with Session(engine) as session:
chat = get_or_create_chat(session, user)
keyboard = [[InlineKeyboardButton(f"Quote {"✅" if chat.release_note_format == "quote" else ""}",
callback_data="release_note_format-quote"),
InlineKeyboardButton(f"Pre {"✅" if chat.release_note_format == "pre" else ""}",
callback_data="release_note_format-pre"),
InlineKeyboardButton(f"Markdown {"✅" if not chat.release_note_format else ""}",
callback_data="release_note_format-markdown"), ],
[InlineKeyboardButton("Cancel", callback_data="cancel")]]
reply_markup = InlineKeyboardMarkup(keyboard)

await query.edit_message_reply_markup(reply_markup)
elif query.data.startswith("release_note_format-"):
with Session(engine) as session:
chat = get_or_create_chat(session, user)
if query.data == "release_note_format-quote":
chat.release_note_format = "quote"
elif query.data == "release_note_format-pre":
chat.release_note_format = "pre"
elif query.data == "release_note_format-markdown":
chat.release_note_format = None
else:
await update.message.reply_text("Error: Unknown format.")
return
session.commit()

await query.edit_message_text(text=f"Release note format changed.")
else:
with Session(engine) as session:
chat = get_or_create_chat(session, user)
Expand Down Expand Up @@ -283,6 +312,15 @@ async def starred_command(self, update: Update, context: ContextTypes.DEFAULT_TY
"Subscribe to the user or add user's repos once?",
reply_markup=reply_markup)

async def settings_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /settings is issued."""
keyboard = [[InlineKeyboardButton("Release note format", callback_data="release_note_format")],
[InlineKeyboardButton("Cancel", callback_data="cancel")]]
reply_markup = InlineKeyboardMarkup(keyboard)

await update.message.reply_text(f"Settings",
reply_markup=reply_markup)

async def stats_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /stats is issued."""
with Session(engine) as session:
Expand Down

0 comments on commit 184e823

Please sign in to comment.