Skip to content

Commit

Permalink
feat: Filter listen_forward message by sender
Browse files Browse the repository at this point in the history
  • Loading branch information
tangyoha committed Aug 23, 2023
1 parent 852cc9d commit cf7a2b8
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 12 deletions.
98 changes: 86 additions & 12 deletions module/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ async def start(
# 命令列表
commands = [
types.BotCommand("help", _t("Help")),
types.BotCommand(
"get_info", _t("Get group and user info from message link")
),
types.BotCommand(
"download",
_t(
Expand Down Expand Up @@ -181,6 +184,9 @@ async def start(
self.bot.add_handler(
MessageHandler(help_command, filters=pyrogram.filters.command(["help"]))
)
self.bot.add_handler(
MessageHandler(get_info, filters=pyrogram.filters.command(["get_info"]))
)
self.bot.add_handler(
MessageHandler(help_command, filters=pyrogram.filters.command(["start"]))
)
Expand Down Expand Up @@ -219,11 +225,7 @@ async def start(
admin = await self.client.get_me()

try:
await self.bot.send_message(
admin.id,
f"```\n🤖 {_t('Telegram Media Downloader')}\n"
f"└─ 🌐 {_t('Version')}: {utils.__version__}```\n",
)
await send_help_str(self.bot, admin.id)
except Exception:
pass
# TODO: add admin
Expand Down Expand Up @@ -251,31 +253,53 @@ def stop_download_bot():
_bot.is_running = False


async def help_command(client: pyrogram.Client, message: pyrogram.types.Message):
async def send_help_str(client: pyrogram.Client, chat_id):
"""
Sends a message with the available commands and their usage.
Sends a help string to the specified chat ID using the provided client.
Parameters:
client (pyrogram.Client): The client instance.
message (pyrogram.types.Message): The message object.
client (pyrogram.Client): The Pyrogram client used to send the message.
chat_id: The ID of the chat to which the message will be sent.
Returns:
None
str: The help string that was sent.
Note:
The help string includes information about the Telegram Media Downloader bot,
its version, and the available commands.
"""
msg = (
f"```\n🤖 {_t('Telegram Media Downloader')}\n"
f"🌐 {_t('Version')}: {utils.__version__}```\n\n"
f"{_t('Available commands:')}\n"
f"/help - {_t('Show available commands')}\n"
f"/get_info - {_t('Get group and user info from message link')}\n"
# f"/add_filter - {_t('Add download filter')}\n"
f"/download - {_t('Download messages')}\n"
f"/forward - {_t('Forward messages')}\n"
f"/listen_forward - {_t('Listen for forwarded messages')}\n"
f"/set_language - {_t('Set language')}\n"
f"/set_language - {_t('Set language')}\n\n"
f"{_t('**Note**: 1 means the start of the entire chat')},"
f"{_t('0 means the end of the entire chat')}\n"
f"`[` `]` {_t('means optional, not required')}\n"
)

await client.send_message(message.chat.id, msg)
await client.send_message(chat_id, msg)


async def help_command(client: pyrogram.Client, message: pyrogram.types.Message):
"""
Sends a message with the available commands and their usage.
Parameters:
client (pyrogram.Client): The client instance.
message (pyrogram.types.Message): The message object.
Returns:
None
"""

await send_help_str(client, message.chat.id)


async def set_language(client: pyrogram.Client, message: pyrogram.types.Message):
Expand Down Expand Up @@ -312,6 +336,56 @@ async def set_language(client: pyrogram.Client, message: pyrogram.types.Message)
)


async def get_info(client: pyrogram.Client, message: pyrogram.types.Message):
"""
Async function that retrieves information from a group message link.
"""

msg = _t("Invalid command format. Please use /get_info group_message_link")

args = message.text.split()
if len(args) != 2:
await client.send_message(
message.from_user.id,
msg,
)
return

chat_id, message_id = extract_info_from_link(args[1])

entity = None
if chat_id:
entity = await _bot.client.get_chat(chat_id)

if entity:
if message_id:
_message = await get_message_with_retry(_bot.client, chat_id, message_id)
if _message:
meta_data = MetaData()
set_meta_data(meta_data, _message)
msg = (
f"```\n"
f"{_t('Group/Channel')}\n"
f"├─ {_t('id')}: {entity.id}\n"
f"├─ {_t('first name')}: {entity.first_name}\n"
f"├─ {_t('last name')}: {entity.last_name}\n"
f"└─ {_t('name')}: {entity.username}\n"
f"{_t('Message')}\n"
)

for key, value in meta_data.data().items():
if key == "send_name":
msg += f"└─ {key}: {value or None}\n"
else:
msg += f"├─ {key}: {value or None}\n"

msg += "```"
await client.send_message(
message.from_user.id,
msg,
)


async def add_filter(client: pyrogram.Client, message: pyrogram.types.Message):
"""
Set the download filter of the bot.
Expand Down
5 changes: 5 additions & 0 deletions module/language.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,11 @@ def set_language(language: Language):
"actual": ["实际", "фактический", "фактичний"],
"file name": ["文件名", "имя файла", "ім'я файлу"],
"Successfully downloaded": ["成功下载", "Успешно скачано", "Успішно скачано"],
"Get group and user info from message link": [
"从消息链接中获取群组和用户信息",
"Получить информацию о группе и пользователе по ссылке на сообщение",
"Отримайте інформацію про групу та користувача за посиланням у повідомленні",
],
}


Expand Down
6 changes: 6 additions & 0 deletions module/pyrogram_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,12 @@ def set_meta_data(
else:
meta_data.message_caption = getattr(message, "caption", None) or ""
meta_data.message_id = getattr(message, "id", None)

from_user = getattr(message, "from_user")
meta_data.sender_id = from_user.id if from_user else 0
meta_data.sender_name = (from_user.username if from_user else "") or ""

# media
for kind in meta_data.AVAILABLE_MEDIA:
media_obj = getattr(message, kind, None)
if media_obj is not None:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def __init__(self, **kwargs):
self.caption = kwargs.get("caption", None)
self.text = None
self.empty = kwargs.get("empty", False)
self.from_user = kwargs.get("from_user", None)

if kwargs.get("dis_chat") == None:
self.chat = Chat(
Expand All @@ -44,6 +45,12 @@ def __init__(self, **kwargs):
self.date = kwargs["date"]


class MockUser:
def __init__(self, **kwargs):
self.id = kwargs.get("id", 0)
self.username = kwargs.get("username", "")


class MockAudio:
def __init__(self, **kwargs):
self.file_name = kwargs["file_name"]
Expand Down
10 changes: 10 additions & 0 deletions tests/utils/test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
MockDocument,
MockMessage,
MockPhoto,
MockUser,
MockVideo,
MockVideoNote,
MockVoice,
Expand Down Expand Up @@ -56,6 +57,10 @@ def test_string_filter(self):
height=1080,
duration=35,
),
from_user=MockUser(
username="coco",
id=123,
),
)

set_meta_data(meta, message)
Expand Down Expand Up @@ -239,6 +244,11 @@ def test_string_filter(self):
filter_exec(download_filter, "file_extension != r'(mp4|mp3)'"), False
)

# test sender
self.assertEqual(filter_exec(download_filter, "sender_name == 'coco'"), True)

self.assertEqual(filter_exec(download_filter, "sender_id == 1"), False)

def test_null_obj(self):
download_filter = Filter()

Expand Down
8 changes: 8 additions & 0 deletions utils/meta_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ class MetaData:
* `media_file_name` : - file name
* `message_caption` : - message_caption
* `message_duration` : - message_duration
* `sender_id` : - Sender id, empty for messages sent to channels.
* `sender_name` : - Sender name, empty for messages sent to channels.
"""

AVAILABLE_MEDIA = (
Expand All @@ -54,6 +56,8 @@ def __init__(
media_duration: int = None,
media_type: str = None,
file_extension: str = None,
sender_id: int = None,
sender_name: str = None,
):
self.message_date = message_date
self.message_id = message_id
Expand All @@ -65,6 +69,8 @@ def __init__(
self.media_duration = media_duration
self.media_type = media_type
self.file_extension = file_extension
self.sender_id = sender_id
self.sender_name = sender_name

def data(self) -> dict:
"""Meta map"""
Expand All @@ -84,4 +90,6 @@ def data(self) -> dict:
"file_name": self.media_file_name,
"media_type": self.media_type,
"file_extension": self.file_extension,
"sender_id": self.sender_id,
"sender_name": self.sender_name,
}

0 comments on commit cf7a2b8

Please sign in to comment.