Add get_user_star_gifts method

Signed-off-by: wulan17 <wulan17@nusantararom.org>
This commit is contained in:
KurimuzonAkuma 2024-10-07 12:07:01 +03:00 committed by wulan17
parent 0a6cc8b5a4
commit f30aa0077a
No known key found for this signature in database
GPG key ID: 318CD6CD3A6AC0A5
11 changed files with 274 additions and 27 deletions

View file

@ -354,6 +354,8 @@ def pyrogram_api():
get_star_gifts
get_stars_transactions
get_stars_transactions_by_id
get_user_star_gifts_count
get_user_star_gifts
hide_star_gift
refund_star_payment
send_invoice
@ -584,6 +586,7 @@ def pyrogram_api():
StarsStatus
StarsTransaction
SuccessfulPayment
UserStarGift
""",
pyromod="""
Pyromod

View file

@ -18,17 +18,15 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from .apply_gift_code import ApplyGiftCode
<<<<<<< HEAD
from .check_giftcode import CheckGiftCode
from .create_invoice_link import CreateInvoiceLink
=======
from .check_gift_code import CheckGiftCode
from .convert_star_gift import ConvertStarGift
>>>>>>> 1473842c6 (Add convert_star_gift method)
from .create_invoice_link import CreateInvoiceLink
from .get_payment_form import GetPaymentForm
from .get_star_gifts import GetStarGifts
from .get_stars_transactions import GetStarsTransactions
from .get_stars_transactions_by_id import GetStarsTransactionsById
from .get_user_star_gifts_count import GetUserStarGiftsCount
from .get_user_star_gifts import GetUserStarGifts
from .hide_star_gift import HideStarGift
from .refund_stars_payment import RefundStarPayment
from .send_invoice import SendInvoice
@ -47,6 +45,8 @@ class Payments(
GetStarGifts,
GetStarsTransactions,
GetStarsTransactionsById,
GetUserStarGiftsCount,
GetUserStarGifts,
HideStarGift,
RefundStarPayment,
SendPaidReaction,

View file

@ -54,11 +54,7 @@ class ConvertStarGift:
"""
peer = await self.resolve_peer(chat_id)
if isinstance(peer, raw.types.InputPeerUser):
peer = raw.types.InputUser(user_id=peer.user_id, access_hash=peer.access_hash)
elif isinstance(peer, raw.types.InputPeerSelf):
peer = raw.types.InputUserSelf()
else:
if not isinstance(peer, (raw.types.InputPeerUser, raw.types.InputPeerSelf)):
raise ValueError("chat_id must belong to a user.")
r = await self.invoke(

View file

@ -0,0 +1,94 @@
# 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, types
class GetUserStarGifts:
async def get_user_star_gifts(
self: "pyrogram.Client",
chat_id: Union[int, str],
limit: int = 0,
offset: str = ""
):
"""Get user star gifts.
.. include:: /_includes/usable-by/users.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
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 results to be returned.
limit (``int``, *optional*):
Maximum amount of star gifts to be returned.
Returns:
``Generator``: A generator yielding :obj:`~pyrogram.types.UserStarGift` objects.
Example:
.. code-block:: python
async for gift in app.get_user_star_gifts(chat_id):
print(gift)
"""
peer = await self.resolve_peer(chat_id)
if not isinstance(peer, (raw.types.InputPeerUser, raw.types.InputPeerSelf)):
raise ValueError("chat_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=60
)
users = {u.id: u for u in r.users}
user_star_gifts = [
await types.UserStarGift._parse(self, gift, users)
for gift in r.gifts
]
if not user_star_gifts:
return
offset = r.next_offset
for gift in user_star_gifts:
yield gift
current += 1
if current >= total:
return

View file

@ -0,0 +1,64 @@
# 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/>.
import logging
from typing import Union
import pyrogram
from pyrogram import raw
log = logging.getLogger(__name__)
class GetUserStarGiftsCount:
async def get_user_star_gifts_count(
self: "pyrogram.Client",
chat_id: Union[int, str]
) -> int:
"""Get the total count of star gifts of specified user.
.. include:: /_includes/usable-by/users.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
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).
Returns:
``int``: On success, the star gifts count is returned.
Example:
.. code-block:: python
await app.get_user_star_gifts_count(chat_id)
"""
peer = await self.resolve_peer(chat_id)
if not isinstance(peer, (raw.types.InputPeerUser, raw.types.InputPeerSelf)):
raise ValueError("chat_id must belong to a user.")
r = await self.invoke(
raw.functions.payments.GetUserStarGifts(
user_id=peer,
offset="",
limit=1
)
)
return r.count

View file

@ -54,11 +54,7 @@ class HideStarGift:
"""
peer = await self.resolve_peer(chat_id)
if isinstance(peer, raw.types.InputPeerUser):
peer = raw.types.InputUser(user_id=peer.user_id, access_hash=peer.access_hash)
elif isinstance(peer, raw.types.InputPeerSelf):
peer = raw.types.InputUserSelf()
else:
if not isinstance(peer, (raw.types.InputPeerUser, raw.types.InputPeerSelf)):
raise ValueError("chat_id must belong to a user.")
r = await self.invoke(

View file

@ -71,11 +71,7 @@ class SendStarGift:
"""
peer = await self.resolve_peer(chat_id)
if isinstance(peer, raw.types.InputPeerUser):
peer = raw.types.InputUser(user_id=peer.user_id, access_hash=peer.access_hash)
elif isinstance(peer, raw.types.InputPeerSelf):
peer = raw.types.InputUserSelf()
else:
if not isinstance(peer, (raw.types.InputPeerUser, raw.types.InputPeerSelf)):
raise ValueError("chat_id must belong to a user.")
text, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()

View file

@ -53,11 +53,7 @@ class ShowStarGift:
"""
peer = await self.resolve_peer(chat_id)
if isinstance(peer, raw.types.InputPeerUser):
peer = raw.types.InputUser(user_id=peer.user_id, access_hash=peer.access_hash)
elif isinstance(peer, raw.types.InputPeerSelf):
peer = raw.types.InputUserSelf()
else:
if not isinstance(peer, (raw.types.InputPeerUser, raw.types.InputPeerSelf)):
raise ValueError("chat_id must belong to a user.")
r = await self.invoke(

View file

@ -33,6 +33,7 @@ from .star_gift import StarGift
from .stars_status import StarsStatus
from .stars_transaction import StarsTransaction
from .successful_payment import SuccessfulPayment
from .user_star_gift import UserStarGift
__all__ = [
"ExtendedMediaPreview",
@ -50,5 +51,6 @@ __all__ = [
"StarGift",
"StarsStatus",
"StarsTransaction",
"SuccessfulPayment"
"SuccessfulPayment",
"UserStarGift"
]

View file

@ -89,5 +89,6 @@ class StarGift(Object):
convert_price=star_gift.convert_stars,
available_amount=getattr(star_gift, "availability_remains", None),
total_amount=getattr(star_gift, "availability_total", None),
is_limited=getattr(star_gift, "limited", None)
is_limited=getattr(star_gift, "limited", None),
client=client
)

View file

@ -0,0 +1,99 @@
# 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 datetime import datetime
from typing import Optional
import pyrogram
from pyrogram import raw
from pyrogram import types
from pyrogram import utils
from ..object import Object
class UserStarGift(Object):
"""A user star gift.
Parameters:
date (``datetime``):
Date when the star gift was received.
star_gift (:obj:`~pyrogram.types.StarGift`, *optional*):
Information about the star gift.
is_name_hidden (``bool``, *optional*):
True, if the sender's name is hidden.
is_saved (``bool``, *optional*):
True, if the star gift is saved in profile.
from_user (:obj:`~pyrogram.types.User`, *optional*):
User who sent the star gift.
text (``str``, *optional*):
Text message.
message_id (``int``, *optional*):
Unique message identifier.
convert_price (``int``, *optional*):
The number of stars you get if you convert this gift.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
date: datetime,
star_gift: "types.StarGift",
is_name_hidden: Optional[bool] = None,
is_saved: Optional[bool] = None,
from_user: Optional["types.User"] = None,
text: Optional[str] = None,
message_id: Optional[int] = None,
convert_price: Optional[int] = None
):
super().__init__(client)
self.date = date
self.star_gift = star_gift
self.is_name_hidden = is_name_hidden
self.is_saved = is_saved
self.from_user = from_user
self.text = text
self.message_id = message_id
self.convert_price = convert_price
@staticmethod
async def _parse(
client,
user_star_gift: "raw.types.UserStarGift",
users: dict
) -> "UserStarGift":
# TODO: Add entities support
return UserStarGift(
date=utils.timestamp_to_datetime(user_star_gift.date),
star_gift=await types.StarGift._parse(client, user_star_gift.gift),
is_name_hidden=getattr(user_star_gift, "name_hidden", None),
is_saved=not user_star_gift.unsaved if getattr(user_star_gift, "unsaved", None) else None,
from_user=types.User._parse(client, users.get(user_star_gift.from_id)) if getattr(user_star_gift, "from_id", None) else None,
text=user_star_gift.message.text if getattr(user_star_gift, "message", None) else None,
message_id=getattr(user_star_gift, "msg_id", None),
convert_price=getattr(user_star_gift, "convert_stars", None),
client=client
)