Skip to content

Commit

Permalink
Steal Star Gifts changes from KurimuzonAkuma fork (#100)
Browse files Browse the repository at this point in the history
Co-authored-by: KurimuzonAkuma <[email protected]>
  • Loading branch information
SpEcHiDe and KurimuzonAkuma authored Oct 25, 2024
1 parent c8cb9b5 commit 58e1f55
Show file tree
Hide file tree
Showing 18 changed files with 749 additions and 12 deletions.
8 changes: 8 additions & 0 deletions compiler/docs/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,11 @@ def get_title_list(s: str) -> list:
get_collectible_item_info
get_payment_form
send_payment_form
get_available_gifts
get_user_gifts
sell_gift
send_gift
toggle_gift_is_saved
""",
advanced="""
Advanced
Expand Down Expand Up @@ -509,6 +514,8 @@ def get_title_list(s: str) -> list:
Poll
Location
Venue
Gift
UserGift
WebAppData
MessageAutoDeleteTimerChanged
ChatBoostAdded
Expand Down Expand Up @@ -735,6 +742,7 @@ def get_title_list(s: str) -> list:
Message.translate
Message.pay
Message.star
UserGift.toggle
""",
chat="""
Chat
Expand Down
1 change: 1 addition & 0 deletions compiler/errors/source/400_BAD_REQUEST.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ PHOTO_SAVE_FILE_INVALID Internal issues, try again later.
PHOTO_THUMB_URL_EMPTY Photo thumbnail URL is empty.
PHOTO_THUMB_URL_INVALID The photo thumb URL is invalid
PINNED_DIALOGS_TOO_MUCH Too many pinned dialogs.
PINNED_TOPIC_NOT_MODIFIED The pinned topic was not modified.
PIN_RESTRICTED You can't pin messages.
PLATFORM_INVALID The provided platform is invalid. Allowed values are "android", "ios", "wp", "bb", "desktop", "web", "ubp", "other".
POLL_ANSWERS_INVALID Invalid poll answers were provided.
Expand Down
1 change: 1 addition & 0 deletions docs/source/releases/changes-in-this-fork.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ If you found any issue or have any suggestions, feel free to make `an issue <htt
| Scheme layer used: 190 |
+------------------------+

- Added the methods :meth:`~pyrogram.Client.get_available_gifts`, :meth:`~pyrogram.Client.get_user_gifts`, :meth:`~pyrogram.Client.sell_gift`, :meth:`~pyrogram.Client.send_gift`, :meth:`~pyrogram.Client.toggle_gift_is_saved`, :meth:`~pyrogram.types.UserGift.toggle` and the types :obj:`~pyrogram.types.UserGift` and :obj:`~pyrogram.types.Gift`.
- Added the parameter ``send_as`` in the appropriate methods and bound methods `PR 107 <https://github.com/TelegramPlayGround/pyrogram/pull/107>`_.
- View `new and changed <https://telegramplayground.github.io/TG-APIs/TL/diff/tdlib.html?from=189&to=190>`__ `raw API methods <https://telegramplayground.github.io/TG-APIs/TL/diff/tdesktop.html?from=189&to=190>`__.

Expand Down
3 changes: 3 additions & 0 deletions pyrogram/enums/message_service_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,5 +141,8 @@ class MessageServiceType(AutoName):
WRITE_ACCESS_ALLOWED = auto()
"The user accepted webapp bot's request to send messages"

USER_GIFT = auto()
"Star gift"

UNKNOWN = auto()
"This service message is unsupported by the current version of Pyrogram"
43 changes: 43 additions & 0 deletions pyrogram/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,49 @@ async def game_filter(_, __, m: Message) -> bool:

# endregion

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


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


# endregion

# region giveaway_result_filter
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."""


# endregion

# region gift_code_filter
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."""


# endregion

# region user_gift
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."""


# endregion

# region video_filter
async def video_filter(_, __, m: Message) -> bool:
Expand Down
14 changes: 12 additions & 2 deletions pyrogram/methods/business/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@
from .get_collectible_item_info import GetCollectibleItemInfo
from .refund_star_payment import RefundStarPayment
from .send_invoice import SendInvoice
from .get_payment_from import GetPaymentForm
from .send_payment_from import SendPaymentForm
from .get_payment_form import GetPaymentForm
from .send_payment_form import SendPaymentForm
from .get_available_gifts import GetAvailableGifts
from .get_user_gifts import GetUserGifts
from .sell_gift import SellGift
from .send_gift import SendGift
from .toggle_gift_is_saved import ToggleGiftIsSaved


class TelegramBusiness(
Expand All @@ -37,5 +42,10 @@ class TelegramBusiness(
SendInvoice,
GetPaymentForm,
SendPaymentForm,
GetAvailableGifts,
GetUserGifts,
SellGift,
SendGift,
ToggleGiftIsSaved,
):
pass
44 changes: 44 additions & 0 deletions pyrogram/methods/business/get_available_gifts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from typing import List

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])
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@

class GetPaymentForm:
async def get_payment_form(
self: "pyrogram.Client", *,
chat_id: Union[int, str] = None,
message_id: int = None,
invoice_link: str = None
self: "pyrogram.Client", *,
chat_id: Union[int, str] = None,
message_id: int = None,
invoice_link: str = None
) -> "types.PaymentForm":
"""Get information about a invoice or paid media.
Expand Down
97 changes: 97 additions & 0 deletions pyrogram/methods/business/get_user_gifts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.

from typing import Union, Optional, AsyncGenerator

import pyrogram
from pyrogram import raw, types


class GetUserGifts:
async def get_user_gifts(
self: "pyrogram.Client",
user_id: Union[int, str],
offset: str = "",
limit: int = 0,
) -> Optional[AsyncGenerator["types.UserGift", 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
67 changes: 67 additions & 0 deletions pyrogram/methods/business/sell_gift.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.


from typing import Union

import pyrogram
from pyrogram import raw


class SellGift:
async def sell_gift(
self: "pyrogram.Client",
sender_user_id: Union[int, str],
message_id: int
) -> bool:
"""Sells a gift received by the current user for Telegram Stars.
.. include:: /_includes/usable-by/users.rst
Parameters:
sender_user_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the user that sent the gift.
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).
message_id (``int``):
Unique identifier of the message with the gift in the chat with the user.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Convert gift
app.sell_gift(sender_user_id=user_id, message_id=123)
"""
peer = await self.resolve_peer(sender_user_id)

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

r = await self.invoke(
raw.functions.payments.ConvertStarGift(
user_id=peer,
msg_id=message_id
)
)

return r
Loading

0 comments on commit 58e1f55

Please sign in to comment.