Skip to content

Commit

Permalink
feat: expand to see.
Browse files Browse the repository at this point in the history
## Summary by Sourcery

Add new features for sending and managing gifts, including methods for sending gifts and managing their visibility. Enhance the chat event system with new event types and improve message handling with support for new message types and translation. Update the build process to separate build and publish steps.

New Features:

- Introduce the ability to send and manage gifts, including methods for sending gifts, getting available gifts, and toggling gift visibility on user profiles.
- Add support for new message types such as user gifts, star gifts, and gift codes, enhancing the messaging capabilities.
- Implement a new method for translating message text to different languages, expanding the functionality of message handling.

Enhancements:

- Enhance the chat event system by adding new event types related to usernames, membership changes, and chat settings toggles.
- Improve the message reply system by adding support for cross-chat replies and allowing paid broadcasts for bots.
- Refactor the message parsing logic to support new service message types and improve the handling of existing ones.

Build:

- Update the build and publish process in the CI workflow to separate the build and publish steps, and switch to using a GitHub Action for publishing to PyPI.
  • Loading branch information
5hojib authored Nov 24, 2024
1 parent 3271662 commit 87f4f36
Show file tree
Hide file tree
Showing 53 changed files with 1,317 additions and 219 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/format_and_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ on:

jobs:
lint-format-and-test:
permissions:
contents: write
runs-on: ubuntu-latest

steps:
Expand Down
13 changes: 8 additions & 5 deletions .github/workflows/tag_and_publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ on:
jobs:
tag_and_publish:
runs-on: ubuntu-latest
environment: release
permissions:
id-token: write

steps:
- name: Checkout Repository
Expand Down Expand Up @@ -49,13 +52,13 @@ jobs:
release_name: Release ${{ env.VERSION }}
body_path: ./release_notes.txt

- name: Build and Publish Python Package
- name: Build
if: env.RELEASE_EXISTS == 'false'
run: |
python -m pip install --upgrade pip
pip install -e '.[dev]'
hatch build
hatch publish
env:
HATCH_INDEX_USER: __token__
HATCH_INDEX_AUTH: ${{ secrets.PYPI_API_TOKEN }}
- name: Publish
if: env.RELEASE_EXISTS == 'false'
uses: pypa/gh-action-pypi-publish@release/v1
122 changes: 45 additions & 77 deletions compiler/api/source/main_api.tl

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions compiler/docs/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,11 @@ def get_title_list(s: str) -> list:
get_bot_info
set_bot_info
get_collectible_item_info
get_available_gifts
get_user_gifts
sell_gift
send_gift
toggle_gift_is_saved
""",
"business": """
Telegram Business
Expand Down Expand Up @@ -490,6 +495,8 @@ def get_title_list(s: str) -> list:
ScreenshotTaken
Game
GiftedPremium
Gift
UserGift
Giveaway
GiveawayLaunched
GiveawayResult
Expand Down Expand Up @@ -739,6 +746,7 @@ def get_title_list(s: str) -> list:
Message.react
Message.wait_for_click
Message.pay
UserGift.toggle
""",
"chat": """
Chat
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ dependencies = [
"pysocks",
"aiosqlite",
"pymediainfo",
"pymongo==4.10.1",
"TgCrypto-pyrofork",
"pymongo",
"ElectroCrypto",
]
requires-python = ">=3.10"

Expand Down
2 changes: 1 addition & 1 deletion pyrogram/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

__version__ = "v0.1.192"
__version__ = "v0.1.194"
__license__ = "MIT License"

from concurrent.futures.thread import ThreadPoolExecutor
Expand Down
25 changes: 23 additions & 2 deletions pyrogram/enums/chat_event_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ class ChatEventAction(AutoName):
USERNAME_CHANGED = auto()
"the chat username has been changed (see ``old_username`` and ``new_username``)"

USERNAMES_CHANGED = auto()
"the chat username has been changed (see ``old_usernames`` and ``new_usernames``)"

CHAT_PERMISSIONS_CHANGED = auto()
"the default chat permissions has been changed (see ``old_chat_permissions`` and ``new_chat_permissions``)"

Expand Down Expand Up @@ -59,8 +62,11 @@ class ChatEventAction(AutoName):
MEMBER_JOINED = auto()
"a member joined by themselves. (see ``user``)"

# MEMBER_JOINED_BY_LINK = auto()
""
MEMBER_JOINED_BY_LINK = auto()
"a new member joined the chat via an invite link (see ``invite_link``)"

MEMBER_JOINED_BY_REQUEST = auto()
"a new member was accepted to the chat by an administrator (see ``invite_link`` and ``approver_user``)"

MEMBER_LEFT = auto()
"a member left by themselves. (see ``user``)"
Expand Down Expand Up @@ -116,5 +122,20 @@ class ChatEventAction(AutoName):
DELETED_FORUM_TOPIC = auto()
"a forum topic has been deleted (see `deleted_forum_topic`)"

MEMBER_SUBSCRIPTION_EXTENDED = auto()
"A chat member extended their subscription to the chat (``old_chat_member`` and ``new_chat_member``)"

SHOW_MESSAGE_SENDER_ENABLED = auto()
"the show message senders have been enabled or disabled (see ``show_message_sender_enabled``)"

AGGRESSIVE_ANTI_SPAM_TOGGLED = auto()
"The ``has_aggressive_anti_spam_enabled`` setting of a supergroup was toggled. (see ``has_aggressive_anti_spam_enabled``)"

PROTECTED_CONTENT_TOGGLED = auto()
"The ``has_protected_content`` setting of a channel was toggled (see ``has_protected_content``)"

CHAT_IS_FORUM_TOGGLED = auto()
"The ``is_forum`` setting of a channel was toggled. (see ``is_forum``)"

UNKNOWN = auto()
"Unknown chat event action"
6 changes: 6 additions & 0 deletions pyrogram/enums/message_service_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ class MessageServiceType(AutoName):
GIFTED_PREMIUM = auto()
"Gifted Premium"

USER_GIFT = auto()
"Star gift"

STAR_GIFT = auto()
"Star gift"

GIVEAWAY_LAUNCHED = auto()
"Giveaway Launch"

Expand Down
32 changes: 32 additions & 0 deletions pyrogram/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,38 @@ async def game_filter(_, __, m: Message):
"""Filter messages that contain :obj:`~pyrogram.types.Game` objects."""


async def giveaway_filter(_, __, m: Message):
return bool(m.giveaway)


giveaway = create(giveaway_filter)
"""Filter messages that contain :obj:`~pyrogram.types.Giveaway` objects."""


async def giveaway_result_filter(_, __, m: Message):
return bool(m.giveaway_winners or m.giveaway_completed)


giveaway_result = create(giveaway_result_filter)
"""Filter messages that contain :obj:`~pyrogram.types.GiveawayWinners` or :obj:`~pyrogram.types.GiveawayCompleted` objects."""


async def gift_code_filter(_, __, m: Message):
return bool(m.gift_code)


gift_code = create(gift_code_filter)
"""Filter messages that contain :obj:`~pyrogram.types.GiftCode` objects."""


async def user_gift_filter(_, __, m: Message):
return bool(m.user_gift)


user_gift = create(user_gift_filter)
"""Filter messages that contain :obj:`~pyrogram.types.UserGift` objects."""


async def video_filter(_, __, m: Message):
return bool(m.video)

Expand Down
5 changes: 5 additions & 0 deletions pyrogram/methods/bots/send_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ async def send_game(
business_connection_id: str | None = None,
reply_to_message_id: int | None = None,
protect_content: bool | None = None,
allow_paid_broadcast: bool | None = None,
message_effect_id: int | None = None,
reply_markup: types.InlineKeyboardMarkup
| types.ReplyKeyboardMarkup
Expand Down Expand Up @@ -52,6 +53,9 @@ async def send_game(
protect_content (``bool``, *optional*):
Protects the contents of the sent message from forwarding and saving.
allow_paid_broadcast (``bool``, *optional*):
Pass True to allow the message to ignore regular broadcast limits for a small fee; for bots only
message_effect_id (``int`` ``64-bit``, *optional*):
Unique identifier of the message effect to be added to the message; for private chats only.
Expand Down Expand Up @@ -87,6 +91,7 @@ async def send_game(
reply_to=reply_to,
random_id=self.rnd_id(),
noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
effect=message_effect_id,
reply_markup=await reply_markup.write(self) if reply_markup else None,
)
Expand Down
18 changes: 15 additions & 3 deletions pyrogram/methods/bots/send_inline_bot_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async def send_inline_bot_result(
quote_text: str | None = None,
quote_entities: list[types.MessageEntity] | None = None,
parse_mode: enums.ParseMode | None = None,
) -> raw.base.Updates:
) -> types.Message:
"""Send an inline bot result.
Bot results can be retrieved using :meth:`~pyrogram.Client.get_inline_bot_results`
Expand Down Expand Up @@ -60,7 +60,7 @@ async def send_inline_bot_result(
For quote_text.
Returns:
:obj:`~pyrogram.raw.base.Updates`: Currently, on success, a raw result is returned.
:obj:`~pyrogram.types.Message`: On success, the sent message is returned.
Example:
.. code-block:: python
Expand All @@ -78,7 +78,7 @@ async def send_inline_bot_result(
parse_mode=parse_mode,
)

return await self.invoke(
r = await self.invoke(
raw.functions.messages.SendInlineBotResult(
peer=await self.resolve_peer(chat_id),
query_id=query_id,
Expand All @@ -88,3 +88,15 @@ async def send_inline_bot_result(
reply_to=reply_to,
)
)

for i in r.updates:
if isinstance(
i, raw.types.UpdateNewMessage | raw.types.UpdateNewChannelMessage
):
return await types.Message._parse(
self,
i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats},
)
return None
10 changes: 10 additions & 0 deletions pyrogram/methods/business/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,30 @@
from .answer_pre_checkout_query import AnswerPreCheckoutQuery
from .answer_shipping_query import AnswerShippingQuery
from .create_invoice_link import CreateInvoiceLink
from .get_available_gifts import GetAvailableGifts
from .get_business_connection import GetBusinessConnection
from .get_payment_form import GetPaymentForm
from .get_stars_transactions import GetStarsTransactions
from .get_stars_transactions_by_id import GetStarsTransactionsById
from .get_user_gifts import GetUserGifts
from .refund_stars_payment import RefundStarPayment
from .sell_gift import SellGift
from .send_gift import SendGift
from .send_invoice import SendInvoice
from .send_payment_form import SendPaymentForm
from .toggle_gift_is_saved import ToggleGiftIsSaved


class TelegramBusiness(
AnswerPreCheckoutQuery,
AnswerShippingQuery,
CreateInvoiceLink,
GetBusinessConnection,
GetAvailableGifts,
GetUserGifts,
SellGift,
SendGift,
ToggleGiftIsSaved,
GetStarsTransactions,
GetStarsTransactionsById,
RefundStarPayment,
Expand Down
25 changes: 25 additions & 0 deletions pyrogram/methods/business/get_available_gifts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from __future__ import annotations

import pyrogram
from pyrogram import raw, types


class GetAvailableGifts:
async def get_available_gifts(
self: pyrogram.Client,
) -> list[types.Gift]:
"""Get all gifts that can be sent to other users.
.. include:: /_includes/usable-by/users.rst
Returns:
List of :obj:`~pyrogram.types.Gift`: On success, a list of star gifts is returned.
Example:
.. code-block:: python
app.get_available_gifts()
"""
r = await self.invoke(raw.functions.payments.GetStarGifts(hash=0))

return types.List([await types.Gift._parse(self, gift) for gift in r.gifts])
81 changes: 81 additions & 0 deletions pyrogram/methods/business/get_user_gifts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from __future__ import annotations

from typing import TYPE_CHECKING

import pyrogram
from pyrogram import raw, types

if TYPE_CHECKING:
from collections.abc import AsyncGenerator


class GetUserGifts:
async def get_user_gifts(
self: pyrogram.Client,
user_id: int | str,
offset: str = "",
limit: int = 0,
) -> AsyncGenerator[types.UserGift, None] | None:
"""Get gifts saved to profile by the given user.
.. include:: /_includes/usable-by/users.rst
Parameters:
user_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target user.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in your Telegram address book you can use his phone number (str).
offset (``str``, *optional*):
Offset of the first entry to return as received from the previous request; use empty string to get the first chunk of results.
limit (``int``, *optional*):
The maximum number of gifts to be returned; must be positive and can't be greater than 100. For optimal performance, the number of returned objects is chosen by Telegram Server and can be smaller than the specified limit.
Returns:
``Generator``: A generator yielding :obj:`~pyrogram.types.UserGift` objects.
Example:
.. code-block:: python
async for user_gift in app.get_user_gifts(user_id):
print(user_gift)
"""
peer = await self.resolve_peer(user_id)

if not isinstance(peer, raw.types.InputPeerUser | raw.types.InputPeerSelf):
raise ValueError("user_id must belong to a user.")

current = 0
total = abs(limit) or (1 << 31) - 1
limit = min(100, total)

while True:
r = await self.invoke(
raw.functions.payments.GetUserStarGifts(
user_id=peer, offset=offset, limit=limit
),
sleep_threshold=max(60, self.sleep_threshold),
)

users = {u.id: u for u in r.users}

user_gifts = [
await types.UserGift._parse(self, gift, users) for gift in r.gifts
]

if not user_gifts:
return

for user_gift in user_gifts:
yield user_gift

current += 1

if current >= total:
return

offset = r.next_offset

if not offset:
return
Loading

0 comments on commit 87f4f36

Please sign in to comment.