Skip to content

Commit

Permalink
Refactor/ptb 20.8 (#159)
Browse files Browse the repository at this point in the history
* chore: enable links for basic bot commands

* chore: align with the new telegram APIs

* test: align with the new telegram APIS

* fix: ignore user problems when following posts

* style: linting and formatting

* chore: update CHANGELOG
  • Loading branch information
TendTo authored Feb 18, 2024
1 parent 2fa677f commit 8ee62f3
Show file tree
Hide file tree
Showing 11 changed files with 95 additions and 45 deletions.
8 changes: 7 additions & 1 deletion .github/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

...

## [3.1.0] - 2024-02-18

### Added

- **/ban** command can now also be used on reports
Expand All @@ -22,7 +26,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added readme overview page in the docs
- Added Privacy Policy in the docs. It is referenced in the bot **/start** command
- Use mermaid to generate entity relationship diagrams in the docs
- Bump python-telegram-bot to version 2.8
- Bump python-telegram-bot to version 2.8, aligning the code to the new API
- Enabled links in basic bot commands

## [3.0.0] - 2023-11-30

Expand Down Expand Up @@ -59,3 +64,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Duplicate index file for the english version

[3.0.0]: https://github.com/UNICT-DMI/Telegram-SpottedDMI-Bot/compare/upgrade...3.0.0
[3.1.0]: https://github.com/UNICT-DMI/Telegram-SpottedDMI-Bot/compare/3.0.0...3.1.0
6 changes: 5 additions & 1 deletion src/spotted/handlers/follow_comment.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Detect Comment on a post in the comment group"""

from telegram import Update
from telegram.error import BadRequest, Forbidden
from telegram.ext import CallbackContext

from spotted.data import User
Expand All @@ -26,4 +27,7 @@ async def follow_spot_comment(update: Update, context: CallbackContext):
for user in users:
# Avoid sending if it's made by the same user
if not user.user_id == info.message.from_user.id:
await info.message.copy(chat_id=user.user_id, reply_to_message_id=user.private_message_id)
try:
await info.message.copy(chat_id=user.user_id, reply_to_message_id=user.private_message_id)
except (BadRequest, Forbidden): # The user deleted the message or blocked the bot, ignore
pass
5 changes: 2 additions & 3 deletions src/spotted/handlers/forwarded_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ async def forwarded_post_msg(update: Update, context: CallbackContext):
context: context passed by the handler
"""
info = EventInfo.from_message(update, context)
if update.message is None or update.message.forward_from_chat is None:
if info.message is None or not info.is_forwarded_post:
return

if info.is_forwarded_post:
await info.send_post_to_channel_group()
await info.send_post_to_channel_group()
4 changes: 1 addition & 3 deletions src/spotted/handlers/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,4 @@ async def help_cmd(update: Update, context: CallbackContext):
text = read_md("instructions")
else: # you are NOT in the admin group
text = read_md("help")
await info.bot.send_message(
chat_id=info.chat_id, text=text, parse_mode=ParseMode.MARKDOWN_V2, disable_web_page_preview=True
)
await info.bot.send_message(chat_id=info.chat_id, text=text, parse_mode=ParseMode.MARKDOWN_V2)
4 changes: 1 addition & 3 deletions src/spotted/handlers/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,4 @@ async def rules_cmd(update: Update, context: CallbackContext):
"""
info = EventInfo.from_message(update, context)
text = read_md("rules")
await info.bot.send_message(
chat_id=info.chat_id, text=text, parse_mode=ParseMode.MARKDOWN_V2, disable_web_page_preview=True
)
await info.bot.send_message(chat_id=info.chat_id, text=text, parse_mode=ParseMode.MARKDOWN_V2)
4 changes: 1 addition & 3 deletions src/spotted/handlers/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,4 @@ async def start_cmd(update: Update, context: CallbackContext):
"""
info = EventInfo.from_message(update, context)
text = read_md("start")
await info.bot.send_message(
chat_id=info.chat_id, text=text, parse_mode=ParseMode.MARKDOWN_V2, disable_web_page_preview=True
)
await info.bot.send_message(chat_id=info.chat_id, text=text, parse_mode=ParseMode.MARKDOWN_V2)
51 changes: 44 additions & 7 deletions src/spotted/utils/info_util.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
"""Common info needed in both command and callback handlers"""

from telegram import Bot, CallbackQuery, Chat, InlineKeyboardMarkup, Message, Update
from telegram import (
Bot,
CallbackQuery,
Chat,
InlineKeyboardMarkup,
LinkPreviewOptions,
Message,
MessageOriginChannel,
MessageOriginChat,
MessageOriginUser,
Update,
)
from telegram.error import BadRequest
from telegram.ext import CallbackContext

Expand Down Expand Up @@ -199,20 +210,46 @@ def forward_from_id(self) -> int:
"""Id of the original message that has been forwarded"""
if self.__message is None:
return None
return self.__message.forward_from_message_id
if isinstance(self.__message.forward_origin, MessageOriginChannel):
return self.__message.forward_origin.message_id
return None

@property
def forward_from_chat_id(self) -> int:
"""Id of the original chat the message has been forwarded from"""
if self.__message is None or self.__message.forward_from_chat is None:
if self.__message is None:
return None
return self.__message.forward_from_chat.id
if isinstance(self.__message.forward_origin, MessageOriginChannel):
return self.__message.forward_origin.chat.id
if isinstance(self.__message.forward_origin, MessageOriginChat):
return self.__message.forward_origin.sender_chat.id
if isinstance(self.__message.forward_origin, MessageOriginUser):
return self.__message.forward_origin.sender_user.id
return None

@property
def is_forward_from_channel(self) -> bool:
"""Whether the message has been forwarded from a channel"""
return isinstance(self.__message.forward_origin, MessageOriginChannel)

@property
def is_forward_from_chat(self) -> bool:
"""Whether the message has been forwarded from a chat"""
return isinstance(self.__message.forward_origin, MessageOriginChat)

@property
def is_forward_from_user(self) -> bool:
"""Whether the message has been forwarded from a user"""
return isinstance(self.__message.forward_origin, MessageOriginUser)

@property
def is_forwarded_post(self) -> bool:
"""Whether the message is in fact a forwarded post from the channel to the group"""
return self.chat_id == Config.post_get("community_group_id") and self.forward_from_chat_id == Config.post_get(
"channel_id"
return (
self.chat_id == Config.post_get("community_group_id")
and isinstance(self.__message.forward_origin, MessageOriginChannel)
and self.__message.forward_origin.chat.id == Config.post_get("channel_id")
and self.__message.is_automatic_forward
)

@classmethod
Expand Down Expand Up @@ -315,7 +352,7 @@ async def send_post_to_admins(self) -> bool:
text=message.text,
reply_markup=get_approve_kb(),
entities=message.entities,
disable_web_page_preview=not show_preview,
link_preview_options=LinkPreviewOptions(not show_preview),
)
else:
g_message = await self.__bot.copy_message(
Expand Down
33 changes: 26 additions & 7 deletions tests/integration/telegram_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@
from telegram import (
Chat,
InlineKeyboardMarkup,
LinkPreviewOptions,
Message,
MessageEntity,
MessageOriginChannel,
MessageOriginChat,
MessageOriginUser,
ReplyKeyboardMarkup,
User,
)
Expand All @@ -30,7 +34,7 @@ class MessageData(TypedDict):
allow_sending_without_reply: bool | None
protect_content: bool | None
parse_mode: ParseMode | None
disable_web_page_preview: bool | None
link_preview_options: LinkPreviewOptions | None
reply_markup: ReplyKeyboardMarkup | InlineKeyboardMarkup | None


Expand All @@ -47,6 +51,26 @@ def __init__(self, simulator: "TelegramSimulator"):
id=Config.post_get("community_group_id"), type=Chat.GROUP
)

def get_forward_origin(
self, forward_message: int | Message
) -> MessageOriginChannel | MessageOriginChat | MessageOriginUser:
if isinstance(forward_message, int):
forward_message = self.__simulator.get_message_by_id(forward_message)
if forward_message.chat.type == Chat.PRIVATE:
return MessageOriginUser(datetime.now(), forward_message.from_user.id)
if forward_message.chat.type == Chat.CHANNEL:
return MessageOriginChannel(
datetime.now(),
Chat(forward_message.chat.id, Chat.CHANNEL, "channel"),
forward_message.id,
forward_message.author_signature,
)
if forward_message.chat.type == Chat.GROUP:
return MessageOriginChat(
datetime.now(), Chat(forward_message.chat.id, Chat.GROUP, "group"), forward_message.author_signature
)
return None

@classmethod
def get_next_id(cls) -> int:
"""Returns the current message id and increases it by one"""
Expand Down Expand Up @@ -110,12 +134,7 @@ def __forward_message(self, data: "MessageData") -> dict:
entities=forward_message.entities,
reply_markup=data.get("reply_markup", None),
reply_to_message=forward_message.reply_to_message,
forward_date=forward_message.date,
forward_from=forward_message.from_user,
forward_from_chat=forward_message.chat,
forward_signature=forward_message.forward_signature,
forward_sender_name=forward_message.forward_sender_name,
forward_from_message_id=forward_message.message_id,
forward_origin=self.get_forward_origin(forward_message),
)
self.__simulator.add_message(message)
return message.to_dict()
Expand Down
6 changes: 2 additions & 4 deletions tests/integration/telegram_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,11 @@ async def send_forward_message(
"""
if isinstance(forward_message, int):
forward_message = self.get_message_by_id(forward_message)

if message is None:
message = self.make_message(
text=forward_message.text,
forward_from_chat=forward_message.chat,
forward_from=forward_message.from_user,
forward_from_message_id=forward_message.message_id,
forward_date=forward_message.date,
forward_origin=self.__api.get_forward_origin(forward_message),
user=user,
chat=chat,
date=date,
Expand Down
4 changes: 0 additions & 4 deletions tests/unit/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ async def test_start_cmd(self, update: Update, context: CallbackContext):
chat_id=update.message.chat_id,
text=read_md("start"),
parse_mode=ParseMode.MARKDOWN_V2,
disable_web_page_preview=True,
)

async def test_help_cmd(self, update: Update, context: CallbackContext):
Expand All @@ -65,7 +64,6 @@ async def test_help_cmd(self, update: Update, context: CallbackContext):
chat_id=update.message.chat_id,
text=read_md("help"),
parse_mode=ParseMode.MARKDOWN_V2,
disable_web_page_preview=True,
)

async def test_help_admin_cmd(self, context: CallbackContext):
Expand All @@ -84,7 +82,6 @@ async def test_help_admin_cmd(self, context: CallbackContext):
chat_id=update.message.chat_id,
text=read_md("instructions"),
parse_mode=ParseMode.MARKDOWN_V2,
disable_web_page_preview=True,
)

async def test_rules_cmd(self, update: Update, context: CallbackContext):
Expand All @@ -96,7 +93,6 @@ async def test_rules_cmd(self, update: Update, context: CallbackContext):
chat_id=update.message.chat_id,
text=read_md("rules"),
parse_mode=ParseMode.MARKDOWN_V2,
disable_web_page_preview=True,
)

async def test_settings_cmd(self, update: Update, context: CallbackContext):
Expand Down
15 changes: 6 additions & 9 deletions tests/unit/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from datetime import datetime

import pytest
from telegram import CallbackQuery, Chat, Message, Update, User
from telegram import CallbackQuery, Chat, Message, MessageOriginChat, Update, User
from telegram.ext import Application, CallbackContext

from spotted.utils import EventInfo
Expand Down Expand Up @@ -56,10 +56,7 @@ def get_message(get_user: User, get_chat: Chat) -> Message:
"date": datetime.now(),
"chat": get_chat,
"from_user": get_user,
"forward_from": get_user,
"forward_from_chat": get_chat,
"forward_from_message_id": 1000,
"forward_date": datetime.now(),
"forward_origin": MessageOriginChat(datetime.now(), get_chat),
"text": "Tets text",
}
return Message(**message_data)
Expand Down Expand Up @@ -149,8 +146,8 @@ def test_message_info(

assert info.query_id is None
assert info.query_data is None
assert info.forward_from_id == get_message.forward_from_message_id
assert info.forward_from_chat_id == get_message.forward_from_chat.id
assert info.forward_from_id is None
assert info.forward_from_chat_id == get_message.forward_origin.sender_chat.id

def test_callback_info(
self,
Expand Down Expand Up @@ -184,8 +181,8 @@ def test_callback_info(

assert info.query_id == get_callback_query.id
assert info.query_data == get_callback_query.data
assert info.forward_from_id == get_message.forward_from_message_id
assert info.forward_from_chat_id == get_message.forward_from_chat.id
assert info.forward_from_id is None
assert info.forward_from_chat_id == get_message.forward_origin.sender_chat.id

def test_job_info(self, job_update: CallbackContext):
"""Tests the :meth:`from_job` :class:`EventInfo` initialization"""
Expand Down

0 comments on commit 8ee62f3

Please sign in to comment.