Skip to content

Commit

Permalink
Add get_user_star_gifts method
Browse files Browse the repository at this point in the history
  • Loading branch information
KurimuzonAkuma committed Oct 7, 2024
1 parent f8c41d6 commit fc4ddbc
Show file tree
Hide file tree
Showing 11 changed files with 272 additions and 21 deletions.
3 changes: 3 additions & 0 deletions compiler/docs/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,8 @@ def get_title_list(s: str) -> list:
convert_star_gift
get_payment_form
get_star_gifts
get_user_star_gifts_count
get_user_star_gifts
hide_star_gift
send_payment_form
send_star_gift
Expand Down Expand Up @@ -505,6 +507,7 @@ def get_title_list(s: str) -> list:
MessageEntity
Photo
Thumbnail
UserStarGift
Audio
AvailableEffect
Document
Expand Down
4 changes: 4 additions & 0 deletions pyrogram/methods/payments/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from .convert_star_gift import ConvertStarGift
from .get_payment_form import GetPaymentForm
from .get_star_gifts import GetStarGifts
from .get_user_star_gifts_count import GetUserStarGiftsCount
from .get_user_star_gifts import GetUserStarGifts
from .hide_star_gift import HideStarGift
from .send_payment_form import SendPaymentForm
from .send_star_gift import SendStarGift
Expand All @@ -32,6 +34,8 @@ class Payments(
ConvertStarGift,
GetPaymentForm,
GetStarGifts,
GetUserStarGiftsCount,
GetUserStarGifts,
HideStarGift,
SendPaymentForm,
SendStarGift,
Expand Down
6 changes: 1 addition & 5 deletions pyrogram/methods/payments/convert_star_gift.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,7 @@ async def convert_star_gift(
"""
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(
Expand Down
94 changes: 94 additions & 0 deletions pyrogram/methods/payments/get_user_star_gifts.py
Original file line number Diff line number Diff line change
@@ -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
64 changes: 64 additions & 0 deletions pyrogram/methods/payments/get_user_star_gifts_count.py
Original file line number Diff line number Diff line change
@@ -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
6 changes: 1 addition & 5 deletions pyrogram/methods/payments/hide_star_gift.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,7 @@ async def hide_star_gift(
"""
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(
Expand Down
6 changes: 1 addition & 5 deletions pyrogram/methods/payments/send_star_gift.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,7 @@ async def send_star_gift(
"""
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()
Expand Down
6 changes: 1 addition & 5 deletions pyrogram/methods/payments/show_star_gift.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,7 @@ async def show_star_gift(
"""
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(
Expand Down
2 changes: 2 additions & 0 deletions pyrogram/types/messages_and_media/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from .stripped_thumbnail import StrippedThumbnail
from .successful_payment import SuccessfulPayment
from .thumbnail import Thumbnail
from .user_star_gift import UserStarGift
from .venue import Venue
from .video import Video
from .video_note import VideoNote
Expand Down Expand Up @@ -104,6 +105,7 @@
"StrippedThumbnail",
"SuccessfulPayment",
"Thumbnail",
"UserStarGift",
"Venue",
"Video",
"VideoNote",
Expand Down
3 changes: 2 additions & 1 deletion pyrogram/types/messages_and_media/star_gift.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,6 @@ async def _parse(
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
)
99 changes: 99 additions & 0 deletions pyrogram/types/messages_and_media/user_star_gift.py
Original file line number Diff line number Diff line change
@@ -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
)

0 comments on commit fc4ddbc

Please sign in to comment.