New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

wpyrogram

Package Overview
Dependencies
Maintainers
1
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

wpyrogram - pypi Package Compare versions

Comparing version
2.0.148
to
2.0.149
+34
pyrogram/enums/chat_join_type.py
# 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 enum import auto
from .auto_name import AutoName
class ChatJoinType(AutoName):
"""How the service message :obj:`~pyrogram.enums.MessageServiceType.NEW_CHAT_MEMBERS` was used for the member to join the chat."""
BY_ADD = auto()
"A new member joined the chat via an invite link"
BY_LINK = auto()
"A new member joined the chat via an invite link"
BY_REQUEST = auto()
"A new member was accepted to the chat by an administrator"
# 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 pyrogram import raw
from .auto_name import AutoName
class PhoneCallDiscardReason(AutoName):
"""Phone call discard reason enumeration used in :obj:`~pyrogram.types.PhoneCallEnded`."""
BUSY = raw.types.PhoneCallDiscardReasonBusy
"Busy"
DISCONNECT = raw.types.PhoneCallDiscardReasonDisconnect
"Disconnect"
HANGUP = raw.types.PhoneCallDiscardReasonHangup
"Hangup"
MISSED = raw.types.PhoneCallDiscardReasonMissed
"Missed"
# 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 Callable
from .handler import Handler
class ChatBoostHandler(Handler):
"""The ChatBoost handler class. Used to handle applied chat boosts.
It is intended to be used with :meth:`~pyrogram.Client.add_handler`
For a nicer way to register this handler, have a look at the
:meth:`~pyrogram.Client.on_chat_boost` decorator.
Parameters:
callback (``Callable``):
Pass a function that will be called when a new boost applied. It takes *(client, boost)*
as positional arguments (look at the section below for a detailed description).
filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of updates to be passed
in your callback function.
Other parameters:
client (:obj:`~pyrogram.Client`):
The Client itself, useful when you want to call other API methods inside the handler.
boost (:obj:`~pyrogram.types.ChatBoost`):
The applied chat boost.
"""
def __init__(self, callback: Callable, filters=None):
super().__init__(callback, filters)
# 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 Callable
from .handler import Handler
class MessageReactionCountHandler(Handler):
"""The MessageReactionCount handler class.
Used to handle changes in the anonymous reaction of a message.
It is intended to be used with :meth:`~pyrogram.Client.add_handler`.
For a nicer way to register this handler, have a look at the
:meth:`~pyrogram.Client.on_message_reaction_count` decorator.
Parameters:
callback (``Callable``):
Pass a function that will be called when a new MessageReactionCount event arrives. It takes
*(client, reactions)* as positional arguments (look at the section below for a detailed
description).
filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of updates to be passed in your callback function.
Other parameters:
client (:obj:`~pyrogram.Client`):
The Client itself, useful when you want to call other API methods inside the handler.
reactions (:obj:`~pyrogram.types.MessageReactionCountUpdated`):
The received message reaction count update.
"""
def __init__(self, callback: Callable, filters=None):
super().__init__(callback, filters)
# 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 Callable
from .handler import Handler
class MessageReactionHandler(Handler):
"""The MessageReaction handler class.
Used to handle changes in the reaction of a message.
It is intended to be used with :meth:`~pyrogram.Client.add_handler`.
For a nicer way to register this handler, have a look at the
:meth:`~pyrogram.Client.on_message_reaction` decorator.
Parameters:
callback (``Callable``):
Pass a function that will be called when a new MessageReaction event arrives. It takes
*(client, reactions)* as positional arguments (look at the section below for a detailed
description).
filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of updates to be passed in your callback function.
Other parameters:
client (:obj:`~pyrogram.Client`):
The Client itself, useful when you want to call other API methods inside the handler.
reactions (:obj:`~pyrogram.types.MessageReactionUpdated`):
The received message reaction update.
"""
def __init__(self, callback: Callable, filters=None):
super().__init__(callback, filters)
# 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 Callable
from .handler import Handler
class PurchasedPaidMediaHandler(Handler):
"""The PurchasedPaidMedia handler class. Used to handle purchased paid medias.
It is intended to be used with :meth:`~pyrogram.Client.add_handler`
For a nicer way to register this handler, have a look at the
:meth:`~pyrogram.Client.on_purchased_paid_media` decorator.
Parameters:
callback (``Callable``):
Pass a function that will be called when a paid media purchased. It takes *(client, update)*
as positional arguments (look at the section below for a detailed description).
filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of updates to be passed
in your callback function.
Other parameters:
client (:obj:`~pyrogram.Client`):
The Client itself, useful when you want to call other API methods inside the handler.
update (:obj:`~pyrogram.types.PurchasedPaidMedia`):
Information about who bought paid media.
"""
def __init__(self, callback: Callable, filters=None):
super().__init__(callback, filters)
# 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 Callable
from .handler import Handler
class ShippingQueryHandler(Handler):
"""The ShippingQueryHandler handler class. Used to handle shipping queries coming only from invoice buttons with flexible price.
It is intended to be used with :meth:`~pyrogram.Client.add_handler`
For a nicer way to register this handler, have a look at the
:meth:`~pyrogram.Client.on_shipping_query` decorator.
Parameters:
callback (``Callable``):
Pass a function that will be called when a new PreCheckoutQuery arrives. It takes *(client, query)*
as positional arguments (look at the section below for a detailed description).
filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of callback queries to be passed
in your callback function.
Other parameters:
client (:obj:`~pyrogram.Client`):
The Client itself, useful when you want to call other API methods inside the shipping query handler.
query (:obj:`~pyrogram.types.ShippingQuery`):
New incoming shipping query. Only for invoices with flexible price.
"""
def __init__(self, callback: Callable, filters=None):
super().__init__(callback, filters)
# 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 Optional, List
import pyrogram
from pyrogram import raw
from pyrogram import types
class AnswerShippingQuery:
async def answer_shipping_query(
self: "pyrogram.Client",
shipping_query_id: str,
ok: bool,
shipping_options: Optional[List["types.ShippingOption"]] = None,
error_message: Optional[str] = None
):
"""If you sent an invoice requesting a shipping address and the parameter ``is_flexible`` was specified, the API sends the confirmation in the form of an :obj:`~pyrogram.handlers.ShippingQueryHandler`.
Use this method to reply to shipping queries.
.. include:: /_includes/usable-by/bots.rst
Parameters:
shipping_query_id (``str``):
Unique identifier for the query to be answered.
ok (``bool``):
Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
shipping_options (List of :obj:`~pyrogram.types.ShippingOptions`, *optional*):
Required if ok is True. A array of available shipping options.
error_message (``str``, *optional*):
Required if ok is False.
Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable"). Telegram will display this message to the user.
Returns:
``bool``: True, on success.
Example:
.. code-block:: python
# Proceed with the order
await app.answer_shipping_query(query_id, ok=True, shipping_options=shipping_options)
# Answer with error message
await app.answer_shipping_query(query_id, ok=False, error_message="Error Message displayed to the user")
"""
if ok and not shipping_options:
raise ValueError("Shipping options required.")
r = await self.invoke(
raw.functions.messages.SetBotShippingResults(
query_id=int(shipping_query_id),
shipping_options=[
so.write()
for so in shipping_options
] if shipping_options else None,
error=error_message
)
)
return r
# 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, List, Optional
import pyrogram
from pyrogram import raw, types
class CreateInvoiceLink:
async def create_invoice_link(
self: "pyrogram.Client",
title: str,
description: str,
payload: Union[str, bytes],
currency: str,
prices: List["types.LabeledPrice"],
provider_token: Optional[str] = None,
max_tip_amount: Optional[int] = None,
suggested_tip_amounts: Optional[List[int]] = None,
start_parameter: Optional[str] = None,
provider_data: Optional[str] = None,
photo_url: Optional[str] = None,
photo_size: Optional[int] = None,
photo_width: Optional[int] = None,
photo_height: Optional[int] = None,
need_name: Optional[bool] = None,
need_phone_number: Optional[bool] = None,
need_email: Optional[bool] = None,
need_shipping_address: Optional[bool] = None,
send_phone_number_to_provider: Optional[bool] = None,
send_email_to_provider: Optional[bool] = None,
is_flexible: Optional[bool] = None
) -> str:
"""Create invoice link.
.. include:: /_includes/usable-by/bots.rst
Parameters:
title (``str``):
Product name, 1-32 characters.
description (``str``):
Product description, 1-255 characters
payload (``str`` | ``bytes``):
Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
currency (``str``):
Three-letter ISO 4217 currency code, see `more on currencies <https://core.telegram.org/bots/payments#supported-currencies>`_. Pass ``XTR`` for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
prices (List of :obj:`~pyrogram.types.LabeledPrice`):
Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
reply_to_message_id (``int``, *optional*):
If the message is a reply, ID of the original message.
provider_token (``str``, *optional*):
Payment provider token, obtained via `@BotFather <https://t.me/botfather>`_. Pass an empty string for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
max_tip_amount (``int``, *optional*):
The maximum accepted amount for tips in the smallest units of the currency (integer, **not** float/double). For example, for a maximum tip of ``US$ 1.45`` pass ``max_tip_amount = 145``. See the exp parameter in `currencies.json <https://core.telegram.org/bots/payments/currencies.json>`_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
suggested_tip_amounts (List of ``int``, *optional*):
An array of suggested amounts of tips in the smallest units of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed ``max_tip_amount``.
start_parameter (``str``, *optional*):
Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter.
provider_data (``str``, *optional*):
JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
photo_url (``str``, *optional*):
URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
photo_size (``int``, *optional*):
Photo size in bytes
photo_width (``int``, *optional*):
Photo width
photo_height (``int``, *optional*):
Photo height
need_name (``bool``, *optional*):
Pass True if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
need_phone_number (``bool``, *optional*):
Pass True if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
need_email (``bool``, *optional*):
Pass True if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
need_shipping_address (``bool``, *optional*):
Pass True if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
send_phone_number_to_provider (``bool``, *optional*):
Pass True if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
send_email_to_provider (``bool``, *optional*):
Pass True if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
is_flexible (``bool``, *optional*):
Pass True if the final price depends on the shipping method. Ignored for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
Returns:
``str``: On success, the invoice url is returned.
"""
media = raw.types.InputMediaInvoice(
title=title,
description=description,
photo=raw.types.InputWebDocument(
url=photo_url,
mime_type="image/jpg",
size=photo_size,
attributes=[
raw.types.DocumentAttributeImageSize(
w=photo_width,
h=photo_height
)
]
) if photo_url else None,
invoice=raw.types.Invoice(
currency=currency,
prices=[i.write() for i in prices],
test=self.test_mode,
name_requested=need_name,
phone_requested=need_phone_number,
email_requested=need_email,
shipping_address_requested=need_shipping_address,
flexible=is_flexible,
phone_to_provider=send_phone_number_to_provider,
email_to_provider=send_email_to_provider,
max_tip_amount=max_tip_amount,
suggested_tip_amounts=suggested_tip_amounts
),
payload=payload.encode() if isinstance(payload, str) else payload,
provider=provider_token,
provider_data=raw.types.DataJSON(
data=provider_data if provider_data else "{}"
),
start_param=start_parameter
)
r = await self.invoke(
raw.functions.payments.ExportInvoice(
invoice_media=media
)
)
return r.url
# 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 GetBotInfoDescription:
async def get_bot_info_description(
self: "pyrogram.Client",
language_code: str = "",
for_my_bot: Union[int, str] = None,
) -> str:
"""Use this method to get the current / owned bot description for the given user language.
.. note::
If the current account is an User, can be called only if the ``for_my_bot`` has ``can_be_edited`` property set to True.
.. include:: /_includes/usable-by/users-bots.rst
Parameters:
language_code (``str``, *optional*):
A two-letter ISO 639-1 language code or an empty string
for_my_bot (``int`` | ``str``, *optional*):
Unique identifier (int) or username (str) of the bot for which profile photo has to be updated instead of the current user.
The bot should have ``can_be_edited`` property set to True.
Returns:
``str``: On success, returns the text shown in the chat with a bot if the chat is empty in the given language.
Example:
.. code-block:: python
bot_description = await app.get_bot_info_description()
"""
bot_info = await self.invoke(
raw.functions.bots.GetBotInfo(
bot=await self.resolve_peer(for_my_bot) if for_my_bot else None,
lang_code=language_code
)
)
return bot_info.description
# 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 GetBotInfoShortDescription:
async def get_bot_info_short_description(
self: "pyrogram.Client",
language_code: str = "",
for_my_bot: Union[int, str] = None,
) -> str:
"""Use this method to get the current / owned bot short description for the given user language.
.. note::
If the current account is an User, can be called only if the ``for_my_bot`` has ``can_be_edited`` property set to True.
.. include:: /_includes/usable-by/users-bots.rst
Parameters:
language_code (``str``, *optional*):
A two-letter ISO 639-1 language code or an empty string
for_my_bot (``int`` | ``str``, *optional*):
Unique identifier (int) or username (str) of the bot for which profile photo has to be updated instead of the current user.
The bot should have ``can_be_edited`` property set to True.
Returns:
``str``: On success, returns the text shown on a bot's profile page and sent together with the link when users share the bot in the given language.
Example:
.. code-block:: python
bot_short_description = await app.get_bot_info_short_description()
"""
bot_info = await self.invoke(
raw.functions.bots.GetBotInfo(
bot=await self.resolve_peer(for_my_bot) if for_my_bot else None,
lang_code=language_code
)
)
return bot_info.about
# 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 GetBotName:
async def get_bot_name(
self: "pyrogram.Client",
language_code: str = "",
for_my_bot: Union[int, str] = None,
) -> str:
"""Use this method to get the current / owned bot name for the given user language.
.. note::
If the current account is an User, can be called only if the ``for_my_bot`` has ``can_be_edited`` property set to True.
.. include:: /_includes/usable-by/users-bots.rst
Parameters:
language_code (``str``, *optional*):
A two-letter ISO 639-1 language code or an empty string
for_my_bot (``int`` | ``str``, *optional*):
Unique identifier (int) or username (str) of the bot for which profile photo has to be updated instead of the current user.
The bot should have ``can_be_edited`` property set to True.
Returns:
``str``: On success, returns the name of a bot in the given language.
Example:
.. code-block:: python
bot_name = await app.get_bot_name()
"""
bot_info = await self.invoke(
raw.functions.bots.GetBotInfo(
bot=await self.resolve_peer(for_my_bot) if for_my_bot else None,
lang_code=language_code
)
)
return bot_info.name
# 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 SetBotInfoDescription:
async def set_bot_info_description(
self: "pyrogram.Client",
description: str,
language_code: str = "",
for_my_bot: Union[int, str] = None,
) -> bool:
"""Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
.. note::
If the current account is an User, can be called only if the ``for_my_bot`` has ``can_be_edited`` property set to True.
.. include:: /_includes/usable-by/users-bots.rst
Parameters:
description (``str``):
New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.
language_code (``str``, *optional*):
A two-letter ISO 639-1 language code or an empty string
for_my_bot (``int`` | ``str``, *optional*):
Unique identifier (int) or username (str) of the bot for which profile photo has to be updated instead of the current user.
The bot should have ``can_be_edited`` property set to True.
Returns:
``bool``: True on success.
Example:
.. code-block:: python
await app.set_bot_info_description("")
"""
return await self.invoke(
raw.functions.bots.SetBotInfo(
bot=await self.resolve_peer(for_my_bot) if for_my_bot else None,
lang_code=language_code,
description=description
)
)
# 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 SetBotInfoShortDescription:
async def set_bot_info_short_description(
self: "pyrogram.Client",
short_description: str,
language_code: str = "",
for_my_bot: Union[int, str] = None,
) -> bool:
"""Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot.
.. note::
If the current account is an User, can be called only if the ``for_my_bot`` has ``can_be_edited`` property set to True.
.. include:: /_includes/usable-by/users-bots.rst
Parameters:
short_description (``str``):
New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.
language_code (``str``, *optional*):
A two-letter ISO 639-1 language code or an empty string
for_my_bot (``int`` | ``str``, *optional*):
Unique identifier (int) or username (str) of the bot for which profile photo has to be updated instead of the current user.
The bot should have ``can_be_edited`` property set to True.
Returns:
``bool``: True on success.
Example:
.. code-block:: python
await app.set_bot_info_short_description("")
"""
return await self.invoke(
raw.functions.bots.SetBotInfo(
bot=await self.resolve_peer(for_my_bot) if for_my_bot else None,
lang_code=language_code,
about=short_description
)
)
# 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 SetBotName:
async def set_bot_name(
self: "pyrogram.Client",
name: str,
language_code: str = "",
for_my_bot: Union[int, str] = None,
) -> str:
"""Use this method to get the current / owned bot name for the given user language.
.. note::
If the current account is an User, can be called only if the ``for_my_bot`` has ``can_be_edited`` property set to True.
.. include:: /_includes/usable-by/users-bots.rst
Parameters:
name (``str``):
New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.
language_code (``str``, *optional*):
A two-letter ISO 639-1 language code or an empty string
for_my_bot (``int`` | ``str``, *optional*):
Unique identifier (int) or username (str) of the bot for which profile photo has to be updated instead of the current user.
The bot should have ``can_be_edited`` property set to True.
Returns:
``bool``: True on success.
Example:
.. code-block:: python
await app.set_bot_name("Pyrogram Assistant")
"""
return await self.invoke(
raw.functions.bots.SetBotInfo(
bot=await self.resolve_peer(for_my_bot) if for_my_bot else None,
lang_code=language_code,
name=name
)
)
# 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 pyrogram
from pyrogram import raw
from typing import Union
class PinForumTopic:
async def pin_forum_topic(
self: "pyrogram.Client",
chat_id: Union[int, str],
topic_id: int
) -> bool:
"""Pin a forum topic.
.. include:: /_includes/usable-by/users.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
topic_id (``int``):
Unique identifier (int) of the target forum topic.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
await app.pin_forum_topic(chat_id, topic_id)
"""
await self.invoke(
raw.functions.channels.UpdatePinnedForumTopic(
channel=await self.resolve_peer(chat_id),
topic_id=topic_id,
pinned=True
)
)
return True
# 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 pyrogram
from pyrogram import raw
from typing import Union
class UnpinForumTopic:
async def unpin_forum_topic(
self: "pyrogram.Client",
chat_id: Union[int, str],
topic_id: int
) -> bool:
"""Unpin a forum topic.
.. include:: /_includes/usable-by/users.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
topic_id (``int``):
Unique identifier (int) of the target forum topic.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
await app.unpin_forum_topic(chat_id, topic_id)
"""
await self.invoke(
raw.functions.channels.UpdatePinnedForumTopic(
channel=await self.resolve_peer(chat_id),
topic_id=topic_id,
pinned=False
)
)
return True
# 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 Callable
import pyrogram
from pyrogram.filters import Filter
class OnChatBoost:
def on_chat_boost(
self=None,
filters=None,
group: int = 0,
) -> Callable:
"""Decorator for handling applied chat boosts.
This does the same thing as :meth:`~pyrogram.Client.add_handler` using the
:obj:`~pyrogram.handlers.ChatBoostHandler`.
.. include:: /_includes/usable-by/bots.rst
Parameters:
filters (:obj:`~pyrogram.filters`, *optional*):
Pass one or more filters to allow only a subset of callback queries to be passed
in your function.
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
def decorator(func: Callable) -> Callable:
if isinstance(self, pyrogram.Client):
self.add_handler(pyrogram.handlers.ShippingQueryHandler(func, filters), group)
elif isinstance(self, Filter) or self is None:
if not hasattr(func, "handlers"):
func.handlers = []
func.handlers.append(
(
pyrogram.handlers.ShippingQueryHandler(func, self),
group if filters is None else filters
)
)
return func
return decorator
# 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 Callable
import pyrogram
from pyrogram.filters import Filter
class OnMessageReactionCount:
def on_message_reaction_count(
self=None,
filters=None,
group: int = 0
) -> Callable:
"""Decorator for handling anonymous reaction changes on messages.
This does the same thing as :meth:`~pyrogram.Client.add_handler` using the
:obj:`~pyrogram.handlers.MessageReactionCountHandler`.
.. include:: /_includes/usable-by/bots.rst
Parameters:
filters (:obj:`~pyrogram.filters`, *optional*):
Pass one or more filters to allow only a subset of updates to be passed in your function.
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
def decorator(func: Callable) -> Callable:
if isinstance(self, pyrogram.Client):
self.add_handler(pyrogram.handlers.MessageReactionCountHandler(func, filters), group)
elif isinstance(self, Filter) or self is None:
if not hasattr(func, "handlers"):
func.handlers = []
func.handlers.append(
(
pyrogram.handlers.MessageReactionCountHandler(func, self),
group if filters is None else filters
)
)
return func
return decorator
# 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 Callable
import pyrogram
from pyrogram.filters import Filter
class OnMessageReaction:
def on_message_reaction(
self=None,
filters=None,
group: int = 0
) -> Callable:
"""Decorator for handling reaction changes on messages.
This does the same thing as :meth:`~pyrogram.Client.add_handler` using the
:obj:`~pyrogram.handlers.MessageReactionHandler`.
.. include:: /_includes/usable-by/bots.rst
Parameters:
filters (:obj:`~pyrogram.filters`, *optional*):
Pass one or more filters to allow only a subset of updates to be passed in your function.
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
def decorator(func: Callable) -> Callable:
if isinstance(self, pyrogram.Client):
self.add_handler(pyrogram.handlers.MessageReactionHandler(func, filters), group)
elif isinstance(self, Filter) or self is None:
if not hasattr(func, "handlers"):
func.handlers = []
func.handlers.append(
(
pyrogram.handlers.MessageReactionHandler(func, self),
group if filters is None else filters
)
)
return func
return decorator
# 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 Callable
import pyrogram
from pyrogram.filters import Filter
class OnPurchasedPaidMedia:
def on_purchased_paid_media(
self=None,
filters=None,
group: int = 0
) -> Callable:
"""Decorator for handling purchased paid media.
This does the same thing as :meth:`~pyrogram.Client.add_handler` using the
:obj:`~pyrogram.handlers.PurchasedPaidMediaHandler`.
.. include:: /_includes/usable-by/bots.rst
Parameters:
filters (:obj:`~pyrogram.filters`, *optional*):
Pass one or more filters to allow only a subset of updates to be passed in your function.
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
def decorator(func: Callable) -> Callable:
if isinstance(self, pyrogram.Client):
self.add_handler(pyrogram.handlers.MessageReactionHandler(func, filters), group)
elif isinstance(self, Filter) or self is None:
if not hasattr(func, "handlers"):
func.handlers = []
func.handlers.append(
(
pyrogram.handlers.MessageReactionHandler(func, self),
group if filters is None else filters
)
)
return func
return decorator
# 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 Callable
import pyrogram
from pyrogram.filters import Filter
class OnShippingQuery:
def on_shipping_query(
self=None,
filters=None,
group: int = 0,
) -> Callable:
"""Decorator for handling shipping queries.
This does the same thing as :meth:`~pyrogram.Client.add_handler` using the
:obj:`~pyrogram.handlers.ShippingQueryHandler`.
.. include:: /_includes/usable-by/bots.rst
Parameters:
filters (:obj:`~pyrogram.filters`, *optional*):
Pass one or more filters to allow only a subset of callback queries to be passed
in your function.
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
def decorator(func: Callable) -> Callable:
if isinstance(self, pyrogram.Client):
self.add_handler(pyrogram.handlers.ShippingQueryHandler(func, filters), group)
elif isinstance(self, Filter) or self is None:
if not hasattr(func, "handlers"):
func.handlers = []
func.handlers.append(
(
pyrogram.handlers.ShippingQueryHandler(func, self),
group if filters is None else filters
)
)
return func
return decorator
# 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 Union, List
import pyrogram
from pyrogram import raw, utils
from pyrogram import types
class ForwardMediaGroup:
async def forward_media_group(
self: "pyrogram.Client",
chat_id: Union[int, str],
from_chat_id: Union[int, str],
message_id: int,
message_thread_id: int = None,
disable_notification: bool = None,
schedule_date: datetime = None,
hide_sender_name: bool = None,
hide_captions: bool = None,
protect_content: bool = None,
allow_paid_broadcast: bool = None
) -> List["types.Message"]:
"""Forward a media group by providing one of the message ids.
.. include:: /_includes/usable-by/users-bots.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).
from_chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the source chat where the original message was sent.
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``):
Message identifier in the chat specified in *from_chat_id*.
message_thread_id (``int``, *optional*):
Unique identifier of a message thread to which the message belongs.
For supergroups only.
disable_notification (``bool``, *optional*):
Sends the message silently.
Users will receive a notification with no sound.
schedule_date (:py:obj:`~datetime.datetime`, *optional*):
Date when the message will be automatically sent.
hide_sender_name (``bool``, *optional*):
If True, the original author of the message will not be shown.
hide_captions (``bool``, *optional*):
If True, the original media captions will be removed.
protect_content (``bool``, *optional*):
Protects the contents of the sent message from forwarding and saving.
allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
Returns:
List of :obj:`~pyrogram.types.Message`: On success, a list of forwarded messages is returned.
Example:
.. code-block:: python
# Forward a media group
await app.forward_media_group(to_chat, from_chat, 123)
"""
message_ids = [i.id for i in await self.get_media_group(from_chat_id, message_id)]
r = await self.invoke(
raw.functions.messages.ForwardMessages(
to_peer=await self.resolve_peer(chat_id),
from_peer=await self.resolve_peer(from_chat_id),
id=message_ids,
silent=disable_notification or None,
random_id=[self.rnd_id() for _ in message_ids],
schedule_date=utils.datetime_to_timestamp(schedule_date),
drop_author=hide_sender_name,
drop_media_captions=hide_captions,
noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
top_msg_id=message_thread_id
)
)
forwarded_messages = []
users = {i.id: i for i in r.users}
chats = {i.id: i for i in r.chats}
for i in r.updates:
if isinstance(i, (raw.types.UpdateNewMessage,
raw.types.UpdateNewChannelMessage,
raw.types.UpdateNewScheduledMessage)):
forwarded_messages.append(
await types.Message._parse(
self, i.message,
users, chats
)
)
return types.List(forwarded_messages)
# 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 SendPaidReaction:
async def send_paid_reaction(
self: "pyrogram.Client",
chat_id: Union[int, str],
message_id: int,
amount: int,
is_private: bool = None
) -> bool:
"""Send a paid reaction to a message.
.. include:: /_includes/usable-by/users.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
message_id (``int``):
Identifier of the message.
amount (``int``):
Amount of stars to send.
is_private (``bool``, *optional*):
Pass True to hide you from top reactors.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Send paid reaction with 1 star
await app.send_paid_reaction(chat_id, message_id, amount=1)
"""
rpc = raw.functions.messages.SendPaidReaction(
peer=await self.resolve_peer(chat_id),
msg_id=message_id,
count=amount,
random_id=self.rnd_id(),
private=is_private
)
await self.invoke(rpc)
return True
# 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 re
import pyrogram
from pyrogram import raw
class ApplyGiftCode:
async def apply_gift_code(
self: "pyrogram.Client",
link: str,
) -> bool:
"""Apply a gift code.
.. include:: /_includes/usable-by/users.rst
Parameters:
link (``str``):
The gift code link.
Returns:
``bool``: On success, True is returned.
Raises:
ValueError: In case the gift code link is invalid.
Example:
.. code-block:: python
# apply a gift code
app.apply_gift_code("t.me/giftcode/abc1234567def")
"""
match = re.match(r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/(?:giftcode/|\+))([\w-]+)$", link)
if match:
slug = match.group(1)
elif isinstance(link, str):
slug = link
else:
raise ValueError("Invalid gift code link")
await self.invoke(
raw.functions.payments.ApplyGiftCode(
slug=slug
)
)
return True
# 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 re
import pyrogram
from pyrogram import raw, types
class CheckGiftCode:
async def check_gift_code(
self: "pyrogram.Client",
link: str,
) -> "types.CheckedGiftCode":
"""Get information about a gift code.
.. include:: /_includes/usable-by/users.rst
Parameters:
link (``str``):
The gift code link.
Returns:
:obj:`~pyrogram.types.CheckedGiftCode`: On success, a checked gift code is returned.
Raises:
ValueError: In case the gift code link is invalid.
Example:
.. code-block:: python
# get information about a gift code
app.check_gift_code("t.me/giftcode/abc1234567def")
"""
match = re.match(r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/(?:giftcode/|\+))([\w-]+)$", link)
if match:
slug = match.group(1)
elif isinstance(link, str):
slug = link
else:
raise ValueError("Invalid gift code link")
r = await self.invoke(
raw.functions.payments.CheckGiftCode(
slug=slug
)
)
users = {i.id: i for i in r.users}
chats = {i.id: i for i in r.chats}
return types.CheckedGiftCode._parse(self, r, users, chats)
# 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 ConvertStarGift:
async def convert_star_gift(
self: "pyrogram.Client",
chat_id: Union[int, str],
message_id: int
) -> bool:
"""Convert star gift to stars.
.. 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).
message_id (``int``):
Unique message identifier of star gift.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Convert gift
app.convert_star_gift(chat_id=chat_id, message_id=123)
"""
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.ConvertStarGift(
user_id=peer,
msg_id=message_id
)
)
return r
# 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 GetStarGifts:
async def get_star_gifts(
self: "pyrogram.Client",
) -> List["types.StarGift"]:
"""Get all available star gifts to send.
.. include:: /_includes/usable-by/users.rst
Returns:
List of :obj:`~pyrogram.types.StarGift`: On success, a list of star gifts is returned.
Example:
.. code-block:: python
app.get_star_gifts()
"""
r = await self.invoke(
raw.functions.payments.GetStarGifts(hash=0)
)
return types.List([await types.StarGift._parse(self, gift) for gift in r.gifts])
# 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
# 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.StarGift` 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.StarGift._parse_user_star_gift(self, gift, users)
for gift in r.gifts
]
if not user_star_gifts:
return
for gift in user_star_gifts:
yield gift
current += 1
if current >= total:
return
offset = r.next_offset
if not offset:
return
# 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 HideStarGift:
async def hide_star_gift(
self: "pyrogram.Client",
chat_id: Union[int, str],
message_id: int
) -> bool:
"""Hide the star gift from your profile.
.. 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).
message_id (``int``):
Unique message identifier of star gift.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Hide gift
app.hide_star_gift(chat_id=chat_id, message_id=123)
"""
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.SaveStarGift(
user_id=peer,
msg_id=message_id,
unsave=True
)
)
return r
# 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 Optional, Union, List
import pyrogram
from pyrogram import raw, types, enums, utils
class SendStarGift:
async def send_star_gift(
self: "pyrogram.Client",
chat_id: Union[int, str],
star_gift_id: int,
text: Optional[str] = None,
parse_mode: Optional["enums.ParseMode"] = None,
entities: Optional[List["types.MessageEntity"]] = None,
hide_my_name: Optional[bool] = None,
) -> bool:
"""Send star gift.
.. 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).
star_gift_id (``int``):
Unique identifier of star gift.
To get all available star gifts use :meth:`~pyrogram.Client.get_star_gifts`.
text (``str``, *optional*):
Text of the message to be sent.
parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*):
By default, texts are parsed using both Markdown and HTML styles.
You can combine both syntaxes together.
entities (List of :obj:`~pyrogram.types.MessageEntity`, *optional*):
List of special entities that appear in message text, which can be specified instead of *parse_mode*.
hide_my_name (``bool``, *optional*):
If True, your name will be hidden from visitors to the gift recipient's profile.
Defaults to None.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Send gift
app.send_star_gift(chat_id=chat_id, star_gift_id=123)
"""
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.")
text, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
invoice = raw.types.InputInvoiceStarGift(
user_id=peer,
gift_id=star_gift_id,
hide_name=hide_my_name,
message=raw.types.TextWithEntities(text=text, entities=entities or []) if text else None
)
form = await self.invoke(
raw.functions.payments.GetPaymentForm(
invoice=invoice
)
)
await self.invoke(
raw.functions.payments.SendStarsForm(
form_id=form.form_id,
invoice=invoice
)
)
return True
# 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 ShowStarGift:
async def show_star_gift(
self: "pyrogram.Client",
chat_id: Union[int, str],
message_id: int
) -> bool:
"""Display the star gift in your profile.
.. 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).
message_id (``int``):
Unique message identifier of star gift.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Show gift
app.show_star_gift(chat_id=chat_id, message_id=123)
"""
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.SaveStarGift(
user_id=peer,
msg_id=message_id,
unsave=False
)
)
return r
# 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 CanPostStories:
async def can_post_stories(
self: "pyrogram.Client",
chat_id: Union[int, str],
) -> bool:
"""Check whether we can post stories as the specified chat.
.. include:: /_includes/usable-by/users.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Check if you can send story to chat id
app.can_post_stories(chat_id)
"""
r = await self.invoke(
raw.functions.stories.CanSendStory(
peer=await self.resolve_peer(chat_id),
)
)
return r
# 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 AsyncGenerator, Union
import pyrogram
from pyrogram import raw
from pyrogram import types
class GetArchivedStories:
async def get_archived_stories(
self: "pyrogram.Client",
chat_id: Union[int, str],
limit: int = 0,
offset_id: int = 0
) -> AsyncGenerator["types.Story", None]:
"""Get all archived stories from a chat by using chat identifier.
.. 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).
limit (``int``, *optional*):
Limits the number of stories to be retrieved.
By default, no limit is applied and all stories are returned.
offset_id (``int``, *optional*):
Identifier of the first story to be returned.
Returns:
``Generator``: A generator yielding :obj:`~pyrogram.types.Story` objects.
Example:
.. code-block:: python
# Get archived stories from specific chat
async for story in app.get_stories_archive(chat_id):
print(story)
"""
current = 0
total = abs(limit) or (1 << 31)
limit = min(100, total)
while True:
peer = await self.resolve_peer(chat_id)
r = await self.invoke(
raw.functions.stories.GetStoriesArchive(
peer=peer,
offset_id=offset_id,
limit=limit
)
)
if not r.stories:
return
last = r.stories[-1]
offset_id = last.id
users = {i.id: i for i in r.users}
chats = {i.id: i for i in r.chats}
for story in r.stories:
yield await types.Story._parse(
self,
story,
users,
chats,
peer
)
current += 1
if current >= total:
return
# 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 HideChatStories:
async def hide_chat_stories(
self: "pyrogram.Client",
chat_id: Union[int, str],
) -> bool:
"""Hide the active stories of a user, preventing them from being displayed on the action bar on the homescreen.
.. 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:
``bool``: On success, a bool is returned.
Example:
.. code-block:: python
# Hide stories from specific chat
app.hide_chat_stories(chat_id)
"""
r = await self.invoke(
raw.functions.stories.TogglePeerStoriesHidden(
peer=await self.resolve_peer(chat_id),
hidden=True
)
)
return r
# 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, Union, Iterable
import pyrogram
from pyrogram import raw
from pyrogram import types
class PinChatStories:
async def pin_chat_stories(
self: "pyrogram.Client",
chat_id: Union[int, str],
stories_ids: Union[int, Iterable[int]]
) -> List[int]:
"""Pin one or more stories in a chat by using stories identifiers.
.. 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".
stories_ids (``int`` | Iterable of ``int``, *optional*):
List of unique identifiers of the target stories.
Returns:
List of ``int``: List of pinned stories IDs
Example:
.. code-block:: python
# Pin a single story
await app.pin_chat_stories(chat_id, 123456789)
"""
is_iterable = not isinstance(stories_ids, int)
stories_ids = list(stories_ids) if is_iterable else [stories_ids]
r = await self.invoke(
raw.functions.stories.TogglePinned(
peer=await self.resolve_peer(chat_id),
id=stories_ids,
pinned=True
)
)
return types.List(r)
# 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, Union
import pyrogram
from pyrogram import raw, types
class ReadChatStories:
async def read_chat_stories(
self: "pyrogram.Client",
chat_id: Union[int, str],
max_id: int = 0,
) -> List[int]:
"""Mark all stories up to a certain identifier as read, for a given chat.
.. include:: /_includes/usable-by/users.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For a contact that exists in your Telegram address book you can use his phone number (str).
max_id (``int``, *optional*):
The id of the last story you want to mark as read.
All the stories before this one will be marked as read as well.
Defaults to 0 (mark every unread message as read).
Returns:
List of ``int``: On success, a list of read stories is returned.
Example:
.. code-block:: python
# Read all stories
await app.read_chat_stories(chat_id)
# Mark stories as read only up to the given story id
await app.read_chat_stories(chat_id, 123)
"""
r = await self.invoke(
raw.functions.stories.ReadStories(
peer=await self.resolve_peer(chat_id),
max_id=max_id or (1 << 31) - 1
)
)
return types.List(r)
# 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 ShowChatStories:
async def show_chat_stories(
self: "pyrogram.Client",
chat_id: Union[int, str],
) -> bool:
"""Show the active stories of a user and display them in the action bar on the homescreen.
.. 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:
``bool``: On success, a bool is returned.
Example:
.. code-block:: python
# Show stories from specific chat
app.show_chat_stories(chat_id)
"""
r = await self.invoke(
raw.functions.stories.TogglePeerStoriesHidden(
peer=await self.resolve_peer(chat_id),
hidden=False
)
)
return r
# 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, Union, Iterable
import pyrogram
from pyrogram import raw
from pyrogram import types
class UnpinChatStories:
async def unpin_chat_stories(
self: "pyrogram.Client",
chat_id: Union[int, str],
stories_ids: Union[int, Iterable[int]]
) -> List[int]:
"""Unpin one or more stories in a chat by using stories identifiers.
.. 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".
stories_ids (``int`` | Iterable of ``int``, *optional*):
List of unique identifiers of the target stories.
Returns:
List of ``int``: List of pinned stories identifiers.
Example:
.. code-block:: python
# Unpin a single story
await app.unpin_chat_stories(chat_id, 123456789)
"""
is_iterable = not isinstance(stories_ids, int)
stories_ids = list(stories_ids) if is_iterable else [stories_ids]
r = await self.invoke(
raw.functions.stories.TogglePinned(
peer=await self.resolve_peer(chat_id),
id=stories_ids,
pinned=False
)
)
return types.List(r)
# 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
import pyrogram
from pyrogram import raw
class SetPersonalChannel:
async def set_personal_channel(
self: "pyrogram.Client",
chat_id: Optional[Union[int, str]] = None
) -> bool:
"""Set a personal channel in bio.
.. include:: /_includes/usable-by/users.rst
To get all available channels you can use
:meth:`~pyrogram.Client.get_personal_channels`.
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target user or None to remove it.
Returns:
``bool``: True on success.
Example:
.. code-block:: python
# Set your personal channel
await app.set_personal_channel(chat_id)
# Remove personal channel from your profile
await app.set_personal_channel()
"""
if chat_id is None:
peer = raw.types.InputChannelEmpty()
else:
peer = await self.resolve_peer(chat_id)
if not isinstance(peer, raw.types.InputPeerChannel):
return False
return bool(
await self.invoke(
raw.functions.account.UpdatePersonalChannel(
channel=peer
)
)
)
# 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 Dict
import pyrogram
from pyrogram import raw, utils
from pyrogram import types
from ..object import Object
from ..update import Update
class ChatBoostUpdated(Object, Update):
"""A channel/supergroup boost has changed (bots only).
Parameters:
chat (:obj:`~pyrogram.types.Chat`):
The chat where boost was changed.
boost (:obj:`~pyrogram.types.ChatBoost`):
New boost information.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
chat: "types.Chat",
boost: "types.ChatBoost"
):
super().__init__(client)
self.chat = chat
self.boost = boost
@staticmethod
def _parse(
client: "pyrogram.Client",
update: "raw.types.UpdateBotChatBoost",
users: Dict[int, "raw.types.User"],
chats: Dict[int, "raw.types.Channel"],
) -> "ChatBoostUpdated":
return ChatBoostUpdated(
chat=types.Chat._parse_channel_chat(client, chats.get(utils.get_raw_peer_id(update.peer))),
boost=types.ChatBoost._parse(client, update.boost, users),
client=client
)
# 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 Dict, List
import pyrogram
from pyrogram import raw, types, utils
from ..object import Object
from ..update import Update
class MessageReactionCountUpdated(Object, Update):
"""Reactions to a message with anonymous reactions were changed.
These updates are heavy and their changes may be delayed by a few minutes.
Parameters:
chat (:obj:`~pyrogram.types.Chat`):
The chat containing the message the user reacted to.
message_id (``int``):
Unique identifier of the message inside the chat.
date (:py:obj:`~datetime.datetime`):
Date of change of the reaction.
reactions (:obj:`~pyrogram.types.ReactionCount`):
List of reactions that are present on the message.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
chat: "types.Chat",
message_id: int,
date: datetime,
reactions: List["types.ReactionCount"]
):
super().__init__(client)
self.chat = chat
self.message_id = message_id
self.date = date
self.reactions = reactions
@staticmethod
def _parse(
client: "pyrogram.Client",
update: "raw.types.UpdateBotMessageReactions",
users: Dict[int, "raw.types.User"],
chats: Dict[int, "raw.types.Chat"]
) -> "MessageReactionCountUpdated":
peer_id = utils.get_peer_id(update.peer)
raw_peer_id = utils.get_raw_peer_id(update.peer)
if peer_id > 0:
chat = types.Chat._parse_user_chat(client, users[raw_peer_id])
else:
chat = types.Chat._parse_chat(client, chats[raw_peer_id])
return MessageReactionCountUpdated(
client=client,
chat=chat,
message_id=update.msg_id,
date=utils.timestamp_to_datetime(update.date),
reactions=[
types.Reaction._parse_count(
client,
reaction
) for reaction in update.reactions
]
)
# 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 Dict, List
import pyrogram
from pyrogram import raw, types, utils
from ..object import Object
from ..update import Update
class MessageReactionUpdated(Object, Update):
"""This object represents a change of a reaction on a message performed by a user.
A reaction to a message was changed by a user.
The update isn't received for reactions set by bots.
These updates are heavy and their changes may be delayed by a few minutes.
Parameters:
chat (:obj:`~pyrogram.types.Chat`):
The chat containing the message the user reacted to.
message_id (``int``):
Unique identifier of the message inside the chat.
user (:obj:`~pyrogram.types.User`, *optional*):
The user that changed the reaction, if the user isn't anonymous.
actor_chat (:obj:`~pyrogram.types.Chat`, *optional*):
The chat on behalf of which the reaction was changed, if the user is anonymous.
date (:py:obj:`~datetime.datetime`):
Date of change of the reaction.
old_reaction (List of :obj:`~pyrogram.types.Reaction`):
Previous list of reaction types that were set by the user.
new_reaction (List of :obj:`~pyrogram.types.Reaction`):
New list of reaction types that have been set by the user.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
chat: "types.Chat",
message_id: int,
user: "types.User",
actor_chat: "types.Chat",
date: datetime,
old_reaction: List["types.Reaction"],
new_reaction: List["types.Reaction"]
):
super().__init__(client)
self.chat = chat
self.message_id = message_id
self.user = user
self.actor_chat = actor_chat
self.date = date
self.old_reaction = old_reaction
self.new_reaction = new_reaction
@staticmethod
def _parse(
client: "pyrogram.Client",
update: "raw.types.UpdateBotMessageReaction",
users: Dict[int, "raw.types.User"],
chats: Dict[int, "raw.types.Chat"]
) -> "MessageReactionUpdated":
peer_id = utils.get_peer_id(update.peer)
raw_peer_id = utils.get_raw_peer_id(update.peer)
if peer_id > 0:
chat = types.Chat._parse_user_chat(client, users[raw_peer_id])
else:
chat = types.Chat._parse_chat(client, chats[raw_peer_id])
user = None
actor_chat = None
raw_actor_peer_id = utils.get_raw_peer_id(update.actor)
actor_peer_id = utils.get_peer_id(update.actor)
if actor_peer_id > 0:
user = types.User._parse(client, users[raw_actor_peer_id])
else:
actor_chat = types.Chat._parse_channel_chat(client, chats[raw_actor_peer_id])
return MessageReactionUpdated(
client=client,
chat=chat,
message_id=update.msg_id,
user=user,
actor_chat=actor_chat,
date=utils.timestamp_to_datetime(update.date),
old_reaction=[
types.Reaction._parse(
client,
reaction
) for reaction in update.old_reactions
],
new_reaction=[
types.Reaction._parse(
client,
reaction
) for reaction in update.new_reactions
]
)
# 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 pyrogram import raw, types
from ..object import Object
class PurchasedPaidMedia(Object):
"""This object represents information about purchased paid media.
Parameters:
from_user (:obj:`~pyrogram.types.User`):
User who bought the paid media.
payload (``str``):
Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
"""
def __init__(
self,
from_user: "types.User",
payload: str
):
super().__init__()
self.from_user = from_user
self.payload = payload
@staticmethod
def _parse(client, purchased_media: "raw.types.UpdateBotPurchasedPaidMedia", users) -> "PurchasedPaidMedia":
return PurchasedPaidMedia(
from_user=types.User._parse(client, users.get(purchased_media.user_id)),
payload=purchased_media.payload
)
# 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
from pyrogram import raw, types
from ..object import Object
class ShippingOption(Object):
"""This object represents one shipping option.
Parameters:
id (``str``):
Shipping option identifier.
title (``str``):
Option title.
prices (List of :obj:`~pyrogram.types.LabeledPrice`):
List of price portions.
"""
def __init__(
self,
id: str,
title: str,
prices: List["types.LabeledPrice"]
):
super().__init__()
self.id = id
self.title = title
self.prices = prices
@staticmethod
def _parse(shipping_option: "raw.types.ShippingOption") -> "ShippingOption":
if isinstance(shipping_option, raw.types.ShippingOption):
return ShippingOption(
id=shipping_option.id,
title=shipping_option.title,
prices=[
types.LabeledPrice._parse(price)
for price in shipping_option.prices
]
)
def write(self):
return raw.types.ShippingOption(
id=self.id,
title=self.title,
prices=[
price.write()
for price in self.prices
]
)
# 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 Optional
import pyrogram
from pyrogram import types, raw
from ..object import Object
from ..update import Update
class ShippingQuery(Object, Update):
"""This object contains information about an incoming shipping query.
Parameters:
id (``str``):
Unique query identifier.
from_user (:obj:`~pyrogram.types.User`):
User who sent the query.
invoice_payload (``str``):
Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
shipping_address (:obj:`~pyrogram.types.ShippingAddress`):
User specified shipping address. Only available to the bot that received the payment.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
id: str,
from_user: "types.User",
invoice_payload: str,
shipping_address: Optional["types.ShippingAddress"] = None
):
super().__init__(client)
self.id = id
self.from_user = from_user
self.invoice_payload = invoice_payload
self.shipping_address = shipping_address
@staticmethod
async def _parse(
client: "pyrogram.Client",
shipping_query: "raw.types.UpdateBotShippingQuery",
users: dict
) -> "ShippingQuery":
# Try to decode shipping query payload into string. If that fails, fallback to bytes instead of decoding by
# ignoring/replacing errors, this way, button clicks will still work.
try:
payload = shipping_query.payload.decode()
except (UnicodeDecodeError, AttributeError):
payload = shipping_query.payload
return ShippingQuery(
id=str(shipping_query.query_id),
from_user=types.User._parse(client, users[shipping_query.user_id]),
invoice_payload=payload,
shipping_address=types.ShippingAddress._parse(shipping_query.shipping_address),
client=client
)
async def answer(
self,
ok: bool,
shipping_options: "types.ShippingOptions" = None,
error_message: str = None
):
"""Bound method *answer* of :obj:`~pyrogram.types.ShippingQuery`.
Use this method as a shortcut for:
.. code-block:: python
await client.answer_shipping_query(
shipping_query.id,
ok=True
)
Example:
.. code-block:: python
await shipping_query.answer(ok=True)
Parameters:
ok (``bool``):
Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible).
shipping_options (:obj:`~pyrogram.types.ShippingOptions`, *optional*):
Required if ok is True. A JSON-serialized array of available shipping options.
error_message (``str``, *optional*):
Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
Returns:
``bool``: True, on success.
"""
return await self._client.answer_shipping_query(
shipping_query_id=self.id,
ok=ok,
shipping_options=shipping_options,
error_message=error_message
)
# 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, types, utils
from ..object import Object
class ChatBoost(Object):
"""Contains information about one or more boosts applied by a specific user.
Parameters:
id (``str``):
Unique identifier for this set of boosts.
date (:py:obj:`~datetime.datetime`):
Date the boost was applied.
expire_date (:py:obj:`~datetime.datetime`):
Point in time when the boost will expire.
multiplier (``int``):
If set, this boost counts as multiplier boosts, otherwise it counts as a single boost.
from_user (:obj:`~pyrogram.types.User`, *optional*):
The user that that applied the boost.
is_gift (``bool``, *optional*):
Whether this boost was applied because the channel/supergroup directly gifted a subscription to the user.
is_giveaway (``bool``, *optional*):
Whether this boost was applied because the user was chosen in a giveaway started by the channel/supergroup.
is_unclaimed (``bool``, *optional*):
If set, the user hasn't yet invoked :meth:`~pyrogram.Client.apply_gift_code` to claim a subscription gifted directly or in a giveaway by the channel.
giveaway_message_id (``int``, *optional*):
The message identifier of the giveaway.
used_gift_slug (``str``, *optional*):
The created Telegram Premium gift code, only set if either gift or giveaway are set AND it is either a gift code for the currently logged in user or if it was already claimed.
stars (``int``, *optional*):
Stars amount.
"""
def __init__(
self,
*,
id: str,
date: datetime,
expire_date: datetime,
multiplier: int,
from_user: Optional["types.User"] = None,
is_gift: Optional[bool] = None,
is_giveaway: Optional[bool] = None,
is_unclaimed: Optional[bool] = None,
giveaway_message_id: Optional[int] = None,
used_gift_slug: Optional[str] = None,
stars: Optional[int] = None
):
super().__init__()
self.id = id
self.date = date
self.expire_date = expire_date
self.multiplier = multiplier
self.from_user = from_user
self.is_gift = is_gift
self.is_giveaway = is_giveaway
self.is_unclaimed = is_unclaimed
self.giveaway_message_id = giveaway_message_id
self.used_gift_slug = used_gift_slug
self.stars = stars
@staticmethod
def _parse(client: "pyrogram.Client", boost: "raw.types.Boost", users) -> "ChatBoost":
return ChatBoost(
id=boost.id,
date=utils.timestamp_to_datetime(boost.date),
expire_date=utils.timestamp_to_datetime(boost.expires),
multiplier=getattr(boost, "multiplier", 1),
from_user=types.User._parse(client, users.get(boost.user_id)),
is_gift=getattr(boost, "gift", None),
is_giveaway=getattr(boost, "giveaway", None),
is_unclaimed=getattr(boost, "unclaimed", None),
giveaway_message_id=getattr(boost, "giveaway_msg_id", None),
used_gift_slug=getattr(boost, "used_gift_slug", None),
stars=getattr(boost, "stars", None)
)
# 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 ..object import Object
class ContactRegistered(Object):
"""A service message that a contact has registered with Telegram.
Currently holds no information.
"""
def __init__(self):
super().__init__()
# 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 pyrogram
from pyrogram import raw, types, errors
from ..object import Object
class GiveawayCompleted(Object):
"""This object represents a service message about the completion of a giveaway without public winners.
Parameters:
winner_count (``int``):
Number of winners in the giveaway.
unclaimed_prize_count (``int``, *optional*):
Number of undistributed prizes.
giveaway_message_id (``int``, *optional*):
Identifier of the message with the giveaway in the chat.
giveaway_message (:obj:`~pyrogram.types.Message`, *optional*):
Message with the giveaway that was completed, if it wasn't deleted.
is_star_giveaway (``bool``, *optional*):
True, if the giveaway is a Telegram Star giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
winner_count: int,
unclaimed_prize_count: int = None,
giveaway_message_id: int = None,
giveaway_message: "types.Message" = None,
is_star_giveaway: bool = None
):
super().__init__(client)
self.winner_count = winner_count
self.unclaimed_prize_count = unclaimed_prize_count
self.giveaway_message_id = giveaway_message_id
self.giveaway_message = giveaway_message
self.is_star_giveaway = is_star_giveaway
@staticmethod
async def _parse(
client,
giveaway_results: "raw.types.MessageActionGiveawayResults",
chat: "types.Chat" = None,
message_id: int = None
) -> "GiveawayCompleted":
if not isinstance(giveaway_results, raw.types.MessageActionGiveawayResults):
return
giveaway_message = None
if chat and message_id:
try:
giveaway_message = await client.get_messages(
chat.id,
message_id,
replies=0
)
except (errors.ChannelPrivate, errors.ChannelInvalid):
pass
return GiveawayCompleted(
winner_count=giveaway_results.winners_count,
unclaimed_prize_count=giveaway_results.unclaimed_count,
giveaway_message_id=message_id,
giveaway_message=giveaway_message,
is_star_giveaway=getattr(giveaway_results, "stars", None),
client=client,
)
# 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 Optional
import pyrogram
from pyrogram import raw
from ..object import Object
class GiveawayCreated(Object):
"""This object represents a service message about the creation of a scheduled giveaway.
Parameters:
prize_star_count (``int``, *optional*):
The number of Telegram Stars to be split between giveaway winners.
For Telegram Star giveaways only.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
prize_star_count: Optional[int] = None
):
super().__init__(client)
self.prize_star_count = prize_star_count
@staticmethod
def _parse(
client,
giveaway_launch: "raw.types.MessageActionGiveawayLaunch"
) -> "GiveawayCreated":
if isinstance(giveaway_launch, raw.types.MessageActionGiveawayLaunch):
return GiveawayCreated(
client=client,
prize_star_count=getattr(giveaway_launch, "stars", None)
)
# 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 List, Optional
import pyrogram
from pyrogram import raw, types, utils, errors
from ..object import Object
class GiveawayWinners(Object):
"""This object represents a message about the completion of a giveaway with public winners.
Parameters:
chat (:obj:`~pyrogram.types.Chat`):
The chat that created the giveaway
giveaway_message_id (``int``):
Identifier of the message with the giveaway in the chat
winners_selection_date (:py:obj:`~datetime.datetime`):
Point in time (Unix timestamp) when winners of the giveaway were selected
quantity (``int``):
Total number of subscriptions in this giveaway.
winner_count (``int``):
Total number of winners in the giveaway
unclaimed_prize_count (``int``):
Number of undistributed prizes
winners (:obj:`~pyrogram.types.User`):
List of up to 100 winners of the giveaway
giveaway_message (:obj:`~pyrogram.types.Message`, *optional*):
Returns the original giveaway start message.
additional_chat_count (``int``, *optional*):
The number of other chats the user had to join in order to be eligible for the giveaway
prize_star_count (``int``, *optional*):
The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only
premium_subscription_month_count (``int``, *optional*):
The number of months the Telegram Premium subscription won from the giveaway will be active for
only_new_members (``bool``, *optional*):
True, if only users who had joined the chats after the giveaway started were eligible to win
was_refunded (``bool``, *optional*):
True, if the giveaway was canceled because the payment for it was refunded
prize_description (``str``, *optional*):
Description of additional giveaway prize
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
chat: "types.Chat",
giveaway_message_id: int,
winners_selection_date: datetime,
quantity: int,
winner_count: int,
unclaimed_prize_count: Optional[int] = None,
winners: List["types.User"],
giveaway_message: Optional["types.Message"] = None,
additional_chat_count: Optional[int] = None,
prize_star_count: Optional[int] = None,
premium_subscription_month_count: Optional[int] = None,
only_new_members: Optional[bool] = None,
was_refunded: Optional[bool] = None,
prize_description: Optional[str] = None
):
super().__init__(client)
self.chat = chat
self.giveaway_message_id = giveaway_message_id
self.winners_selection_date = winners_selection_date
self.quantity = quantity
self.winner_count = winner_count
self.unclaimed_prize_count = unclaimed_prize_count
self.winners = winners
self.giveaway_message = giveaway_message
self.additional_chat_count = additional_chat_count
self.prize_star_count = prize_star_count
self.premium_subscription_month_count = premium_subscription_month_count
self.only_new_members = only_new_members
self.was_refunded = was_refunded
self.prize_description = prize_description
@staticmethod
async def _parse(
client,
chats: dict,
users: dict,
giveaway_media: "raw.types.MessageMediaGiveawayResults"
) -> "GiveawayWinners":
if not isinstance(giveaway_media, raw.types.MessageMediaGiveawayResults):
return
giveaway_message = None
try:
giveaway_message = await client.get_messages(
utils.get_channel_id(giveaway_media.channel_id),
giveaway_media.launch_msg_id,
replies=0
)
except (errors.ChannelPrivate, errors.ChannelInvalid):
pass
return GiveawayWinners(
chat=types.Chat._parse_channel_chat(client, chats[giveaway_media.channel_id]),
giveaway_message_id=giveaway_media.launch_msg_id,
giveaway_message=giveaway_message,
winners_selection_date=utils.timestamp_to_datetime(giveaway_media.until_date),
quantity=giveaway_media.winners_count + giveaway_media.unclaimed_count,
winner_count=giveaway_media.winners_count,
unclaimed_prize_count=giveaway_media.unclaimed_count,
winners=types.List(types.User._parse(client, users.get(i)) for i in giveaway_media.winners) or None,
additional_chat_count=getattr(giveaway_media, "additional_peers_count", None),
prize_star_count=giveaway_media.stars,
premium_subscription_month_count=getattr(giveaway_media, "months", None),
only_new_members=getattr(giveaway_media, "only_new_subscribers", None),
was_refunded=getattr(giveaway_media, "refunded", None),
prize_description=getattr(giveaway_media, "prize_description", None),
client=client
)
# 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 pyrogram import raw
from ..object import Object
class RefundedPayment(Object):
"""This object contains basic information about a refunded payment.
Parameters:
currency (``str``):
Three-letter ISO 4217 `currency <https://core.telegram.org/bots/payments#supported-currencies>`_ code, or ``XTR`` for payments in `Telegram Stars <https://t.me/BotNews/90>`_.
total_amount (``int``):
Total price in the smallest units of the currency (integer, **not** float/double). For example, for a price of ``US$ 1.45`` pass ``amount = 145``. See the __exp__ parameter in `currencies.json <https://core.telegram.org/bots/payments/currencies.json>`_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
invoice_payload (``str``):
Bot specified invoice payload. Only available to the bot that received the payment.
telegram_payment_charge_id (``str``):
Telegram payment identifier. Only available to the bot that received the payment.
provider_payment_charge_id (``str``):
Provider payment identifier. Only available to the bot that received the payment.
"""
def __init__(
self,
*,
currency: str,
total_amount: str,
invoice_payload: str,
telegram_payment_charge_id: str,
provider_payment_charge_id: str
):
super().__init__()
self.currency = currency
self.total_amount = total_amount
self.invoice_payload = invoice_payload
self.telegram_payment_charge_id = telegram_payment_charge_id
self.provider_payment_charge_id = provider_payment_charge_id
@staticmethod
def _parse(
refunded_payment: "raw.types.MessageActionPaymentRefunded"
) -> "RefundedPayment":
invoice_payload = None
# Try to decode invoice payload into string. If that fails, fallback to bytes instead of decoding by
# ignoring/replacing errors, this way, button clicks will still work.
try:
invoice_payload = refunded_payment.payload.decode()
except (UnicodeDecodeError, AttributeError):
invoice_payload = getattr(refunded_payment, "payload", None)
return RefundedPayment(
currency=refunded_payment.currency,
total_amount=refunded_payment.total_amount,
invoice_payload=invoice_payload,
telegram_payment_charge_id=refunded_payment.charge.id,
provider_payment_charge_id=refunded_payment.charge.provider_charge_id
)
# 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 ..object import Object
class ScreenshotTaken(Object):
"""A service message that a screenshot of a message in the chat has been taken.
Currently holds no information.
"""
def __init__(self):
super().__init__()
# 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, List
import pyrogram
from pyrogram import raw
from pyrogram import types
from pyrogram import utils
from ..object import Object
class StarGift(Object):
"""A star gift.
Parameters:
id (``int``):
Unique star gift identifier.
sticker (:obj:`~pyrogram.types.Sticker`):
Information about the star gift sticker.
caption (``str``, *optional*):
Text message.
caption_entities (List of :obj:`~pyrogram.types.MessageEntity`, *optional*):
For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text.
message_id (``int``, *optional*):
Unique message identifier.
date (``datetime``, *optional*):
Date when the star gift was received.
first_sale_date (``datetime``, *optional*):
Date when the star gift was first purchased.
last_sale_date (``datetime``, *optional*):
Date when the star gift was last purchased.
from_user (:obj:`~pyrogram.types.User`, *optional*):
User who sent the star gift.
price (``int``, *optional*):
Price of this gift in stars.
convert_price (``int``, *optional*):
The number of stars you get if you convert this gift.
available_amount (``int``, *optional*):
The number of gifts available for purchase.
Returned only if is_limited is True.
total_amount (``int``, *optional*):
Total amount of gifts.
Returned only if is_limited is True.
is_limited (``bool``, *optional*):
True, if the number of gifts is limited.
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.
is_sold_out (``bool``, *optional*):
True, if the star gift is sold out.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
id: int,
sticker: "types.Sticker",
caption: Optional[str] = None,
caption_entities: List["types.MessageEntity"] = None,
message_id: Optional[int] = None,
date: Optional[datetime] = None,
first_sale_date: Optional[datetime] = None,
last_sale_date: Optional[datetime] = None,
from_user: Optional["types.User"] = None,
price: Optional[int] = None,
convert_price: Optional[int] = None,
available_amount: Optional[int] = None,
total_amount: Optional[int] = None,
is_limited: Optional[bool] = None,
is_name_hidden: Optional[bool] = None,
is_saved: Optional[bool] = None,
is_sold_out: Optional[bool] = None
):
super().__init__(client)
self.id = id
self.sticker = sticker
self.caption = caption
self.caption_entities = caption_entities
self.message_id = message_id
self.date = date
self.first_sale_date = first_sale_date
self.last_sale_date = last_sale_date
self.from_user = from_user
self.price = price
self.convert_price = convert_price
self.available_amount = available_amount
self.total_amount = total_amount
self.is_limited = is_limited
self.is_name_hidden = is_name_hidden
self.is_saved = is_saved
self.is_sold_out = is_sold_out
@staticmethod
async def _parse(
client,
star_gift: "raw.types.StarGift",
) -> "StarGift":
doc = star_gift.sticker
attributes = {type(i): i for i in doc.attributes}
return StarGift(
id=star_gift.id,
sticker=await types.Sticker._parse(client, doc, attributes),
price=star_gift.stars,
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),
first_sale_date=utils.timestamp_to_datetime(getattr(star_gift, "first_sale_date", None)),
last_sale_date=utils.timestamp_to_datetime(getattr(star_gift, "last_sale_date", None)),
is_sold_out=getattr(star_gift, "sold_out", None),
client=client
)
@staticmethod
async def _parse_user_star_gift(
client,
user_star_gift: "raw.types.UserStarGift",
users: dict
) -> "StarGift":
doc = user_star_gift.gift.sticker
attributes = {type(i): i for i in doc.attributes}
caption, caption_entities = (
utils.parse_text_with_entities(
client, getattr(user_star_gift, "message", None), users
)
).values()
return StarGift(
id=user_star_gift.gift.id,
sticker=await types.Sticker._parse(client, doc, attributes),
price=user_star_gift.gift.stars,
convert_price=user_star_gift.gift.convert_stars,
available_amount=getattr(user_star_gift.gift, "availability_remains", None),
total_amount=getattr(user_star_gift.gift, "availability_total", None),
date=utils.timestamp_to_datetime(user_star_gift.date),
is_limited=getattr(user_star_gift.gift, "limited", None),
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,
message_id=getattr(user_star_gift, "msg_id", None),
caption=caption,
caption_entities=caption_entities,
client=client
)
@staticmethod
async def _parse_action(
client,
message: "raw.base.Message",
users: dict
) -> "StarGift":
action = message.action
doc = action.gift.sticker
attributes = {type(i): i for i in doc.attributes}
caption, caption_entities = (
utils.parse_text_with_entities(
client, getattr(action, "message", None), users
)
).values()
return StarGift(
id=action.gift.id,
sticker=await types.Sticker._parse(client, doc, attributes),
price=action.gift.stars,
convert_price=action.gift.convert_stars,
available_amount=getattr(action.gift, "availability_remains", None),
total_amount=getattr(action.gift, "availability_total", None),
date=utils.timestamp_to_datetime(message.date),
is_limited=getattr(action.gift, "limited", None),
is_name_hidden=getattr(action, "name_hidden", None),
is_saved=getattr(action, "saved", None),
from_user=types.User._parse(client, users.get(utils.get_raw_peer_id(message.peer_id))),
message_id=message.id,
caption=caption,
caption_entities=caption_entities,
client=client
)
async def show(self) -> bool:
"""Bound method *show* of :obj:`~pyrogram.types.StarGift`.
Use as a shortcut for:
.. code-block:: python
await client.show_star_gift(
chat_id=message.chat.id,
message_id=message_id
)
Example:
.. code-block:: python
await star_gift.show()
Returns:
``bool``: On success, True is returned.
"""
return await self._client.show_star_gift(
chat_id=self.from_user.id,
message_id=self.message_id
)
async def hide(self) -> bool:
"""Bound method *hide* of :obj:`~pyrogram.types.StarGift`.
Use as a shortcut for:
.. code-block:: python
await client.hide_star_gift(
chat_id=message.chat.id,
message_id=message_id
)
Example:
.. code-block:: python
await star_gift.hide()
Returns:
``bool``: On success, True is returned.
"""
return await self._client.hide_star_gift(
chat_id=self.from_user.id,
message_id=self.message_id
)
# 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 pyrogram import raw
from ..object import Object
class WriteAccessAllowed(Object):
"""This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method `requestWriteAccess <https://core.telegram.org/bots/webapps#initializing-mini-apps>`__.
Parameters:
from_request (``bool``, *optional*):
True, if the access was granted after the user accepted an explicit request from a Web App sent by the method `requestWriteAccess <https://core.telegram.org/bots/webapps#initializing-mini-apps>`__
web_app_name (``str``, *optional*):
Name of the Web App, if the access was granted when the Web App was launched from a link
from_attachment_menu (``bool``, *optional*):
True, if the access was granted when the bot was added to the attachment or side menu
"""
def __init__(
self,
*,
from_request: bool = None,
web_app_name: str = None,
from_attachment_menu: bool = None,
):
super().__init__()
self.from_request = from_request
self.web_app_name = web_app_name
self.from_attachment_menu = from_attachment_menu
@staticmethod
def _parse(action: "raw.types.MessageActionBotAllowed"):
return WriteAccessAllowed(
from_request=action.from_request if action.from_request else None,
web_app_name=action.app.short_name if action.app is not None else None,
from_attachment_menu=action.attach_menu if action.attach_menu else None,
)
# 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 Optional
from pyrogram import raw, enums
from ..object import Object
class PhoneCallEnded(Object):
"""A service message about a phone_call ended in the chat.
Parameters:
id (``int``):
Unique call identifier.
is_video (``bool``):
True, if call was a video call.
reason (:obj:`~pyrogram.enums.PhoneCallDiscardReason`):
The reason enumeration why the call was discarded.
duration (``int``, *optional*):
Voice chat duration; in seconds.
"""
def __init__(
self, *,
id: int,
is_video: bool,
reason: "enums.PhoneCallDiscardReason",
duration: Optional[int] = None
):
super().__init__()
self.id = id
self.is_video = is_video
self.reason = reason
self.duration = duration
@staticmethod
def _parse(action: "raw.types.MessageActionPhoneCall") -> "PhoneCallEnded":
return PhoneCallEnded(
id=action.call_id,
is_video=action.video,
reason=enums.PhoneCallDiscardReason(type(action.reason)),
duration=getattr(action, "duration", None)
)
# 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 pyrogram import raw
from ..object import Object
class PhoneCallStarted(Object):
"""A service message about a phone_call started in the chat.
Parameters:
id (``int``):
Unique call identifier.
is_video (``bool``):
True, if call was a video call.
"""
def __init__(
self, *,
id: int,
is_video: bool
):
super().__init__()
self.id = id
self.is_video = is_video
@staticmethod
def _parse(action: "raw.types.MessageActionPhoneCall") -> "PhoneCallStarted":
return PhoneCallStarted(
id=action.call_id,
is_video=action.video
)
+135
-9

@@ -151,2 +151,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

send_message
forward_media_group
forward_messages

@@ -210,2 +211,3 @@ copy_message

send_paid_media
send_paid_reaction
""",

@@ -228,2 +230,4 @@ chats="""

unpin_chat_message
pin_forum_topic
unpin_forum_topic
unpin_all_chat_messages

@@ -237,3 +241,2 @@ get_chat

set_chat_username
get_nearby_chats
archive_chats

@@ -327,5 +330,13 @@ unarchive_chats

Payments
apply_gift_code
check_gift_code
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
show_star_gift
""",

@@ -362,2 +373,11 @@ phone="""

answer_pre_checkout_query
answer_shipping_query
create_invoice_link
refund_star_payment
set_bot_info_description
get_bot_info_description
set_bot_info_short_description
get_bot_info_short_description
set_bot_name
get_bot_name
""",

@@ -397,3 +417,3 @@ business="""

Stories
can_send_story
can_post_stories
copy_story

@@ -408,8 +428,10 @@ delete_stories

get_pinned_stories
get_stories_archive
get_archived_stories
get_stories
hide_stories
hide_chat_stories
show_chat_stories
view_stories
pin_stories
read_stories
pin_chat_stories
unpin_chat_stories
read_chat_stories
send_story

@@ -474,3 +496,2 @@ """,

BusinessIntro
BusinessMessage
BusinessRecipients

@@ -504,2 +525,3 @@ BusinessWeeklyOpen

Messages & Media
BusinessMessage
Message

@@ -512,2 +534,7 @@ MessageEntity

Document
ForumTopic
ForumTopicClosed
ForumTopicCreated
ForumTopicEdited
ForumTopicReopened
Animation

@@ -527,2 +554,4 @@ Video

Reaction
RefundedPayment
StarGift
VideoChatScheduled

@@ -532,2 +561,4 @@ VideoChatStarted

VideoChatMembersInvited
PhoneCallStarted
PhoneCallEnded
WebAppData

@@ -540,3 +571,5 @@ MessageReactions

Giveaway
GiveawayResult
GiveawayCreated
GiveawayCompleted
GiveawayWinners
Invoice

@@ -549,2 +582,6 @@ GiftCode

PaymentForm
ChatBoost
ContactRegistered
ScreenshotTaken
WriteAccessAllowed
""",

@@ -569,3 +606,2 @@ bot_keyboards="""

SentWebAppMessage
ForumTopic
RequestChannelInfo

@@ -578,2 +614,8 @@ RequestChatInfo

ShippingAddress
ShippingQuery
MessageReactionUpdated
MessageReactionCountUpdated
ChatBoostUpdated
ShippingOption
PurchasedPaidMedia
""",

@@ -768,2 +810,6 @@ bot_commands="""

""",
shipping_query="""
ShippingQuery
ShippingQuery.answer
""",
chat_join_request="""

@@ -776,2 +822,3 @@ ChatJoinRequest

Story
Story.reply
Story.reply_text

@@ -812,2 +859,7 @@ Story.reply_animation

ActiveSession.reset
""",
star_gift="""
StarGift
StarGift.show
StarGift.hide
"""

@@ -846,2 +898,76 @@ )

# Enumerations
categories = dict(
enums="""
Enumerations
BusinessSchedule
ChatAction
ChatEventAction
ChatJoinType
ChatMemberStatus
ChatMembersFilter
ChatType
ClientPlatform
FolderColor
MessageEntityType
MessageServiceType
MessagesFilter
NextCodeType
ParseMode
PhoneCallDiscardReason
PollType
PrivacyKey
ProfileColor
ReplyColor
SentCodeType
StoriesPrivacyRules
UserStatus
""",
)
root = PYROGRAM_API_DEST + "/enums"
shutil.rmtree(root, ignore_errors=True)
os.mkdir(root)
with open(HOME + "/template/enums.rst") as f:
template = f.read()
with open(root + "/cleanup.html", "w") as f:
f.write("""<script>
document
.querySelectorAll("em.property")
.forEach((elem, i) => i !== 0 ? elem.remove() : true)
document
.querySelectorAll("a.headerlink")
.forEach((elem, i) => [0, 1].includes(i) ? true : elem.remove())
</script>""")
with open(root + "/index.rst", "w") as f:
fmt_keys = {}
for k, v in categories.items():
name, *enums = get_title_list(v)
fmt_keys.update({"{}_hlist".format(k): "\n ".join("{}".format(enum) for enum in enums)})
fmt_keys.update(
{"{}_toctree".format(k): "\n ".join("{}".format(enum) for enum in enums)})
# noinspection PyShadowingBuiltins
for enum in enums:
with open(root + "/{}.rst".format(enum), "w") as f2:
title = "{}".format(enum)
f2.write(title + "\n" + "=" * len(title) + "\n\n")
f2.write(".. autoclass:: pyrogram.enums.{}()".format(enum))
f2.write("\n :members:\n")
f2.write("\n.. raw:: html\n :file: ./cleanup.html\n")
f.write(template.format(**fmt_keys))
def start():

@@ -848,0 +974,0 @@ global page_template

+1
-1
Metadata-Version: 2.1
Name: WPyrogram
Version: 2.0.148
Version: 2.0.149
Summary: Elegant, modern and asynchronous Telegram MTProto API framework in Python for users and bots - Woto's experimental fork

@@ -5,0 +5,0 @@ Home-page: https://github.com/ALiwoto/WPyrogram

@@ -19,3 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

__version__ = "2.0.148"
__version__ = "2.0.149"
__license__ = "GNU Lesser General Public License v3.0 (LGPL-3.0)"

@@ -22,0 +22,0 @@ __copyright__ = "Copyright (C) 2017-present Dan <https://github.com/delivrance>"

@@ -54,4 +54,2 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram.storage import Storage, FileStorage, MemoryStorage
from pyrogram.types import User, TermsOfService, ListenerStopped, ListenerTimeout, ListenerTypes
from pyrogram.utils import ainput, PyromodConfig
from pyrogram.types import User, TermsOfService

@@ -357,3 +355,2 @@ from pyrogram.utils import ainput

self.loop = asyncio.get_event_loop()
self.listeners = {listener_type: {} for listener_type in ListenerTypes}

@@ -390,133 +387,2 @@ def __enter__(self):

async def listen(
self,
identifier: tuple,
filters=None,
listener_type=ListenerTypes.MESSAGE,
timeout=None,
unallowed_click_alert=True,
):
if type(listener_type) != ListenerTypes:
raise TypeError(
"Parameter listener_type should be a"
" value from pyromod.listen.ListenerTypes"
)
future = self.loop.create_future()
future.add_done_callback(
lambda f: self.stop_listening(identifier, listener_type)
)
listener_data = {
"future": future,
"filters": filters,
"unallowed_click_alert": unallowed_click_alert,
}
self.listeners[listener_type].update({identifier: listener_data})
try:
return await asyncio.wait_for(future, timeout)
except asyncio.exceptions.TimeoutError:
if callable(PyromodConfig.timeout_handler):
PyromodConfig.timeout_handler(
identifier, listener_data, timeout
)
elif PyromodConfig.throw_exceptions:
raise ListenerTimeout(timeout)
async def ask(
self,
text,
identifier: tuple,
filters=None,
listener_type=ListenerTypes.MESSAGE,
timeout=None,
*args,
**kwargs
):
request = await self.send_message(identifier[0], text, *args, **kwargs)
response = await self.listen(
identifier, filters, listener_type, timeout
)
if response:
response.request = request
return response
"""
needed for matching when message_id or
user_id is null, and to take precedence
"""
def match_listener(
self,
data: Optional[tuple] = None,
listener_type: ListenerTypes = ListenerTypes.MESSAGE,
identifier_pattern: Optional[tuple] = None,
) -> tuple:
if data:
listeners = self.listeners[listener_type]
# case with 3 args on identifier
# most probably waiting for a specific user
# to click a button in a specific message
if data in listeners:
return listeners[data], data
# cases with 2 args on identifier
# (None, user, message) does not make
# sense since the message_id is not unique
elif (data[0], data[1], None) in listeners:
matched = (data[0], data[1], None)
elif (data[0], None, data[2]) in listeners:
matched = (data[0], None, data[2])
# cases with 1 arg on identifier
# (None, None, message) does not make sense as well
elif (data[0], None, None) in listeners:
matched = (data[0], None, None)
elif (None, data[1], None) in listeners:
matched = (None, data[1], None)
else:
return None, None
return listeners[matched], matched
elif identifier_pattern:
def match_identifier(pattern, identifier):
comparison = (
pattern[0] in (identifier[0], None),
pattern[1] in (identifier[1], None),
pattern[2] in (identifier[2], None),
)
return comparison == (True, True, True)
for identifier, listener in self.listeners[listener_type].items():
if match_identifier(identifier_pattern, identifier):
return listener, identifier
return None, None
def stop_listening(
self,
data: Optional[tuple] = None,
listener_type: ListenerTypes = ListenerTypes.MESSAGE,
identifier_pattern: Optional[tuple] = None,
):
listener, identifier = self.match_listener(
data, listener_type, identifier_pattern
)
if not listener:
return
elif listener["future"].done():
del self.listeners[listener_type][identifier]
return
if callable(PyromodConfig.stopped_handler):
PyromodConfig.stopped_handler(identifier, listener)
elif PyromodConfig.throw_exceptions:
listener["future"].set_exception(ListenerStopped())
del self.listeners[listener_type][identifier]
async def authorize(self) -> User:

@@ -523,0 +389,0 @@ if self.bot_token:

@@ -21,3 +21,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

import logging
from typing import Optional
from typing import Optional, Type

@@ -33,3 +33,11 @@ from .transport import TCP, TCPAbridged

def __init__(self, dc_id: int, test_mode: bool, ipv6: bool, proxy: dict, media: bool = False):
def __init__(
self,
dc_id: int,
test_mode: bool,
ipv6: bool,
proxy: dict,
media: bool = False,
protocol_factory: Type[TCP] = TCPAbridged
) -> None:
self.dc_id = dc_id

@@ -40,9 +48,10 @@ self.test_mode = test_mode

self.media = media
self.protocol_factory = protocol_factory
self.address = DataCenter(dc_id, test_mode, ipv6, media)
self.protocol: TCP = None
self.protocol: Optional[TCP] = None
async def connect(self):
async def connect(self) -> None:
for i in range(Connection.MAX_CONNECTION_ATTEMPTS):
self.protocol = TCPAbridged(self.ipv6, self.proxy)
self.protocol = self.protocol_factory(ipv6=self.ipv6, proxy=self.proxy)

@@ -67,7 +76,7 @@ try:

async def close(self):
async def close(self) -> None:
await self.protocol.close()
log.info("Disconnected")
async def send(self, data: bytes):
async def send(self, data: bytes) -> None:
await self.protocol.send(data)

@@ -74,0 +83,0 @@

@@ -19,3 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .tcp import TCP
from .tcp import TCP, Proxy
from .tcp_abridged import TCPAbridged

@@ -22,0 +22,0 @@ from .tcp_abridged_o import TCPAbridgedO

@@ -21,7 +21,7 @@ # Pyrogram - Telegram MTProto API Client Library for Python

import os
from typing import Optional
from typing import Optional, Tuple
import pyrogram
from pyrogram.crypto import aes
from .tcp import TCP
from .tcp import TCP, Proxy

@@ -34,3 +34,3 @@ log = logging.getLogger(__name__)

def __init__(self, ipv6: bool, proxy: dict):
def __init__(self, ipv6: bool, proxy: Proxy) -> None:
super().__init__(ipv6, proxy)

@@ -41,3 +41,3 @@

async def connect(self, address: tuple):
async def connect(self, address: Tuple[str, int]) -> None:
await super().connect(address)

@@ -61,3 +61,3 @@

async def send(self, data: bytes, *args):
async def send(self, data: bytes, *args) -> None:
length = len(data) // 4

@@ -64,0 +64,0 @@ data = (bytes([length]) if length <= 126 else b"\x7f" + length.to_bytes(3, "little")) + data

@@ -20,5 +20,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

import logging
from typing import Optional
from typing import Optional, Tuple
from .tcp import TCP
from .tcp import TCP, Proxy

@@ -29,10 +29,10 @@ log = logging.getLogger(__name__)

class TCPAbridged(TCP):
def __init__(self, ipv6: bool, proxy: dict):
def __init__(self, ipv6: bool, proxy: Proxy) -> None:
super().__init__(ipv6, proxy)
async def connect(self, address: tuple):
async def connect(self, address: Tuple[str, int]) -> None:
await super().connect(address)
await super().send(b"\xef")
async def send(self, data: bytes, *args):
async def send(self, data: bytes, *args) -> None:
length = len(data) // 4

@@ -39,0 +39,0 @@

@@ -22,5 +22,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from struct import pack, unpack
from typing import Optional
from typing import Optional, Tuple
from .tcp import TCP
from .tcp import TCP, Proxy

@@ -31,12 +31,12 @@ log = logging.getLogger(__name__)

class TCPFull(TCP):
def __init__(self, ipv6: bool, proxy: dict):
def __init__(self, ipv6: bool, proxy: Proxy) -> None:
super().__init__(ipv6, proxy)
self.seq_no = None
self.seq_no: Optional[int] = None
async def connect(self, address: tuple):
async def connect(self, address: Tuple[str, int]) -> None:
await super().connect(address)
self.seq_no = 0
async def send(self, data: bytes, *args):
async def send(self, data: bytes, *args) -> None:
data = pack("<II", len(data) + 12, self.seq_no) + data

@@ -43,0 +43,0 @@ data += pack("<I", crc32(data))

@@ -22,6 +22,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from struct import pack, unpack
from typing import Optional
from typing import Optional, Tuple
from pyrogram.crypto import aes
from .tcp import TCP
from .tcp import TCP, Proxy

@@ -34,3 +34,3 @@ log = logging.getLogger(__name__)

def __init__(self, ipv6: bool, proxy: dict):
def __init__(self, ipv6: bool, proxy: Proxy) -> None:
super().__init__(ipv6, proxy)

@@ -41,3 +41,3 @@

async def connect(self, address: tuple):
async def connect(self, address: Tuple[str, int]) -> None:
await super().connect(address)

@@ -61,3 +61,3 @@

async def send(self, data: bytes, *args):
async def send(self, data: bytes, *args) -> None:
await super().send(

@@ -64,0 +64,0 @@ aes.ctr256_encrypt(

@@ -21,5 +21,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from struct import pack, unpack
from typing import Optional
from typing import Optional, Tuple
from .tcp import TCP
from .tcp import TCP, Proxy

@@ -30,10 +30,10 @@ log = logging.getLogger(__name__)

class TCPIntermediate(TCP):
def __init__(self, ipv6: bool, proxy: dict):
def __init__(self, ipv6: bool, proxy: Proxy) -> None:
super().__init__(ipv6, proxy)
async def connect(self, address: tuple):
async def connect(self, address: Tuple[str, int]) -> None:
await super().connect(address)
await super().send(b"\xee" * 4)
async def send(self, data: bytes, *args):
async def send(self, data: bytes, *args) -> None:
await super().send(pack("<i", len(data)) + data)

@@ -40,0 +40,0 @@

@@ -24,2 +24,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from concurrent.futures import ThreadPoolExecutor
from typing import Tuple, Dict, TypedDict, Optional

@@ -30,11 +31,26 @@ import socks

proxy_type_by_scheme: Dict[str, int] = {
"SOCKS4": socks.SOCKS4,
"SOCKS5": socks.SOCKS5,
"HTTP": socks.HTTP,
}
class Proxy(TypedDict):
scheme: str
hostname: str
port: int
username: Optional[str]
password: Optional[str]
class TCP:
TIMEOUT = 10
def __init__(self, ipv6: bool, proxy: dict):
self.socket = None
def __init__(self, ipv6: bool, proxy: Proxy) -> None:
self.ipv6 = ipv6
self.proxy = proxy
self.reader = None
self.writer = None
self.reader: Optional[asyncio.StreamReader] = None
self.writer: Optional[asyncio.StreamWriter] = None

@@ -44,62 +60,89 @@ self.lock = asyncio.Lock()

self.proxy = proxy
async def _connect_via_proxy(
self,
destination: Tuple[str, int]
) -> None:
scheme = self.proxy.get("scheme")
if scheme is None:
raise ValueError("No scheme specified")
if proxy:
hostname = proxy.get("hostname")
proxy_type = proxy_type_by_scheme.get(scheme.upper())
if proxy_type is None:
raise ValueError(f"Unknown proxy type {scheme}")
try:
ip_address = ipaddress.ip_address(hostname)
except ValueError:
self.socket = socks.socksocket(socket.AF_INET)
else:
if isinstance(ip_address, ipaddress.IPv6Address):
self.socket = socks.socksocket(socket.AF_INET6)
else:
self.socket = socks.socksocket(socket.AF_INET)
hostname = self.proxy.get("hostname")
port = self.proxy.get("port")
username = self.proxy.get("username")
password = self.proxy.get("password")
self.socket.set_proxy(
proxy_type=getattr(socks, proxy.get("scheme").upper()),
addr=hostname,
port=proxy.get("port", None),
username=proxy.get("username", None),
password=proxy.get("password", None)
)
try:
ip_address = ipaddress.ip_address(hostname)
except ValueError:
is_proxy_ipv6 = False
else:
is_proxy_ipv6 = isinstance(ip_address, ipaddress.IPv6Address)
self.socket.settimeout(TCP.TIMEOUT)
proxy_family = socket.AF_INET6 if is_proxy_ipv6 else socket.AF_INET
sock = socks.socksocket(proxy_family)
log.info("Using proxy %s", hostname)
else:
self.socket = socket.socket(
socket.AF_INET6 if ipv6
else socket.AF_INET
)
sock.set_proxy(
proxy_type=proxy_type,
addr=hostname,
port=port,
username=username,
password=password
)
sock.settimeout(TCP.TIMEOUT)
self.socket.setblocking(False)
with ThreadPoolExecutor() as executor:
await self.loop.run_in_executor(executor, sock.connect, destination)
async def connect(self, address: tuple):
sock.setblocking(False)
self.reader, self.writer = await asyncio.open_connection(
sock=sock
)
async def _connect_via_direct(
self,
destination: Tuple[str, int]
) -> None:
host, port = destination
family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
self.reader, self.writer = await asyncio.open_connection(
host=host,
port=port,
family=family
)
async def _connect(self, destination: Tuple[str, int]) -> None:
if self.proxy:
with ThreadPoolExecutor(1) as executor:
await self.loop.run_in_executor(executor, self.socket.connect, address)
await self._connect_via_proxy(destination)
else:
try:
await asyncio.wait_for(asyncio.get_event_loop().sock_connect(self.socket, address), TCP.TIMEOUT)
except asyncio.TimeoutError: # Re-raise as TimeoutError. asyncio.TimeoutError is deprecated in 3.11
raise TimeoutError("Connection timed out")
await self._connect_via_direct(destination)
self.reader, self.writer = await asyncio.open_connection(sock=self.socket)
async def connect(self, address: Tuple[str, int]) -> None:
try:
await asyncio.wait_for(self._connect(address), TCP.TIMEOUT)
except asyncio.TimeoutError: # Re-raise as TimeoutError. asyncio.TimeoutError is deprecated in 3.11
raise TimeoutError("Connection timed out")
async def close(self):
async def close(self) -> None:
if self.writer is None:
return None
try:
if self.writer is not None:
self.writer.close()
await asyncio.wait_for(self.writer.wait_closed(), TCP.TIMEOUT)
self.writer.close()
await asyncio.wait_for(self.writer.wait_closed(), TCP.TIMEOUT)
except Exception as e:
log.info("Close exception: %s %s", type(e).__name__, e)
async def send(self, data: bytes):
async def send(self, data: bytes) -> None:
if self.writer is None:
return None
async with self.lock:
try:
if self.writer is not None:
self.writer.write(data)
await self.writer.drain()
self.writer.write(data)
await self.writer.drain()
except Exception as e:

@@ -109,3 +152,3 @@ log.info("Send exception: %s %s", type(e).__name__, e)

async def recv(self, length: int = 0):
async def recv(self, length: int = 0) -> Optional[bytes]:
data = b""

@@ -112,0 +155,0 @@

@@ -44,6 +44,2 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram.handlers import (
ConversationHandler
)
log = logging.getLogger(__name__)

@@ -76,5 +72,2 @@

self.conversation_handler = ConversationHandler()
self.groups[0] = [self.conversation_handler]
async def message_parser(update, users, chats):

@@ -81,0 +74,0 @@ return (

@@ -22,2 +22,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .chat_event_action import ChatEventAction
from .chat_join_type import ChatJoinType
from .chat_member_status import ChatMemberStatus

@@ -34,3 +35,5 @@ from .chat_members_filter import ChatMembersFilter

from .parse_mode import ParseMode
from .phone_call_discard_reason import PhoneCallDiscardReason
from .poll_type import PollType
from .privacy_key import PrivacyKey
from .profile_color import ProfileColor

@@ -46,2 +49,3 @@ from .reply_color import ReplyColor

'ChatEventAction',
'ChatJoinType',
'ChatMemberStatus',

@@ -58,3 +62,5 @@ 'ChatMembersFilter',

'ParseMode',
'PhoneCallDiscardReason',
'PollType',
'PrivacyKey',
'ProfileColor',

@@ -61,0 +67,0 @@ 'ReplyColor',

@@ -30,6 +30,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

HASHTAG = raw.types.MessageEntityHashtag
"``#hashtag``"
"``#hashtag`` or ``#hashtag@username``"
CASHTAG = raw.types.MessageEntityCashtag
"``$USD``"
"``$USD`` or ``$USD@username``"

@@ -36,0 +36,0 @@ BOT_COMMAND = raw.types.MessageEntityBotCommand

@@ -75,4 +75,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

GIVEAWAY_RESULT = auto()
"Giveaway result media"
GIVEAWAY_WINNERS = auto()
"Giveaway winners media"

@@ -84,1 +84,4 @@ STORY = auto()

"Invoice media"
PAID_MEDIA = auto()
"Paid media"

@@ -81,5 +81,8 @@ # Pyrogram - Telegram MTProto API Client Library for Python

GIVEAWAY_LAUNCH = auto()
"Giveaway launch"
GIVEAWAY_CREATED = auto()
"Giveaway created"
GIVEAWAY_COMPLETED = auto()
"Giveaway completed"
GIFT_CODE = auto()

@@ -100,2 +103,8 @@ "Gift code"

PHONE_CALL_STARTED = auto()
"Phone call started"
PHONE_CALL_ENDED = auto()
"Phone call ended"
WEB_APP_DATA = auto()

@@ -110,2 +119,5 @@ "Web app data"

REFUNDED_PAYMENT = auto()
"Refunded payment"
CHAT_TTL_CHANGED = auto()

@@ -117,3 +129,15 @@ "Chat TTL changed"

JOIN_REQUEST_APPROVED = auto()
"Join request approved"
STAR_GIFT = auto()
"Star gift"
CONNECTED_WEBSITE = auto()
"Connected website"
WRITE_ACCESS_ALLOWED = auto()
"Write access allowed"
SCREENSHOT_TAKEN = auto()
"Screenshot taken"
CONTACT_REGISTERED = auto()
"Contact registered"

@@ -20,5 +20,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .callback_query_handler import CallbackQueryHandler
from .chat_boost_handler import ChatBoostHandler
from .chat_join_request_handler import ChatJoinRequestHandler
from .chat_member_updated_handler import ChatMemberUpdatedHandler
from .conversation_handler import ConversationHandler
from .chosen_inline_result_handler import ChosenInlineResultHandler

@@ -30,6 +30,10 @@ from .deleted_messages_handler import DeletedMessagesHandler

from .message_handler import MessageHandler
from .message_reaction_count_handler import MessageReactionCountHandler
from .message_reaction_handler import MessageReactionHandler
from .poll_handler import PollHandler
from .pre_checkout_query_handler import PreCheckoutQueryHandler
from .purchased_paid_media_handler import PurchasedPaidMediaHandler
from .raw_update_handler import RawUpdateHandler
from .shipping_query_handler import ShippingQueryHandler
from .story_handler import StoryHandler
from .user_status_handler import UserStatusHandler

@@ -30,2 +30,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

.. note::
Days should be in range 30-730
.. include:: /_includes/usable-by/users.rst

@@ -43,3 +47,3 @@

# Set ttl in days
# Set account ttl to 1 year
await app.set_account_ttl(365)

@@ -46,0 +50,0 @@ """

@@ -76,3 +76,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

except KeyError:
await self.invoke(
r = await self.invoke(
raw.functions.contacts.ResolveUsername(

@@ -83,2 +83,7 @@ username=peer_id

if isinstance(r.peer, raw.types.PeerUser):
return await self.storage.get_peer_by_id(r.peer.user_id)
elif isinstance(r.peer, raw.types.PeerChannel):
return await self.storage.get_peer_by_id(utils.get_channel_id(r.peer.channel_id))
return await self.storage.get_peer_by_username(peer_id)

@@ -123,3 +128,2 @@ else:

)
try:

@@ -126,0 +130,0 @@ return await self.storage.get_peer_by_id(peer_id)

@@ -132,3 +132,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

file_size_limit_mib = 4000 if self.me.is_premium else 2000
if self.me and self.me.is_premium:
file_size_limit_mib = 4000
else:
file_size_limit_mib = 2000

@@ -135,0 +138,0 @@ if file_size > file_size_limit_mib * 1024 * 1024:

@@ -22,6 +22,11 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .answer_pre_checkout_query import AnswerPreCheckoutQuery
from .answer_shipping_query import AnswerShippingQuery
from .answer_web_app_query import AnswerWebAppQuery
from .create_invoice_link import CreateInvoiceLink
from .delete_bot_commands import DeleteBotCommands
from .get_bot_commands import GetBotCommands
from .get_bot_default_privileges import GetBotDefaultPrivileges
from .get_bot_info_description import GetBotInfoDescription
from .get_bot_info_short_description import GetBotInfoShortDescription
from .get_bot_name import GetBotName
from .get_chat_menu_button import GetChatMenuButton

@@ -37,2 +42,5 @@ from .get_game_high_scores import GetGameHighScores

from .set_bot_default_privileges import SetBotDefaultPrivileges
from .set_bot_info_description import SetBotInfoDescription
from .set_bot_info_short_description import SetBotInfoShortDescription
from .set_bot_name import SetBotName
from .set_chat_menu_button import SetChatMenuButton

@@ -45,2 +53,5 @@ from .set_game_score import SetGameScore

AnswerInlineQuery,
AnswerPreCheckoutQuery,
AnswerShippingQuery,
CreateInvoiceLink,
GetInlineBotResults,

@@ -58,8 +69,13 @@ RefundStarPayment,

SetBotDefaultPrivileges,
SetBotInfoDescription,
SetBotInfoShortDescription,
SetBotName,
GetBotDefaultPrivileges,
GetBotInfoDescription,
GetBotInfoShortDescription,
GetBotName,
SetChatMenuButton,
GetChatMenuButton,
AnswerWebAppQuery,
AnswerPreCheckoutQuery
AnswerWebAppQuery
):
pass

@@ -38,2 +38,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

protect_content: bool = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -80,2 +81,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup`, *optional*):

@@ -111,2 +118,3 @@ An object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown automatically.

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -113,0 +121,0 @@ effect=effect_id

@@ -58,2 +58,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

reply_to_message_id: Optional[int] = None,
allow_paid_broadcast: bool = None,
reply_markup: Optional[Union[

@@ -156,2 +157,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -221,2 +228,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -223,0 +231,0 @@ effect=message_effect_id,

@@ -47,3 +47,2 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .get_forum_topics_by_id import GetForumTopicsByID
from .get_nearby_chats import GetNearbyChats
from .get_personal_channels import GetPersonalChannels

@@ -57,2 +56,3 @@ from .get_send_as_chats import GetSendAsChats

from .pin_chat_message import PinChatMessage
from .pin_forum_topic import PinForumTopic
from .promote_chat_member import PromoteChatMember

@@ -77,2 +77,3 @@ from .restrict_chat_member import RestrictChatMember

from .unpin_chat_message import UnpinChatMessage
from .unpin_forum_topic import UnpinForumTopic
from .update_chat_notifications import UpdateChatNotifications

@@ -103,2 +104,4 @@ from .update_color import UpdateColor

UnpinChatMessage,
PinForumTopic,
UnpinForumTopic,
UpdateChatNotifications,

@@ -128,3 +131,2 @@ UpdateColor,

ExportFolderLink,
GetNearbyChats,
GetPersonalChannels,

@@ -131,0 +133,0 @@ SetAdministratorTitle,

@@ -21,3 +21,2 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram import raw
from pyrogram import types
from typing import Union

@@ -44,3 +43,3 @@

Returns:
`bool`: On success, a Boolean is returned.
``bool``: On success, True is returned.

@@ -47,0 +46,0 @@ Example:

@@ -21,3 +21,2 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram import raw
from pyrogram import types
from typing import Union

@@ -44,3 +43,3 @@

Returns:
`bool`: On success, a Boolean is returned.
``bool``: On success, True is returned.

@@ -47,0 +46,0 @@ Example:

@@ -21,3 +21,2 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram import raw
from pyrogram import types
from typing import Union

@@ -60,3 +59,3 @@

Returns:
`bool`: On success, a Boolean is returned.
``bool``: On success, True is returned.

@@ -63,0 +62,0 @@ Example:

@@ -32,3 +32,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

force_full: bool = True
) -> Union["types.Chat", "types.ChatPreview"]:
) -> "types.Chat":
"""Get up to date information about a chat.

@@ -52,3 +52,3 @@

Returns:
:obj:`~pyrogram.types.Chat` | :obj:`~pyrogram.types.ChatPreview`: On success, if you've already joined the chat, a chat object is returned,
:obj:`~pyrogram.types.Chat`: On success, if you've already joined the chat, a chat object is returned,
otherwise, a chat preview object is returned.

@@ -75,3 +75,3 @@

if isinstance(r, raw.types.ChatInvite):
return types.ChatPreview._parse(self, r)
return types.Chat._parse_preview(self, r)

@@ -78,0 +78,0 @@ await self.fetch_peers([r.chat])

@@ -19,2 +19,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from typing import Optional
import pyrogram

@@ -27,3 +29,4 @@ from pyrogram import raw

self: "pyrogram.Client",
pinned_only: bool = False
pinned_only: bool = False,
from_archive: Optional[bool] = None
) -> int:

@@ -39,2 +42,5 @@ """Get the total count of your dialogs.

from_archive (``bool``, *optional*):
Pass True to get dialogs count from archive.
Returns:

@@ -51,3 +57,9 @@ ``int``: On success, the dialogs count is returned.

if pinned_only:
return len((await self.invoke(raw.functions.messages.GetPinnedDialogs(folder_id=0))).dialogs)
r = await self.invoke(
raw.functions.messages.GetPinnedDialogs(
folder_id=1 if from_archive else 0
)
)
return len(r.dialogs)
else:

@@ -60,3 +72,4 @@ r = await self.invoke(

limit=1,
hash=0
hash=0,
folder_id=None if from_archive is None else 1 if from_archive else 0
)

@@ -63,0 +76,0 @@ )

@@ -19,3 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from typing import AsyncGenerator
from typing import AsyncGenerator, Optional

@@ -29,3 +29,5 @@ import pyrogram

self: "pyrogram.Client",
limit: int = 0
limit: int = 0,
exclude_pinned: Optional[bool] = None,
from_archive: Optional[bool] = None
) -> AsyncGenerator["types.Dialog", None]:

@@ -41,2 +43,8 @@ """Get a user's dialogs sequentially.

exclude_pinned (``bool``, *optional*):
Exclude pinned dialogs.
from_archive (``bool``, *optional*):
Pass True to get dialogs from archive.
Returns:

@@ -51,2 +59,6 @@ ``Generator``: A generator yielding :obj:`~pyrogram.types.Dialog` objects.

print(dialog.chat.first_name or dialog.chat.title)
# Iterate through dialogs from archive
async for dialog in app.get_dialogs(from_archive=True):
print(dialog.chat.first_name or dialog.chat.title)
"""

@@ -68,3 +80,5 @@ current = 0

limit=limit,
hash=0
hash=0,
exclude_pinned=exclude_pinned,
folder_id=None if from_archive is None else 1 if from_archive else 0
),

@@ -85,6 +99,3 @@ sleep_threshold=60

try:
messages[chat_id] = await types.Message._parse(self, message, users, chats)
except KeyError:
pass
messages[chat_id] = await types.Message._parse(self, message, users, chats)

@@ -97,6 +108,3 @@ dialogs = []

try:
dialogs.append(types.Dialog._parse(self, dialog, messages, users, chats))
except KeyError:
pass
dialogs.append(types.Dialog._parse(self, dialog, messages, users, chats))

@@ -103,0 +111,0 @@ if not dialogs:

@@ -93,3 +93,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

)
except: pass
except: pass # noqa: E701, E722

@@ -105,2 +105,2 @@ for current in topics.values():

return topics_list if is_iterable else topics_list[0] if topics_list else None
return topics if is_iterable else topics[0] if topics else None

@@ -25,2 +25,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram import utils
from pyrogram import types
from pyrogram.file_id import FileType

@@ -37,3 +38,3 @@

video_start_ts: float = None,
) -> bool:
) -> "types.Message":
"""Set a new chat photo or video (H.264/MPEG-4 AVC video, max 5 seconds).

@@ -66,3 +67,3 @@

Returns:
``bool``: True on success.
:obj:`~pyrogram.types.Message`: On success, the sent service message is returned.

@@ -108,3 +109,3 @@ Raises:

if isinstance(peer, raw.types.InputPeerChat):
await self.invoke(
r = await self.invoke(
raw.functions.messages.EditChatPhoto(

@@ -116,3 +117,3 @@ chat_id=peer.chat_id,

elif isinstance(peer, raw.types.InputPeerChannel):
await self.invoke(
r = await self.invoke(
raw.functions.channels.EditPhoto(

@@ -126,2 +127,13 @@ channel=peer,

return True
for i in r.updates:
if isinstance(i, (raw.types.UpdateNewMessage,
raw.types.UpdateNewChannelMessage,
raw.types.UpdateNewScheduledMessage,
raw.types.UpdateBotNewBusinessMessage)):
return await types.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats},
is_scheduled=isinstance(i, raw.types.UpdateNewScheduledMessage),
business_connection_id=getattr(i, "connection_id", None)
)

@@ -20,2 +20,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .on_callback_query import OnCallbackQuery
from .on_chat_boost import OnChatBoost
from .on_chat_join_request import OnChatJoinRequest

@@ -28,6 +29,10 @@ from .on_chat_member_updated import OnChatMemberUpdated

from .on_inline_query import OnInlineQuery
from .on_message_reaction_count import OnMessageReactionCount
from .on_message_reaction import OnMessageReaction
from .on_message import OnMessage
from .on_poll import OnPoll
from .on_pre_checkout_query import OnPreCheckoutQuery
from .on_purchased_paid_media import OnPurchasedPaidMedia
from .on_raw_update import OnRawUpdate
from .on_shipping_query import OnShippingQuery
from .on_user_status import OnUserStatus

@@ -42,6 +47,10 @@ from .on_story import OnStory

OnCallbackQuery,
OnChatBoost,
OnRawUpdate,
OnDisconnect,
OnShippingQuery,
OnUserStatus,
OnInlineQuery,
OnMessageReactionCount,
OnMessageReaction,
OnPoll,

@@ -52,4 +61,5 @@ OnChosenInlineResult,

OnStory,
OnPreCheckoutQuery
OnPreCheckoutQuery,
OnPurchasedPaidMedia
):
pass

@@ -32,2 +32,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .edit_message_text import EditMessageText
from .forward_media_group import ForwardMediaGroup
from .forward_messages import ForwardMessages

@@ -66,2 +67,3 @@ from .get_available_effects import GetAvailableEffects

from .send_paid_media import SendPaidMedia
from .send_paid_reaction import SendPaidReaction
from .send_photo import SendPhoto

@@ -89,2 +91,3 @@ from .send_poll import SendPoll

EditMessageText,
ForwardMediaGroup,
ForwardMessages,

@@ -105,2 +108,3 @@ GetAvailableEffects,

SendPaidMedia,
SendPaidReaction,
SendPhoto,

@@ -107,0 +111,0 @@ SendSticker,

@@ -44,3 +44,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

schedule_date: datetime = None,
show_above_text: bool = None,
show_caption_above_media: bool = None,
) -> List["types.Message"]:

@@ -107,5 +107,4 @@ """Copy a media group by providing one of the message ids.

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.

@@ -163,4 +162,4 @@ Returns:

captions if isinstance(captions, str) and i == 0 else
message.caption if message.caption and message.caption != "None" and not type(
captions) is str else "")
message.caption if message.caption and message.caption != "None" and not
isinstance(captions, str) else "")
)

@@ -184,3 +183,3 @@ )

schedule_date=utils.datetime_to_timestamp(schedule_date),
invert_media=show_above_text
invert_media=show_caption_above_media
),

@@ -187,0 +186,0 @@ sleep_threshold=60

@@ -24,3 +24,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

import pyrogram
from pyrogram import types, enums, utils
from pyrogram import types, enums

@@ -47,2 +47,3 @@ log = logging.getLogger(__name__)

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -142,4 +143,5 @@ "types.InlineKeyboardMarkup",

has_spoiler=has_spoiler,
allow_paid_broadcast=allow_paid_broadcast,
reply_markup=reply_markup,
business_connection_id=business_connection_id
)

@@ -42,3 +42,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

) -> bool:
"""Edit inline animation, audio, document, photo or video messages.
"""Edit inline animation, audio, document, photo or video messages, or to add media to text messages.

@@ -82,2 +82,3 @@ When the inline message is edited, a new file can't be uploaded. Use a previously uploaded file via its file_id

parse_mode = media.parse_mode
caption_entities = media.caption_entities

@@ -236,3 +237,3 @@ is_bytes_io = isinstance(media.media, io.BytesIO)

reply_markup=await reply_markup.write(self) if reply_markup else None,
**await self.parser.parse(caption, parse_mode)
**await utils.parse_text_entities(self, caption, parse_mode, caption_entities)
),

@@ -239,0 +240,0 @@ sleep_threshold=self.sleep_threshold

@@ -19,3 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from typing import Optional
from typing import Optional, List

@@ -35,2 +35,3 @@ import pyrogram

parse_mode: Optional["enums.ParseMode"] = None,
entities: List["types.MessageEntity"] = None,
disable_web_page_preview: bool = None,

@@ -54,2 +55,5 @@ reply_markup: "types.InlineKeyboardMarkup" = None

entities (List of :obj:`~pyrogram.types.MessageEntity`):
List of special entities that appear in message text, which can be specified instead of *parse_mode*.
disable_web_page_preview (``bool``, *optional*):

@@ -88,5 +92,5 @@ Disables link previews for links in this message.

reply_markup=await reply_markup.write(self) if reply_markup else None,
**await self.parser.parse(text, parse_mode)
**await utils.parse_text_entities(self, text, parse_mode, entities)
),
sleep_threshold=self.sleep_threshold
)

@@ -38,3 +38,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

media: "types.InputMedia",
show_above_text: bool = None,
show_caption_above_media: bool = None,
schedule_date: datetime = None,

@@ -44,7 +44,11 @@ reply_markup: "types.InlineKeyboardMarkup" = None,

) -> "types.Message":
"""Edit animation, audio, document, photo or video messages.
"""Edit animation, audio, document, photo or video messages, or to add media to text messages.
If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, the
message type can be changed arbitrarily.
If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise.
Otherwise, the message type can be changed arbitrarily.
.. note::
Business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
.. include:: /_includes/usable-by/users-bots.rst

@@ -64,5 +68,4 @@

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.

@@ -101,2 +104,3 @@ schedule_date (:py:obj:`~datetime.datetime`, *optional*):

parse_mode = media.parse_mode
caption_entities = media.caption_entities

@@ -106,3 +110,3 @@ message, entities = None, None

if caption is not None:
message, entities = (await self.parser.parse(caption, parse_mode)).values()
message, entities = (await utils.parse_text_entities(self, caption, parse_mode, caption_entities)).values()

@@ -289,3 +293,3 @@ if isinstance(media, types.InputMediaPhoto):

id=message_id,
invert_media=show_above_text,
invert_media=show_caption_above_media,
media=media,

@@ -292,0 +296,0 @@ schedule_date=utils.datetime_to_timestamp(schedule_date),

@@ -37,3 +37,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

disable_web_page_preview: bool = None,
show_above_text: bool = None,
show_caption_above_media: bool = None,
schedule_date: datetime = None,

@@ -68,5 +68,4 @@ reply_markup: "types.InlineKeyboardMarkup" = None

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.

@@ -99,3 +98,3 @@ schedule_date (:py:obj:`~datetime.datetime`, *optional*):

no_webpage=disable_web_page_preview or None,
invert_media=show_above_text or None,
invert_media=show_caption_above_media or None,
schedule_date=utils.datetime_to_timestamp(schedule_date),

@@ -102,0 +101,0 @@ reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -38,3 +38,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

hide_captions: bool = None,
protect_content: bool = None
protect_content: bool = None,
allow_paid_broadcast: bool = None
) -> Union["types.Message", List["types.Message"]]:

@@ -79,2 +80,9 @@ """Forward messages of any kind.

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
Returns:

@@ -108,2 +116,3 @@ :obj:`~pyrogram.types.Message` | List of :obj:`~pyrogram.types.Message`: In case *message_ids* was not

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
top_msg_id=message_thread_id

@@ -110,0 +119,0 @@ )

@@ -19,3 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from typing import Union
from typing import Union, Optional

@@ -30,5 +30,6 @@ import pyrogram

chat_id: Union[int, str],
query: str = "",
filter: "enums.MessagesFilter" = enums.MessagesFilter.EMPTY,
from_user: Union[int, str] = None
query: Optional[str] = "",
filter: Optional["enums.MessagesFilter"] = enums.MessagesFilter.EMPTY,
from_user: Optional[Union[int, str]] = None,
message_thread_id: Optional[int] = None
) -> int:

@@ -59,2 +60,6 @@ """Get the count of messages resulting from a search inside a chat.

message_thread_id (``int``, *optional*):
Unique identifier for the target message thread (topic) of the forum.
For supergroups only.
Returns:

@@ -80,2 +85,3 @@ ``int``: On success, the messages count is returned.

),
top_msg_id=message_thread_id,
hash=0

@@ -82,0 +88,0 @@ )

@@ -39,3 +39,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

max_id: int = 0,
from_user: Union[int, str] = None
from_user: Union[int, str] = None,
message_thread_id: Optional[int] = None
) -> List["types.Message"]:

@@ -59,2 +60,3 @@ r = await client.invoke(

),
top_msg_id=message_thread_id,
hash=0

@@ -73,12 +75,13 @@ ),

chat_id: Union[int, str],
query: str = "",
offset: int = 0,
offset_id: int = 0,
min_date: datetime = utils.zero_datetime(),
max_date: datetime = utils.zero_datetime(),
min_id: int = 0,
max_id: int = 0,
filter: "enums.MessagesFilter" = enums.MessagesFilter.EMPTY,
limit: int = 0,
from_user: Union[int, str] = None
query: Optional[str] = "",
offset: Optional[int] = 0,
offset_id: Optional[int] = 0,
min_date: Optional[datetime] = utils.zero_datetime(),
max_date: Optional[datetime] = utils.zero_datetime(),
min_id: Optional[int] = 0,
max_id: Optional[int] = 0,
filter: Optional["enums.MessagesFilter"] = enums.MessagesFilter.EMPTY,
limit: Optional[int] = 0,
from_user: Union[int, str] = None,
message_thread_id: Optional[int] = None
) -> AsyncGenerator["types.Message", None]:

@@ -120,3 +123,3 @@ """Search for text and media messages inside a specific chat.

max_id (``int``, *optional*):
If a positive value was provided, the method will return only messages with IDs less than max_id.
If a positive value was provided, the method will return only messages with IDs less than max_id.

@@ -134,2 +137,6 @@ filter (:obj:`~pyrogram.enums.MessagesFilter`, *optional*):

message_thread_id (``int``, *optional*):
Unique identifier for the target message thread (topic) of the forum.
For supergroups only.
Returns:

@@ -173,3 +180,4 @@ ``Generator``: A generator yielding :obj:`~pyrogram.types.Message` objects.

limit=limit,
from_user=from_user
from_user=from_user,
message_thread_id=message_thread_id
)

@@ -176,0 +184,0 @@

@@ -60,2 +60,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -162,2 +163,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -284,2 +291,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -286,0 +294,0 @@ effect=effect_id,

@@ -58,2 +58,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -155,2 +156,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -277,2 +284,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -279,0 +287,0 @@ effect=effect_id,

@@ -46,4 +46,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

has_spoiler: bool = None,
show_above_text: bool = None,
show_caption_above_media: bool = None,
business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -116,5 +117,4 @@ "types.InlineKeyboardMarkup",

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.

@@ -124,2 +124,8 @@ business_connection_id (``str``, *optional*):

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -145,3 +151,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

silent=disable_notification or None,
invert_media=show_above_text,
invert_media=show_caption_above_media,
reply_to=utils.get_reply_to(

@@ -159,2 +165,3 @@ reply_to_message_id=reply_to_message_id,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -177,3 +184,3 @@ **await utils.parse_text_entities(self, caption, parse_mode, caption_entities)

business_connection_id=getattr(i, "connection_id", None),
reply_to_message=getattr(i, "reply_to_message", None)
raw_reply_to_message=getattr(i, "reply_to_message", None)
)

@@ -50,2 +50,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -120,2 +121,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -158,2 +165,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -160,0 +168,0 @@ effect=effect_id

@@ -45,2 +45,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -113,2 +114,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -153,2 +160,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -155,0 +163,0 @@ message="",

@@ -56,2 +56,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -147,2 +148,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -249,2 +256,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -251,0 +259,0 @@ effect=effect_id,

@@ -45,2 +45,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -109,2 +110,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -146,2 +153,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -148,0 +156,0 @@ effect=effect_id

@@ -58,4 +58,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

protect_content: bool = None,
show_above_text: bool = None,
business_connection_id: str = None
show_caption_above_media: bool = None,
business_connection_id: str = None,
allow_paid_broadcast: bool = None
) -> List["types.Message"]:

@@ -115,5 +116,4 @@ """Send a group of photos or videos as an album.

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.

@@ -123,2 +123,8 @@ business_connection_id (``str``, *optional*):

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
Returns:

@@ -219,3 +225,3 @@ List of :obj:`~pyrogram.types.Message`: On success, a list of the sent messages is returned.

mime_type=self.guess_mime_type(i.media) or "video/mp4",
nosound_video=True, # no-sounds videos cannot be sent in a media group
nosound_video=True,
attributes=[

@@ -228,3 +234,3 @@ raw.types.DocumentAttributeVideo(

),
raw.types.DocumentAttributeFilename(file_name=os.path.basename(i.media))
raw.types.DocumentAttributeFilename(file_name=i.file_name or os.path.basename(i.media))
]

@@ -275,3 +281,3 @@ ),

mime_type=self.guess_mime_type(getattr(i.media, "name", "video.mp4")) or "video/mp4",
nosound_video=True, # no-sounds videos cannot be sent in a media group
nosound_video=True,
attributes=[

@@ -284,3 +290,3 @@ raw.types.DocumentAttributeVideo(

),
raw.types.DocumentAttributeFilename(file_name=getattr(i.media, "name", "video.mp4"))
raw.types.DocumentAttributeFilename(file_name=i.file_name or getattr(i.media, "name", "video.mp4"))
]

@@ -316,3 +322,3 @@ ),

),
raw.types.DocumentAttributeFilename(file_name=os.path.basename(i.media))
raw.types.DocumentAttributeFilename(file_name=i.file_name or os.path.basename(i.media))
]

@@ -365,3 +371,3 @@ ),

),
raw.types.DocumentAttributeFilename(file_name=getattr(i.media, "name", "audio.mp3"))
raw.types.DocumentAttributeFilename(file_name=i.file_name or getattr(i.media, "name", "audio.mp3"))
]

@@ -391,3 +397,3 @@ ),

attributes=[
raw.types.DocumentAttributeFilename(file_name=os.path.basename(i.media))
raw.types.DocumentAttributeFilename(file_name=i.file_name or os.path.basename(i.media))
]

@@ -437,3 +443,3 @@ ),

attributes=[
raw.types.DocumentAttributeFilename(file_name=getattr(i.media, "name", "file.zip"))
raw.types.DocumentAttributeFilename(file_name=i.file_name or getattr(i.media, "name", "file.zip"))
]

@@ -459,3 +465,3 @@ ),

random_id=self.rnd_id(),
**await self.parser.parse(i.caption, i.parse_mode)
**await utils.parse_text_entities(self, i.caption, i.parse_mode, i.caption_entities)
)

@@ -483,3 +489,4 @@ )

noforwards=protect_content,
invert_media=show_above_text,
invert_media=show_caption_above_media,
allow_paid_floodskip=allow_paid_broadcast,
effect=effect_id,

@@ -493,5 +500,6 @@ ),

for i in r.updates:
if getattr(i, "connection_id", None):
conn_id = i.connection_id
for u in r.updates:
if getattr(u, "connection_id", None):
conn_id = u.connection_id
break

@@ -498,0 +506,0 @@

@@ -38,3 +38,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

effect_id: int = None,
show_above_text: bool = None,
show_caption_above_media: bool = None,
reply_to_message_id: int = None,

@@ -49,2 +49,3 @@ reply_to_chat_id: Union[int, str] = None,

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -92,5 +93,4 @@ "types.InlineKeyboardMarkup",

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.

@@ -124,2 +124,8 @@ reply_to_message_id (``int``, *optional*):

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -177,3 +183,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

silent=disable_notification or None,
invert_media=show_above_text or None,
invert_media=show_caption_above_media or None,
reply_to=utils.get_reply_to(

@@ -190,2 +196,3 @@ reply_to_message_id=reply_to_message_id,

schedule_date=utils.datetime_to_timestamp(schedule_date),
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -192,0 +199,0 @@ message=message,

@@ -45,2 +45,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

caption: str = "",
payload: str = None,
parse_mode: Optional["enums.ParseMode"] = None,

@@ -55,3 +56,4 @@ caption_entities: List["types.MessageEntity"] = None,

protect_content: bool = None,
show_above_text: bool = None
show_caption_above_media: bool = None,
business_connection_id: str = None
) -> List["types.Message"]:

@@ -77,2 +79,5 @@ """Send a group or one paid photo/video.

invoice_payload (``str``):
Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*):

@@ -108,6 +113,8 @@ By default, texts are parsed using both Markdown and HTML styles.

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.
business_connection_id (``str``, *optional*):
Unique identifier of the business connection on behalf of which the message will be sent.
Returns:

@@ -255,3 +262,4 @@ :obj:`~pyrogram.types.Message`: On success, the sent message is returned.

stars_amount=stars_amount,
extended_media=multi_media
extended_media=multi_media,
payload=payload
),

@@ -268,8 +276,16 @@ silent=disable_notification or None,

noforwards=protect_content,
invert_media=show_above_text,
invert_media=show_caption_above_media,
**await utils.parse_text_entities(self, caption, parse_mode, caption_entities)
),
sleep_threshold=60,
business_connection_id=business_connection_id
)
conn_id = None
for u in r.updates:
if getattr(u, "connection_id", None):
conn_id = u.connection_id
break
return await utils.parse_messages(

@@ -288,2 +304,3 @@ self,

),
business_connection_id=conn_id
)

@@ -55,2 +55,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -143,2 +144,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -238,2 +245,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -240,0 +248,0 @@ effect=effect_id,

@@ -59,2 +59,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

options_parse_mode: Optional["enums.ParseMode"] = None,
allow_paid_broadcast: bool = None,
reply_markup: Optional[

@@ -177,2 +178,8 @@ Union[

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -252,2 +259,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -254,0 +262,0 @@ effect=effect_id

@@ -95,3 +95,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

story_id=story_id,
reaction=emoji[0] if emoji else None,
reaction=emoji[0] if emoji else raw.types.ReactionEmpty(),
)

@@ -98,0 +98,0 @@ else:

@@ -52,2 +52,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -122,2 +123,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -214,2 +221,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -216,0 +224,0 @@ message="",

@@ -49,2 +49,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -126,2 +127,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -171,2 +178,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -173,0 +181,0 @@ effect=effect_id

@@ -55,2 +55,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -141,2 +142,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -248,2 +255,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -250,0 +258,0 @@ message="",

@@ -62,2 +62,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -173,2 +174,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -297,2 +304,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -299,0 +307,0 @@ effect=effect_id,

@@ -55,2 +55,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -138,2 +139,8 @@ "types.InlineKeyboardMarkup",

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -249,2 +256,3 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

noforwards=protect_content,
allow_paid_floodskip=allow_paid_broadcast,
reply_markup=await reply_markup.write(self) if reply_markup else None,

@@ -251,0 +259,0 @@ effect=effect_id,

@@ -40,3 +40,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

effect_id: int = None,
show_above_text: bool = None,
show_caption_above_media: bool = None,
reply_to_message_id: int = None,

@@ -51,2 +51,3 @@ reply_to_chat_id: Union[int, str] = None,

business_connection_id: str = None,
allow_paid_broadcast: bool = None,
reply_markup: Union[

@@ -91,5 +92,4 @@ "types.InlineKeyboardMarkup",

show_above_text (``bool``, *optional*):
If True, link preview will be shown above the message text.
Otherwise, the link preview will be shown below the message text.
show_caption_above_media (``bool``, *optional*):
Pass True, if the caption must be shown above the message media.

@@ -135,2 +135,8 @@ disable_notification (``bool``, *optional*):

allow_paid_broadcast (``bool``, *optional*):
If True, you will be allowed to send up to 1000 messages per second.
Ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message.
The relevant Stars will be withdrawn from the bot's balance.
For bots only.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):

@@ -193,3 +199,4 @@ Additional interface options. An object for an inline keyboard, custom reply keyboard,

),
invert_media=show_above_text,
invert_media=show_caption_above_media,
allow_paid_floodskip=allow_paid_broadcast,
entities=entities,

@@ -196,0 +203,0 @@ noforwards=protect_content,

@@ -31,3 +31,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

param: str = ""
) -> bool:
) -> "types.Message":
"""Start bot

@@ -34,0 +34,0 @@

@@ -19,11 +19,27 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .check_giftcode import CheckGiftCode
from .apply_gift_code import ApplyGiftCode
from .check_gift_code import CheckGiftCode
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
from .show_star_gift import ShowStarGift
class Payments(
ApplyGiftCode,
CheckGiftCode,
ConvertStarGift,
GetPaymentForm,
SendPaymentForm
GetStarGifts,
GetUserStarGiftsCount,
GetUserStarGifts,
HideStarGift,
SendPaymentForm,
SendStarGift,
ShowStarGift
):
pass

@@ -28,5 +28,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

async def get_payment_form(
self: "pyrogram.Client",
chat_id: Union[int, str],
message_id: Union[int, str],
self: "pyrogram.Client", *,
chat_id: Union[int, str] = None,
message_id: int = None,
invoice_link: str = None
) -> "types.PaymentForm":

@@ -40,7 +41,8 @@ """Get information about a invoice or paid media.

Unique identifier (int) or username (str) of the target chat.
Unique identifier for the target chat in form of a *t.me/joinchat/* link, identifier (int) or username
of the target channel/supergroup (in the format @username).
message_id (``int`` | ``str``):
message_id (``int``):
Pass a message identifier or to get the invoice from message.
invoice_link (``str``):
Pass a invoice link in form of a *t.me/$...* link or slug itself to get the payment form from link.

@@ -55,10 +57,13 @@

# get payment form from message
app.get_payment_form(chat_id, 123)
app.get_payment_form(chat_id=chat_id, message_id=123)
# get payment form from link
app.get_payment_form(chat_id, "https://t.me/$xvbzUtt5sUlJCAAATqZrWRy9Yzk")
app.get_payment_form(invoice_link="https://t.me/$xvbzUtt5sUlJCAAATqZrWRy9Yzk")
"""
if not any((all((chat_id, message_id)), invoice_link)):
raise ValueError("You should pass at least one parameter to this method.")
invoice = None
if isinstance(message_id, int):
if message_id:
invoice = raw.types.InputInvoiceMessage(

@@ -68,4 +73,4 @@ peer=await self.resolve_peer(chat_id),

)
elif isinstance(message_id, str):
match = re.match(r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/\$)([\w-]+)$", message_id)
elif invoice_link:
match = re.match(r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/\$)([\w-]+)$", invoice_link)

@@ -75,3 +80,3 @@ if match:

else:
slug = message_id
slug = invoice_link

@@ -78,0 +83,0 @@ invoice = raw.types.InputInvoiceSlug(

@@ -20,6 +20,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

import re
from typing import Union
from typing import Union, List
import pyrogram
from pyrogram import raw
from pyrogram import raw, types

@@ -29,6 +29,7 @@

async def send_payment_form(
self: "pyrogram.Client",
chat_id: Union[int, str],
message_id: Union[int, str],
) -> bool:
self: "pyrogram.Client", *,
chat_id: Union[int, str] = None,
message_id: int = None,
invoice_link: str = None
) -> List[Union["types.Photo", "types.Video"]]:
"""Pay an invoice.

@@ -45,11 +46,12 @@

Unique identifier (int) or username (str) of the target chat.
Unique identifier for the target chat in form of a *t.me/joinchat/* link, identifier (int) or username
of the target channel/supergroup (in the format @username).
message_id (``int`` | ``str``):
message_id (``int``):
Pass a message identifier or to get the invoice from message.
Pass a invoice link in form of a *t.me/$...* link or slug itself to get the payment form from link.
invoice_link (``str``):
Pass a invoice link in form of a *t.me/$...* link or slug itself to pay this invoice.
Returns:
``bool``: On success, True is returned.
List of :obj:`~pyrogram.types.Photo` | :obj:`~pyrogram.types.Video`: On success, the list of bought photos and videos is returned.

@@ -60,11 +62,14 @@ Example:

# Pay invoice from message
app.send_payment_form(chat_id, 123)
app.send_payment_form(chat_id=chat_id, message_id=123)
# Pay invoice form from link
# Chat id can be None
app.send_payment_form(chat_id, "https://t.me/$xvbzUtt5sUlJCAAATqZrWRy9Yzk")
app.send_payment_form(invoice_link="https://t.me/$xvbzUtt5sUlJCAAATqZrWRy9Yzk")
"""
if not any((all((chat_id, message_id)), invoice_link)):
raise ValueError("You should pass at least one parameter to this method.")
form = None
invoice = None
if isinstance(message_id, int):
if message_id:
invoice = raw.types.InputInvoiceMessage(

@@ -74,4 +79,4 @@ peer=await self.resolve_peer(chat_id),

)
elif isinstance(message_id, str):
match = re.match(r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/\$)([\w-]+)$", message_id)
elif invoice_link:
match = re.match(r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/\$)([\w-]+)$", invoice_link)

@@ -81,3 +86,3 @@ if match:

else:
slug = message_id
slug = invoice_link

@@ -88,6 +93,6 @@ invoice = raw.types.InputInvoiceSlug(

form = await self.get_payment_form(chat_id=chat_id, message_id=message_id)
form = await self.get_payment_form(chat_id=chat_id, message_id=message_id, invoice_link=invoice_link)
# if form.invoice.currency == "XTR":
await self.invoke(
r = await self.invoke(
raw.functions.payments.SendStarsForm(

@@ -108,2 +113,28 @@ form_id=form.id,

return True
medias = []
if isinstance(r, raw.types.payments.PaymentResult):
for i in r.updates.updates:
if isinstance(i, raw.types.UpdateMessageExtendedMedia):
for ext_media in i.extended_media:
media = ext_media.media
if isinstance(media, raw.types.MessageMediaPhoto):
medias.append(types.Photo._parse(self, media.photo))
elif isinstance(media, raw.types.MessageMediaDocument):
doc = media.document
attributes = {type(i): i for i in doc.attributes}
file_name = getattr(
attributes.get(
raw.types.DocumentAttributeFilename, None
), "file_name", None
)
video_attributes = attributes[raw.types.DocumentAttributeVideo]
medias.append(types.Video._parse(self, doc, video_attributes, file_name))
return types.List(medias)
# elif isinstance(r, raw.types.payments.PaymentVerificationNeeded):

@@ -19,3 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .can_send_story import CanSendStory
from .can_post_stories import CanPostStories
from .copy_story import CopyStory

@@ -28,14 +28,16 @@ from .delete_stories import DeleteStories

from .get_all_stories import GetAllStories
from .get_archived_stories import GetArchivedStories
from .get_chat_stories import GetChatStories
from .get_pinned_stories import GetPinnedStories
from .get_stories import GetStories
from .get_stories_archive import GetStoriesArchive
from .hide_stories import HideStories
from .hide_chat_stories import HideChatStories
from .pin_chat_stories import PinChatStories
from .read_chat_stories import ReadChatStories
from .send_story import SendStory
from .show_chat_stories import ShowChatStories
from .unpin_chat_stories import UnpinChatStories
from .view_stories import ViewStories
from .pin_stories import PinStories
from .read_stories import ReadStories
from .send_story import SendStory
class Stories(
CanSendStory,
CanPostStories,
CopyStory,

@@ -48,12 +50,14 @@ DeleteStories,

GetAllStories,
GetArchivedStories,
GetChatStories,
GetPinnedStories,
GetStories,
GetStoriesArchive,
HideStories,
HideChatStories,
PinChatStories,
ReadChatStories,
SendStory,
ShowChatStories,
UnpinChatStories,
ViewStories,
PinStories,
ReadStories,
SendStory,
):
pass

@@ -32,3 +32,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

) -> List[int]:
"""Delete stories.
"""Delete posted stories.

@@ -41,3 +41,2 @@ .. include:: /_includes/usable-by/users.rst

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).

@@ -48,3 +47,3 @@ story_ids (``int`` | Iterable of ``int``, *optional*):

Returns:
List of ``int``: List of deleted stories IDs
List of ``int``: List of deleted stories IDs.

@@ -51,0 +50,0 @@ Example:

@@ -29,3 +29,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

story_id: int,
privacy: "enums.StoriesPrivacyRules" = None,
privacy: "enums.StoriesPrivacyRules" = enums.StoriesPrivacyRules.PUBLIC,
allowed_users: List[Union[int, str]] = None,

@@ -48,3 +48,3 @@ disallowed_users: List[Union[int, str]] = None,

privacy (:obj:`~pyrogram.enums.StoriesPrivacyRules`, *optional*):
Story privacy.
Story privacy. Defaults to :obj:`~pyrogram.enums.StoriesPrivacyRules.PUBLIC`.

@@ -81,37 +81,37 @@ allowed_users (List of ``int`` | ``str``, *optional*):

if privacy:
if privacy == enums.StoriesPrivacyRules.PUBLIC:
privacy_rules.append(raw.types.InputPrivacyValueAllowAll())
if disallowed_users:
users = [await self.resolve_peer(user_id) for user_id in disallowed_users]
privacy_rules.append(raw.types.InputPrivacyValueDisallowUsers(users=users))
elif privacy == enums.StoriesPrivacyRules.CONTACTS:
privacy_rules = [raw.types.InputPrivacyValueAllowContacts()]
if disallowed_users:
users = [await self.resolve_peer(user_id) for user_id in disallowed_users]
privacy_rules.append(raw.types.InputPrivacyValueDisallowUsers(users=users))
elif privacy == enums.StoriesPrivacyRules.CLOSE_FRIENDS:
privacy_rules = [raw.types.InputPrivacyValueAllowCloseFriends()]
if allowed_users:
users = [await self.resolve_peer(user_id) for user_id in allowed_users]
privacy_rules.append(raw.types.InputPrivacyValueAllowUsers(users=users))
elif privacy == enums.StoriesPrivacyRules.SELECTED_USERS:
_allowed_users = []
_allowed_chats = []
if not privacy:
privacy = enums.StoriesPrivacyRules.PUBLIC
for user in allowed_users:
peer = await self.resolve_peer(user)
if isinstance(peer, raw.types.InputPeerUser):
_allowed_users.append(peer)
elif isinstance(peer, (raw.types.InputPeerChat, raw.types.InputPeerChannel)):
_allowed_chats.append(peer)
if _allowed_users:
privacy_rules.append(raw.types.InputPrivacyValueAllowUsers(users=_allowed_users))
if _allowed_chats:
privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=_allowed_chats))
else:
if privacy == enums.StoriesPrivacyRules.PUBLIC:
privacy_rules.append(raw.types.InputPrivacyValueAllowAll())
if disallowed_users:
users = [await self.resolve_peer(user_id) for user_id in disallowed_users]
privacy_rules.append(raw.types.InputPrivacyValueDisallowUsers(users=users))
elif privacy == enums.StoriesPrivacyRules.CONTACTS:
privacy_rules = [raw.types.InputPrivacyValueAllowContacts()]
if disallowed_users:
users = [await self.resolve_peer(user_id) for user_id in disallowed_users]
privacy_rules.append(raw.types.InputPrivacyValueDisallowUsers(users=users))
elif privacy == enums.StoriesPrivacyRules.CLOSE_FRIENDS:
privacy_rules = [raw.types.InputPrivacyValueAllowCloseFriends()]
if allowed_users:
users = [await self.resolve_peer(user_id) for user_id in allowed_users]
privacy_rules.append(raw.types.InputPrivacyValueAllowUsers(users=users))
elif privacy == enums.StoriesPrivacyRules.SELECTED_USERS:
_allowed_users = []
_allowed_chats = []
for user in allowed_users:
peer = await self.resolve_peer(user)
if isinstance(peer, raw.types.InputPeerUser):
_allowed_users.append(peer)
elif isinstance(peer, (raw.types.InputPeerChat, raw.types.InputPeerChannel)):
_allowed_chats.append(peer)
if _allowed_users:
privacy_rules.append(raw.types.InputPrivacyValueAllowUsers(users=_allowed_users))
if _allowed_chats:
privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=_allowed_chats))
r = await self.invoke(

@@ -118,0 +118,0 @@ raw.functions.stories.EditStory(

@@ -37,3 +37,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

) -> Optional["types.Message"]:
"""Send story.
"""Forward story.

@@ -40,0 +40,0 @@ .. include:: /_includes/usable-by/users.rst

@@ -33,6 +33,20 @@ # Pyrogram - Telegram MTProto API Client Library for Python

) -> AsyncGenerator["types.Story", None]:
"""Get all active stories.
"""Get all active or hidden stories that displayed on the action bar on the homescreen.
.. include:: /_includes/usable-by/users.rst
Parameters
next (``bool``, *optional*):
If next and state are both set, uses the passed state to paginate to the next results.
If neither state nor next are set, fetches the initial page.
If state is set and next is not set, check for changes in the active/hidden peerset.
hidden (``bool``, *optional*):
If set, fetches the hidden active story list, otherwise fetches the active story list.
state (``str``, *optional*):
If next and state are both set, uses the passed state to paginate to the next results.
If neither state nor next are set, fetches the initial page.
If state is set and next is not set, check for changes in the active/hidden peerset.
Returns:

@@ -47,5 +61,2 @@ ``Generator``: On success, a generator yielding :obj:`~pyrogram.types.Story` objects is returned.

print(story)
Raises:
ValueError: In case of invalid arguments.
"""

@@ -52,0 +63,0 @@

@@ -47,3 +47,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

# Get all non expired stories from spesific chat
# Get all non expired stories from specific chat
async for story in app.get_chat_stories(chat_id):

@@ -50,0 +50,0 @@ print(story)

@@ -50,4 +50,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

Yields:
:obj:`~pyrogram.types.Story` objects.
Returns:
``Generator``: On success, a generator yielding :obj:`~pyrogram.types.Story` objects is returned.

@@ -54,0 +54,0 @@ Example:

@@ -19,3 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from typing import Union, Iterable
from typing import Union, Iterable, List

@@ -32,3 +32,3 @@ import pyrogram

story_ids: Union[int, Iterable[int]],
) -> "types.Stories":
) -> Union["types.Story", List["types.Story"]] :
"""Get one or more stories from a chat by using stories identifiers.

@@ -44,3 +44,3 @@

story_ids (``int`` | Iterable of ``int``, *optional*):
story_ids (``int`` | Iterable of ``int``):
Pass a single story identifier or an iterable of story ids (as integers) to get the content of the

@@ -47,0 +47,0 @@ story themselves.

@@ -51,8 +51,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

) -> "types.Story":
"""Send new story.
"""Post new story.
.. include:: /_includes/usable-by/users.rst
Note: You must pass one of following parameters *animation*, *photo*, *video*
Parameters:

@@ -59,0 +57,0 @@ chat_id (``int`` | ``str``):

@@ -29,2 +29,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .set_emoji_status import SetEmojiStatus
from .set_personal_channel import SetPersonalChannel
from .set_profile_photo import SetProfilePhoto

@@ -34,3 +35,2 @@ from .set_username import SetUsername

from .update_birthday import UpdateBirthday
from .update_personal_channel import UpdatePersonalChannel
from .update_profile import UpdateProfile

@@ -45,2 +45,3 @@ from .update_status import UpdateStatus

GetChatPhotos,
SetPersonalChannel,
SetProfilePhoto,

@@ -54,3 +55,2 @@ DeleteProfilePhotos,

UpdateBirthday,
UpdatePersonalChannel,
UpdateProfile,

@@ -57,0 +57,0 @@ UpdateStatus,

@@ -19,2 +19,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from datetime import datetime
from typing import Union, AsyncGenerator, Optional

@@ -31,3 +32,8 @@

limit: int = 0,
) -> AsyncGenerator["types.Photo", None]:
) -> Optional[
Union[
AsyncGenerator["types.Photo", None],
AsyncGenerator["types.Animation", None]
]
]:
"""Get a chat or a user profile photos sequentially.

@@ -48,3 +54,3 @@

Returns:
``Generator``: A generator yielding :obj:`~pyrogram.types.Photo` objects.
``Generator``: A generator yielding :obj:`~pyrogram.types.Photo` | :obj:`~pyrogram.types.Animation` objects.

@@ -66,36 +72,47 @@ Example:

current = types.Photo._parse(self, r.full_chat.chat_photo) or []
current = types.Animation._parse_chat_animation(
self,
r.full_chat.chat_photo,
f"photo_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.mp4"
) or types.Photo._parse(self, r.full_chat.chat_photo) or []
r = await utils.parse_messages(
self,
await self.invoke(
raw.functions.messages.Search(
peer=peer_id,
q="",
filter=raw.types.InputMessagesFilterChatPhotos(),
min_date=0,
max_date=0,
offset_id=0,
add_offset=0,
limit=limit,
max_id=0,
min_id=0,
hash=0
if current:
current = [current]
if not self.me.is_bot:
r = await utils.parse_messages(
self,
await self.invoke(
raw.functions.messages.Search(
peer=peer_id,
q="",
filter=raw.types.InputMessagesFilterChatPhotos(),
min_date=0,
max_date=0,
offset_id=0,
add_offset=0,
limit=limit,
max_id=0,
min_id=0,
hash=0
)
)
)
)
extra = [message.new_chat_photo for message in r]
extra = [message.new_chat_photo for message in r]
if extra:
if current:
photos = ([current] + extra) if current.file_id != extra[0].file_id else extra
if extra:
if current:
photos = (current + extra) if current[0].file_id != extra[0].file_id else extra
else:
photos = extra
else:
photos = extra
else:
if current:
photos = [current]
else:
photos = []
if current:
photos = current
else:
photos = []
if not photos:
return
current = 0

@@ -126,3 +143,10 @@

photos = [types.Photo._parse(self, photo) for photo in r.photos]
photos = [
types.Animation._parse_chat_animation(
self,
photo,
f"photo_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.mp4"
) or types.Photo._parse(self, photo)
for photo in r.photos
]

@@ -129,0 +153,0 @@ if not photos:

@@ -25,2 +25,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from os import urandom
from typing import Optional

@@ -41,3 +42,8 @@ import pyrogram

def __init__(self, client: "pyrogram.Client", dc_id: int, test_mode: bool):
def __init__(
self,
client: "pyrogram.Client",
dc_id: int,
test_mode: bool
):
self.dc_id = dc_id

@@ -47,4 +53,6 @@ self.test_mode = test_mode

self.proxy = client.proxy
self.connection_factory = client.connection_factory
self.protocol_factory = client.protocol_factory
self.connection = None
self.connection: Optional[Connection] = None

@@ -82,3 +90,10 @@ @staticmethod

while True:
self.connection = Connection(self.dc_id, self.test_mode, self.ipv6, self.proxy)
self.connection = self.connection_factory(
dc_id=self.dc_id,
test_mode=self.test_mode,
ipv6=self.ipv6,
proxy=self.proxy,
media=False,
protocol_factory=self.protocol_factory
)

@@ -85,0 +100,0 @@ try:

@@ -26,2 +26,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from io import BytesIO
from typing import Optional

@@ -34,3 +35,3 @@ import pyrogram

RPCError, InternalServerError, AuthKeyDuplicated, FloodWait, FloodPremiumWait, ServiceUnavailable, BadMsgNotification,
SecurityCheckMismatch
SecurityCheckMismatch, Unauthorized
)

@@ -87,3 +88,3 @@ from pyrogram.raw.all import layer

self.connection = None
self.connection: Optional[Connection] = None

@@ -114,8 +115,9 @@ self.auth_key_id = sha1(auth_key).digest()[-8:]

while True:
self.connection = Connection(
self.dc_id,
self.test_mode,
self.client.ipv6,
self.client.proxy,
self.is_media
self.connection = self.client.connection_factory(
dc_id=self.dc_id,
test_mode=self.test_mode,
ipv6=self.client.ipv6,
proxy=self.client.proxy,
media=self.is_media,
protocol_factory=self.client.protocol_factory
)

@@ -154,3 +156,3 @@

log.info("System: %s (%s)", self.client.system_version, self.client.lang_code)
except AuthKeyDuplicated as e:
except (AuthKeyDuplicated, Unauthorized) as e:
await self.stop()

@@ -200,10 +202,17 @@ raise e

async def handle_packet(self, packet):
data = await self.loop.run_in_executor(
pyrogram.crypto_executor,
mtproto.unpack,
BytesIO(packet),
self.session_id,
self.auth_key,
self.auth_key_id
)
try:
data = await self.loop.run_in_executor(
pyrogram.crypto_executor,
mtproto.unpack,
BytesIO(packet),
self.session_id,
self.auth_key,
self.auth_key_id
)
except ValueError as e:
if self.auto_restart_on_fail:
log.debug(e)
self.loop.create_task(self.restart())
return
raise e

@@ -323,5 +332,5 @@ messages = (

if error_code == 404:
raise Exception(
"Auth key not found in the system. You must delete your session file"
"and log in again with your phone number or bot token"
raise Unauthorized(
"Auth key not found in the system. You must delete your session file "
"and log in again with your phone number or bot token."
)

@@ -328,0 +337,0 @@

@@ -86,2 +86,8 @@ # Pyrogram - Telegram MTProto API Client Library for Python

if version == 5:
with self.conn:
self.conn.execute("CREATE INDEX idx_usernames_id ON usernames (id);")
version += 1
self.version(version)

@@ -88,0 +94,0 @@

@@ -73,2 +73,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

CREATE INDEX idx_peers_phone_number ON peers (phone_number);
CREATE INDEX idx_usernames_id ON usernames (id);
CREATE INDEX idx_usernames_username ON usernames (username);

@@ -109,3 +110,3 @@

class SQLiteStorage(Storage):
VERSION = 5
VERSION = 6
USERNAME_TTL = 8 * 60 * 60

@@ -145,26 +146,18 @@

async def update_peers(self, peers: List[Tuple[int, int, str, List[str], str]]):
peers_data = []
usernames_data = []
ids_to_delete = []
for id, access_hash, type, usernames, phone_number in peers:
ids_to_delete.append((id,))
peers_data.append((id, access_hash, type, phone_number))
if usernames:
usernames_data.extend([(id, username) for username in usernames])
async def update_peers(self, peers: List[Tuple[int, int, str, str]]):
self.conn.executemany(
"REPLACE INTO peers (id, access_hash, type, phone_number) VALUES (?, ?, ?, ?)",
peers_data)
peers
)
async def update_usernames(self, usernames: List[Tuple[int, List[str]]]):
self.conn.executemany(
"DELETE FROM usernames WHERE id = ?",
ids_to_delete)
[(id,) for id, _ in usernames]
)
if usernames_data:
self.conn.executemany(
"REPLACE INTO usernames (id, username) VALUES (?, ?)",
usernames_data)
self.conn.executemany(
"REPLACE INTO usernames (id, username) VALUES (?, ?)",
[(id, username) for id, usernames in usernames for username in usernames]
)

@@ -178,14 +171,13 @@ async def update_state(self, value: Tuple[int, int, int, int, int] = object):

else:
with self.conn:
if isinstance(value, int):
self.conn.execute(
"DELETE FROM update_state WHERE id = ?",
(value,)
)
else:
self.conn.execute(
"REPLACE INTO update_state (id, pts, qts, date, seq)"
"VALUES (?, ?, ?, ?, ?)",
value
)
if isinstance(value, int):
self.conn.execute(
"DELETE FROM update_state WHERE id = ?",
(value,)
)
else:
self.conn.execute(
"REPLACE INTO update_state (id, pts, qts, date, seq)"
"VALUES (?, ?, ?, ?, ?)",
value
)

@@ -192,0 +184,0 @@ async def get_peer_by_id(self, peer_id: int):

@@ -60,7 +60,7 @@ # Pyrogram - Telegram MTProto API Client Library for Python

async def delete(self):
"""Deletes the storage."""
"""Deletes the storage file."""
raise NotImplementedError
@abstractmethod
async def update_peers(self, peers: List[Tuple[int, int, str, List[str], str]]):
async def update_peers(self, peers: List[Tuple[int, int, str, str]]):
"""

@@ -70,3 +70,4 @@ Update the peers table with the provided information.

Parameters:
peers (``List[Tuple[int, int, str, List[str], str]]``): A list of tuples containing the
peers (``List[Tuple[int, int, str, str]]``):
A list of tuples containing the
information of the peers to be updated. Each tuple must contain the following

@@ -77,3 +78,2 @@ information:

- ``str``: The peer type (user, chat or channel).
- List of ``str``: The peer username (if any).
- ``str``: The peer phone number (if any).

@@ -84,2 +84,17 @@ """

@abstractmethod
async def update_usernames(self, usernames: List[Tuple[int, List[str]]]):
"""
Update the usernames table with the provided information.
Parameters:
usernames (``List[Tuple[int, List[str]]]``):
A list of tuples containing the
information of the usernames to be updated. Each tuple must contain the following
information:
- ``int``: The peer id.
- List of ``str``: The peer username (if any).
"""
raise NotImplementedError
@abstractmethod
async def update_state(self, update_state: Tuple[int, int, int, int, int] = object):

@@ -89,3 +104,4 @@ """Get or set the update state of the current session.

Parameters:
update_state (``Tuple[int, int, int, int, int]``): A tuple containing the update state to set.
update_state (``Tuple[int, int, int, int, int]``):
A tuple containing the update state to set.
Tuple must contain the following information:

@@ -92,0 +108,0 @@ - ``int``: The id of the entity.

@@ -30,2 +30,1 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .user_and_chats import *
from .pyromod import *

@@ -30,2 +30,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .callback_query import CallbackQuery
from .chat_boost_updated import ChatBoostUpdated
from .force_reply import ForceReply

@@ -42,4 +43,7 @@ from .game_high_score import GameHighScore

from .menu_button_web_app import MenuButtonWebApp
from .message_reaction_count_updated import MessageReactionCountUpdated
from .message_reaction_updated import MessageReactionUpdated
from .order_info import OrderInfo
from .pre_checkout_query import PreCheckoutQuery
from .purchased_paid_media import PurchasedPaidMedia
from .reply_keyboard_markup import ReplyKeyboardMarkup

@@ -53,2 +57,4 @@ from .reply_keyboard_remove import ReplyKeyboardRemove

from .sent_web_app_message import SentWebAppMessage
from .shipping_option import ShippingOption
from .shipping_query import ShippingQuery
from .shipping_address import ShippingAddress

@@ -60,2 +66,3 @@ from .web_app_info import WebAppInfo

"CallbackQuery",
"ChatBoostUpdated",
"ForceReply",

@@ -88,7 +95,12 @@ "GameHighScore",

"MenuButtonWebApp",
"MessageReactionCountUpdated",
"MessageReactionUpdated",
"OrderInfo",
"PreCheckoutQuery",
"PurchasedPaidMedia",
"MenuButtonDefault",
"SentWebAppMessage",
"ShippingOption",
"ShippingQuery",
"ShippingAddress"
]

@@ -22,4 +22,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

import pyrogram
from pyrogram import raw, enums
from pyrogram import types
from pyrogram import raw, enums, types
from pyrogram.errors import ChannelPrivate
from ..object import Object

@@ -91,3 +91,3 @@ from ..update import Update

@staticmethod
async def _parse(client: "pyrogram.Client", callback_query, users) -> "CallbackQuery":
async def _parse(client: "pyrogram.Client", callback_query, users, chats: dict = {}) -> "CallbackQuery":
message = None

@@ -103,13 +103,40 @@ inline_message_id = None

if not message:
message = await client.get_messages(chat_id, message_id)
try:
message = await client.get_messages(
chat_id=chat_id,
message_ids=message_id
)
except ChannelPrivate:
channel = chats.get(utils.get_raw_peer_id(callback_query.peer), None)
if channel:
message = types.Message(
id=message_id,
chat=types.Chat._parse_chat(
client,
channel
)
)
elif isinstance(callback_query, raw.types.UpdateInlineBotCallbackQuery):
inline_message_id = utils.pack_inline_message_id(callback_query.msg_id)
elif isinstance(callback_query, raw.types.UpdateBusinessBotCallbackQuery):
message = await types.Message._parse(
client,
callback_query.message,
users,
chats,
is_scheduled=False,
replies=0,
business_connection_id=callback_query.connection_id,
raw_reply_to_message=getattr(callback_query, "reply_to_message", None)
)
# Try to decode callback query data into string. If that fails, fallback to bytes instead of decoding by
# ignoring/replacing errors, this way, button clicks will still work.
try:
data = callback_query.data.decode()
except (UnicodeDecodeError, AttributeError):
data = callback_query.data
data = getattr(callback_query, "data", None)
if data:
try:
data = data.decode()
except (UnicodeDecodeError, AttributeError):
data = data
return CallbackQuery(

@@ -122,3 +149,3 @@ id=str(callback_query.query_id),

data=data,
game_short_name=callback_query.game_short_name,
game_short_name=getattr(callback_query, "game_short_name", None),
client=client

@@ -125,0 +152,0 @@ )

@@ -75,2 +75,13 @@ # Pyrogram - Telegram MTProto API Client Library for Python

A button that asks for the 2-step verification password of the current user and then sends a callback query to a bot Data to be sent to the bot via a callback query.
pay (``bool``, *optional*):
Pass True, to send a Pay button.
Substrings `⭐` and `XTR` in the buttons's text will be replaced with a Telegram Star icon.
Available in :meth:`~pyrogram.Client.send_invoice`.
**NOTE**: This type of button **must** always be the first button in the first row and can only be used in invoice messages.
copy_text (``str``, *optional*):
A button that copies specified text to clipboard.
Limited to 256 character.
"""

@@ -89,3 +100,5 @@

callback_game: Optional["types.CallbackGame"] = None,
requires_password: Optional[bool] = None
requires_password: Optional[bool] = None,
pay: bool = None,
copy_text: str = None
):

@@ -104,3 +117,4 @@ super().__init__()

self.requires_password = requires_password
# self.pay = pay
self.pay = pay
self.copy_text = copy_text

@@ -169,5 +183,12 @@ @staticmethod

return InlineKeyboardButton(
text=b.text
text=b.text,
pay=True
)
if isinstance(b, raw.types.KeyboardButtonCopy):
return InlineKeyboardButton(
text=b.text,
copy_text=b.copy_text
)
async def write(self, client: "pyrogram.Client"):

@@ -225,1 +246,10 @@ if self.callback_data is not None:

)
if self.pay is not None:
return raw.types.KeyboardButtonBuy(text=self.text)
if self.copy_text is not None:
return raw.types.KeyboardButtonCopy(
text=self.text,
copy_text=self.copy_text
)

@@ -44,3 +44,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

invoice_payload (``str``):
Bot specified invoice payload.
Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.

@@ -47,0 +47,0 @@ shipping_option_id (``str``, *optional*):

@@ -19,2 +19,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram import raw
from ..object import Object

@@ -65,1 +67,17 @@

self.post_code = post_code
@staticmethod
def _parse(
shipping_address: "raw.types.PostAddress",
) -> "ShippingAddress":
if not shipping_address:
return None
return ShippingAddress(
country_code=shipping_address.country_iso2,
state=shipping_address.state,
city=shipping_address.city,
street_line1=shipping_address.street_line1,
street_line2=shipping_address.street_line2,
post_code=shipping_address.post_code
)

@@ -19,8 +19,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from base64 import b64encode
from struct import pack
import pyrogram
from pyrogram import raw
from pyrogram import types
from pyrogram import utils
from ..object import Object

@@ -77,15 +75,2 @@ from ..update import Update

def _parse(client, chosen_inline_result: raw.types.UpdateBotInlineSend, users) -> "ChosenInlineResult":
inline_message_id = None
if isinstance(chosen_inline_result.msg_id, raw.types.InputBotInlineMessageID):
inline_message_id = b64encode(
pack(
"<iqq",
chosen_inline_result.msg_id.dc_id,
chosen_inline_result.msg_id.id,
chosen_inline_result.msg_id.access_hash
),
b"-_"
).decode().rstrip("=")
return ChosenInlineResult(

@@ -100,3 +85,5 @@ result_id=str(chosen_inline_result.id),

) if chosen_inline_result.geo else None,
inline_message_id=inline_message_id
inline_message_id=utils.pack_inline_message_id(
chosen_inline_result.msg_id
) if getattr(chosen_inline_result, "msg_id", None) else None
)

@@ -64,2 +64,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

Title of the audio
file_name (``str``, *optional*):
File name of the audio sent.
Defaults to file's path basename.
"""

@@ -76,3 +80,4 @@

performer: str = "",
title: str = ""
title: str = "",
file_name: str = None
):

@@ -85,1 +90,2 @@ super().__init__(media, caption, parse_mode, caption_entities)

self.title = title
self.file_name = file_name

@@ -53,2 +53,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

List of special entities that appear in the caption, which can be specified instead of *parse_mode*.
file_name (``str``, *optional*):
File name of the document sent.
Defaults to file's path basename.
"""

@@ -62,3 +66,4 @@

parse_mode: Optional["enums.ParseMode"] = None,
caption_entities: List[MessageEntity] = None
caption_entities: List[MessageEntity] = None,
file_name: str = None
):

@@ -68,1 +73,2 @@ super().__init__(media, caption, parse_mode, caption_entities)

self.thumb = thumb
self.file_name = file_name

@@ -64,2 +64,6 @@ # Pyrogram - Telegram MTProto API Client Library for Python

file_name (``str``, *optional*):
File name of the video sent.
Defaults to file's path basename.
supports_streaming (``bool``, *optional*):

@@ -86,2 +90,3 @@ Pass True, if the uploaded video is suitable for streaming.

duration: int = 0,
file_name: str = None,
supports_streaming: bool = True,

@@ -97,4 +102,5 @@ has_spoiler: bool = None,

self.duration = duration
self.file_name = file_name
self.supports_streaming = supports_streaming
self.has_spoiler = has_spoiler
self.no_sound = no_sound

@@ -24,3 +24,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .business_message import BusinessMessage
from .chat_boost import ChatBoost
from .checked_gift_code import CheckedGiftCode
from .contact_registered import ContactRegistered
from .contact import Contact

@@ -40,3 +42,5 @@ from .dice import Dice

from .giveaway import Giveaway
from .giveaway_result import GiveawayResult
from .giveaway_completed import GiveawayCompleted
from .giveaway_created import GiveawayCreated
from .giveaway_winners import GiveawayWinners
from .location import Location

@@ -54,2 +58,5 @@ from .message import Message

from .reaction import Reaction
from .refunded_payment import RefundedPayment
from .screenshot_taken import ScreenshotTaken
from .star_gift import StarGift
from .sticker import Sticker

@@ -66,2 +73,3 @@ from .story import Story

from .web_page import WebPage
from .write_access_allowed import WriteAccessAllowed

@@ -74,3 +82,5 @@ __all__ = [

"BusinessMessage",
"ChatBoost",
"CheckedGiftCode",
"ContactRegistered",
"Contact",

@@ -90,3 +100,5 @@ "Dice",

"Invoice",
"GiveawayResult",
"GiveawayCompleted",
"GiveawayCreated",
"GiveawayWinners",
"Location",

@@ -104,2 +116,5 @@ "Message",

"Reaction",
"RefundedPayment",
"ScreenshotTaken",
"StarGift",
"Sticker",

@@ -116,2 +131,3 @@ "Story",

"WebPage",
"WriteAccessAllowed",
]

@@ -20,3 +20,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from datetime import datetime
from typing import List
from typing import List, Optional

@@ -26,3 +26,3 @@ import pyrogram

from pyrogram import types
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType, ThumbnailSource
from ..object import Object

@@ -124,1 +124,48 @@

)
@staticmethod
def _parse_chat_animation(
client,
video: "raw.types.Photo",
file_name: str
) -> Optional["Animation"]:
if isinstance(video, raw.types.Photo):
if not video.video_sizes:
return None
videos: List[raw.types.VideoSize] = []
for v in video.video_sizes:
if isinstance(v, raw.types.VideoSize):
videos.append(v)
videos.sort(key=lambda v: v.size)
main = videos[-1]
return Animation(
file_id=FileId(
file_type=FileType.PHOTO,
dc_id=video.dc_id,
media_id=video.id,
access_hash=video.access_hash,
file_reference=video.file_reference,
thumbnail_source=ThumbnailSource.THUMBNAIL,
thumbnail_file_type=FileType.PHOTO,
thumbnail_size=main.type,
volume_id=0,
local_id=0
).encode(),
file_unique_id=FileUniqueId(
file_unique_type=FileUniqueType.DOCUMENT,
media_id=video.id
).encode(),
width=main.w,
height=main.h,
duration=0,
file_size=main.size,
date=utils.timestamp_to_datetime(video.date),
file_name=file_name,
mime_type="video/mp4",
client=client
)

@@ -94,8 +94,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

if isinstance(message, raw.types.BusinessAwayMessage):
if isinstance(message.schedule, raw.types.BusinessAwayMessageScheduleAlways):
schedule = enums.BusinessSchedule.ALWAYS
elif isinstance(message.schedule, raw.types.BusinessAwayMessageScheduleOutsideWorkHours):
schedule = enums.BusinessSchedule.OUTSIDE_WORK_HOURS
elif isinstance(message.schedule, raw.types.BusinessAwayMessageScheduleCustom):
schedule = enums.BusinessSchedule.CUSTOM
schedule = enums.BusinessSchedule(type(message.schedule))

@@ -102,0 +97,0 @@ return BusinessMessage(

@@ -120,2 +120,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

def _parse(client: "pyrogram.Client", forum_topic: "raw.types.ForumTopic", messages: dict = {}, users: dict = {}, chats: dict = {}) -> "ForumTopic":
if not forum_topic:
return None
if isinstance(forum_topic, raw.types.ForumTopicDeleted):

@@ -122,0 +125,0 @@ return ForumTopic(id=forum_topic.id, is_deleted=True)

@@ -19,2 +19,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from typing import Optional, List
from pyrogram import raw, types, utils

@@ -25,22 +27,39 @@ from ..object import Object

class GiftCode(Object):
"""Contains gift code data.
"""Contains information about gift code.
Parameters:
months (``int``):
id (``str``):
Identifier of gift code.
You can combine it with `t.me/giftcode/{id}` to get link for this gift.
premium_subscription_month_count (``int``):
Number of months of subscription.
slug (``str``):
Identifier of gift code.
You can combine it with `t.me/giftcode/{slug}`
to get link for this gift.
caption (``str``, *optional*):
Text message.
via_giveaway (``bool``):
caption_entities (List of :obj:`~pyrogram.types.MessageEntity`, *optional*):
For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text.
via_giveaway (``bool``, *optional*):
True if the gift code is received via giveaway.
is_unclaimed (``bool``):
is_unclaimed (``bool``, *optional*):
True if the winner for the corresponding Telegram Premium subscription wasn't chosen.
boosted_chat (:obj:`~pyrogram.types.Chat`):
boosted_chat (:obj:`~pyrogram.types.Chat`, *optional*):
The channel where the gift code was won.
currency (``str``, *optional*):
Currency for the paid amount.
amount (``int``, *optional*):
The paid amount, in the smallest units of the currency.
cryptocurrency (``str``, *optional*):
Cryptocurrency used to pay for the gift.
cryptocurrency_amount (``int``, *optional*):
The paid amount, in the smallest units of the cryptocurrency.
link (``str``, *property*):

@@ -53,26 +72,46 @@ Generate a link to this gift code.

*,
months: int,
slug: str,
via_giveaway: bool = None,
is_unclaimed: bool = None,
boosted_chat: "types.Chat" = None
id: str,
premium_subscription_month_count: int,
caption: Optional[str] = None,
caption_entities: List["types.MessageEntity"] = None,
via_giveaway: Optional[bool] = None,
is_unclaimed: Optional[bool] = None,
boosted_chat: Optional["types.Chat"] = None,
currency: Optional[str] = None,
amount: Optional[int] = None,
cryptocurrency: Optional[str] = None,
cryptocurrency_amount: Optional[int] = None
):
super().__init__()
self.months = months
self.slug = slug
self.id = id
self.premium_subscription_month_count = premium_subscription_month_count
self.caption = caption
self.caption_entities = caption_entities
self.via_giveaway = via_giveaway
self.is_unclaimed = is_unclaimed
self.boosted_chat = boosted_chat
self.currency = currency
self.amount = amount
self.cryptocurrency = cryptocurrency
self.cryptocurrency_amount = cryptocurrency_amount
@staticmethod
def _parse(client, giftcode: "raw.types.MessageActionGiftCode", chats):
def _parse(client, giftcode: "raw.types.MessageActionGiftCode", users, chats):
peer = chats.get(utils.get_raw_peer_id(getattr(giftcode, "boost_peer")))
message, entities = (utils.parse_text_with_entities(client, getattr(giftcode, "message", None), users)).values()
return GiftCode(
months=giftcode.months,
slug=giftcode.slug,
id=giftcode.slug,
premium_subscription_month_count=giftcode.months,
caption=message or None,
caption_entities=entities or None,
via_giveaway=getattr(giftcode, "via_giveaway"),
is_unclaimed=getattr(giftcode, "unclaimed"),
boosted_chat=types.Chat._parse_chat(client, peer) if peer else None
boosted_chat=types.Chat._parse_chat(client, peer) if peer else None,
currency=getattr(giftcode, "currency", None) or None,
amount=getattr(giftcode, "amount", None) or None,
cryptocurrency=getattr(giftcode, "cryptocurrency", None) or None,
cryptocurrency_amount=getattr(giftcode, "cryptocurrency_amount", None) or None
)

@@ -82,2 +121,2 @@

def link(self) -> str:
return f"https://t.me/giftcode/{self.slug}"
return f"https://t.me/giftcode/{self.id}"

@@ -58,2 +58,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

True, if this giveaway winners is visible.
stars (``int``, *optional*):
Stars amount.
"""

@@ -72,3 +75,4 @@

only_for_countries: List[str] = None,
winners_are_visible: bool = None
winners_are_visible: bool = None,
stars: int = None
):

@@ -85,2 +89,3 @@ super().__init__(client)

self.winners_are_visible = winners_are_visible
self.stars = stars

@@ -102,3 +107,4 @@ @staticmethod

winners_are_visible=getattr(giveaway, "winners_are_visible", None),
stars=getattr(giveaway, "stars", None),
client=client
)

@@ -80,2 +80,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

Point in time when the poll will be automatically closed.
voter (:obj:`~pyrogram.types.User`, *optional*):
The user that voted in the poll.
"""

@@ -101,3 +104,4 @@

open_period: Optional[int] = None,
close_date: Optional[datetime] = None
close_date: Optional[datetime] = None,
voter: Optional["types.User"] = None
):

@@ -121,2 +125,3 @@ super().__init__(client)

self.close_date = close_date
self.voter = voter

@@ -201,36 +206,55 @@ @staticmethod

@staticmethod
def _parse_update(client, update: "raw.types.UpdateMessagePoll"):
if update.poll is not None:
return Poll._parse(client, update)
def _parse_update(client, update: Union["raw.types.UpdateMessagePoll", "raw.types.UpdateMessagePollVote"], users: dict):
if isinstance(update, raw.types.UpdateMessagePoll):
if update.poll is not None:
return Poll._parse(client, update)
results = update.results.results
chosen_option_id = None
correct_option_id = None
options = []
results = update.results.results
chosen_option_id = None
correct_option_id = None
options = []
for i, result in enumerate(results):
if result.chosen:
chosen_option_id = i
for i, result in enumerate(results):
if result.chosen:
chosen_option_id = i
if result.correct:
correct_option_id = i
if result.correct:
correct_option_id = i
options.append(
types.PollOption(
text="",
voter_count=result.voters,
data=result.option,
client=client
options.append(
types.PollOption(
text="",
voter_count=result.voters,
data=result.option,
client=client
)
)
return Poll(
id=str(update.poll_id),
question="",
options=options,
total_voter_count=update.results.total_voters,
is_closed=False,
chosen_option_id=chosen_option_id,
correct_option_id=correct_option_id,
client=client
)
return Poll(
id=str(update.poll_id),
question="",
options=options,
total_voter_count=update.results.total_voters,
is_closed=False,
chosen_option_id=chosen_option_id,
correct_option_id=correct_option_id,
client=client
)
if isinstance(update, raw.types.UpdateMessagePollVote):
return Poll(
id=str(update.poll_id),
question="",
options=[
types.PollOption(
text="",
voter_count=None,
data=option,
client=client
) for option in update.options
],
total_voter_count=None,
is_closed=False,
voter=types.User._parse(client, users[update.peer.user_id]),
client=client
)

@@ -42,2 +42,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

Available for chosen reactions.
is_paid (``bool``, *optional*):
True, if reaction is paid.
"""

@@ -52,3 +55,4 @@

count: Optional[int] = None,
chosen_order: Optional[int] = None
chosen_order: Optional[int] = None,
is_paid: Optional[bool] = None
):

@@ -61,2 +65,3 @@ super().__init__(client)

self.chosen_order = chosen_order
self.is_paid = is_paid

@@ -80,2 +85,8 @@ @staticmethod

if isinstance(reaction, raw.types.ReactionPaid):
return Reaction(
client=client,
is_paid=True
)
@staticmethod

@@ -82,0 +93,0 @@ def _parse_count(

@@ -20,3 +20,3 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from typing import Union, Optional
import pyrogram
from pyrogram import raw

@@ -90,3 +90,2 @@ from pyrogram import types

def _parse(
client: "pyrogram.Client",
successful_payment: Union[

@@ -93,0 +92,0 @@ "raw.types.MessageActionPaymentSent",

@@ -46,2 +46,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

codec (``str``):
Codec used for video file encoding, for example, "h264", "h265", or "av1".
duration (``int``):

@@ -80,2 +83,3 @@ Duration of the video in seconds as defined by sender.

height: int,
codec: str,
duration: int,

@@ -96,2 +100,3 @@ file_name: str = None,

self.height = height
self.codec = codec
self.duration = duration

@@ -126,4 +131,5 @@ self.file_name = file_name

).encode(),
width=video_attributes.w,
height=video_attributes.h,
width=getattr(video_attributes, "w", None),
height=getattr(video_attributes, "h", None),
codec=getattr(video_attributes, "video_codec", None),
duration=video_attributes.duration,

@@ -130,0 +136,0 @@ file_name=file_name,

@@ -46,2 +46,4 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from .invite_link_importer import InviteLinkImporter
from .phone_call_ended import PhoneCallEnded
from .phone_call_started import PhoneCallStarted
from .privacy_rule import PrivacyRule

@@ -76,2 +78,4 @@ from .restriction import Restriction

"InviteLinkImporter",
"PhoneCallEnded",
"PhoneCallStarted",
"PrivacyRule",

@@ -78,0 +82,0 @@ "ChatAdminWithInviteLinks",

@@ -73,2 +73,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

Administrators only. Privileged actions that an administrator is able to take.
subscription_until_date (:py:obj:`~datetime.datetime`, *optional*):
Date when the the subscription will end.
"""

@@ -92,3 +95,4 @@

permissions: "types.ChatPermissions" = None,
privileges: "types.ChatPrivileges" = None
privileges: "types.ChatPrivileges" = None,
subscription_until_date: datetime = None
):

@@ -110,2 +114,3 @@ super().__init__(client)

self.privileges = privileges
self.subscription_until_date = subscription_until_date

@@ -149,2 +154,3 @@ @staticmethod

joined_date=utils.timestamp_to_datetime(member.date),
subscription_until_date=utils.timestamp_to_datetime(getattr(member, "subscription_until_date", None)),
client=client

@@ -230,3 +236,4 @@ )

invited_by=types.User._parse(client, users[member.inviter_id]),
subscription_until_date=utils.timestamp_to_datetime(getattr(member, "subscription_until_date", None)),
client=client
)

@@ -46,2 +46,8 @@ # Pyrogram - Telegram MTProto API Client Library for Python

different accounts. Can't be used to download or reuse the file.
has_animation (``bool``):
True, if animated profile picture is available for this user.
is_personal (``bool``):
True, if the photo is visible only for the current user.
"""

@@ -56,4 +62,5 @@

big_file_id: str,
big_photo_unique_id: str
big_photo_unique_id: str,
has_animation: bool,
is_personal: bool
):

@@ -66,2 +73,4 @@ super().__init__(client)

self.big_photo_unique_id = big_photo_unique_id
self.has_animation = has_animation
self.is_personal = is_personal

@@ -109,3 +118,5 @@ @staticmethod

).encode(),
has_animation=chat_photo.has_video,
is_personal=getattr(chat_photo, "personal", False),
client=client
)

@@ -94,2 +94,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

is_paid_reactions_available (``bool``, *optional*):
True, if paid reactions enabled in this chat.
title (``str``, *optional*):

@@ -181,6 +184,2 @@ Title, for supergroups, channels and basic group chats.

distance (``int``, *optional*):
Distance in meters of this group chat from your location.
Returned only in :meth:`~pyrogram.Client.get_nearby_chats`.
personal_channel (:obj:`~pyrogram.types.Chat`, *optional*):

@@ -245,2 +244,5 @@ The personal channel linked to this chat.

subscription_until_date (:py:obj:`~datetime.datetime`, *optional*):
Date when the the subscription will end.
reactions_limit (``int``, *optional*):

@@ -280,2 +282,3 @@ This flag may be used to impose a custom limit of unique reactions (i.e. a customizable version of appConfig.reactions_uniq_max).

is_public: bool = None,
is_paid_reactions_available: bool = None,
title: str = None,

@@ -306,3 +309,2 @@ username: str = None,

permissions: "types.ChatPermissions" = None,
distance: int = None,
personal_channel: "types.Chat" = None,

@@ -326,2 +328,3 @@ personal_channel_message: "types.Message" = None,

banned_until_date: datetime = None,
subscription_until_date: datetime = None,
reactions_limit: int = None,

@@ -352,2 +355,3 @@ raw: Union["raw.base.Chat", "raw.base.User", "raw.base.ChatFull", "raw.base.UserFull"] = None

self.is_public = is_public
self.is_paid_reactions_available = is_paid_reactions_available
self.title = title

@@ -378,3 +382,2 @@ self.username = username

self.permissions = permissions
self.distance = distance
self.personal_channel = personal_channel

@@ -398,2 +401,3 @@ self.personal_channel_message = personal_channel_message

self.banned_until_date = banned_until_date
self.subscription_until_date = subscription_until_date
self.reactions_limit = reactions_limit

@@ -510,2 +514,3 @@ self.raw = raw

profile_color=types.ChatColor._parse(getattr(channel, "profile_color", None)),
subscription_until_date=utils.timestamp_to_datetime(getattr(channel, "subscription_until_date", None)),
raw=channel,

@@ -612,2 +617,3 @@ client=client

parsed_chat.can_send_paid_media = getattr(full_chat, "paid_media_allowed", None)
parsed_chat.is_paid_reactions_available = getattr(full_chat, "paid_reactions_available", None)

@@ -640,2 +646,3 @@ linked_chat_raw = chats.get(full_chat.linked_chat_id, None)

if full_chat.wallpaper and isinstance(full_chat.wallpaper, raw.types.WallPaper):

@@ -642,0 +649,0 @@ parsed_chat.wallpaper = types.Document._parse(client, full_chat.wallpaper.document, "wallpaper.jpg")

@@ -124,5 +124,2 @@ # Pyrogram - Telegram MTProto API Client Library for Python

full_name (``str``, *property*):
Full name of the other party in a private chat, for private chats and bots.
status (:obj:`~pyrogram.enums.UserStatus`, *optional*):

@@ -165,8 +162,2 @@ User's last seen & online status. ``None``, for bots.

mention (``str``, *property*):
Generate a text mention for this user.
You can use ``user.mention()`` to mention the user using their first name (styled using html), or
``user.mention("another name")`` for a custom name. To choose a different style
("html" or "md"/"markdown") use ``user.mention(style="md")``.
reply_color (:obj:`~pyrogram.types.ChatColor`, *optional*):

@@ -413,15 +404,2 @@ Chat reply color.

def listen(self, *args, **kwargs):
return self._client.listen((None, self.id, None), *args, **kwargs)
def ask(self, text, *args, **kwargs):
return self._client.ask(
text, (self.id, self.id, None), *args, **kwargs
)
def stop_listening(self, *args, **kwargs):
return self._client.stop_listening(
*args, identifier_pattern=(None, self.id, None), **kwargs
)
async def archive(self):

@@ -428,0 +406,0 @@ """Bound method *archive* of :obj:`~pyrogram.types.User`.

@@ -34,20 +34,5 @@ # Pyrogram - Telegram MTProto API Client Library for Python

from pyrogram import types
from pyrogram.errors import AuthBytesInvalid
from pyrogram.file_id import FileId, FileType, PHOTO_TYPES, DOCUMENT_TYPES
from pyrogram.session import Session
from pyrogram.session.auth import Auth
class PyromodConfig:
timeout_handler = None
stopped_handler = None
throw_exceptions = True
unallowed_click_alert = True
unallowed_click_alert_text = (
"[pyromod] You're not expected to click this button."
)
async def ainput(prompt: str = "", *, hide: bool = False):

@@ -54,0 +39,0 @@ """Just like the built-in input, but async"""

Metadata-Version: 2.1
Name: WPyrogram
Version: 2.0.148
Version: 2.0.149
Summary: Elegant, modern and asynchronous Telegram MTProto API framework in Python for users and bots - Woto's experimental fork

@@ -5,0 +5,0 @@ Home-page: https://github.com/ALiwoto/WPyrogram

@@ -69,2 +69,3 @@ COPYING

pyrogram/enums/chat_event_action.py
pyrogram/enums/chat_join_type.py
pyrogram/enums/chat_member_status.py

@@ -81,2 +82,3 @@ pyrogram/enums/chat_members_filter.py

pyrogram/enums/parse_mode.py
pyrogram/enums/phone_call_discard_reason.py
pyrogram/enums/poll_type.py

@@ -93,6 +95,6 @@ pyrogram/enums/privacy_key.py

pyrogram/handlers/callback_query_handler.py
pyrogram/handlers/chat_boost_handler.py
pyrogram/handlers/chat_join_request_handler.py
pyrogram/handlers/chat_member_updated_handler.py
pyrogram/handlers/chosen_inline_result_handler.py
pyrogram/handlers/conversation_handler.py
pyrogram/handlers/deleted_messages_handler.py

@@ -104,5 +106,9 @@ pyrogram/handlers/disconnect_handler.py

pyrogram/handlers/message_handler.py
pyrogram/handlers/message_reaction_count_handler.py
pyrogram/handlers/message_reaction_handler.py
pyrogram/handlers/poll_handler.py
pyrogram/handlers/pre_checkout_query_handler.py
pyrogram/handlers/purchased_paid_media_handler.py
pyrogram/handlers/raw_update_handler.py
pyrogram/handlers/shipping_query_handler.py
pyrogram/handlers/story_handler.py

@@ -145,6 +151,11 @@ pyrogram/handlers/user_status_handler.py

pyrogram/methods/bots/answer_pre_checkout_query.py
pyrogram/methods/bots/answer_shipping_query.py
pyrogram/methods/bots/answer_web_app_query.py
pyrogram/methods/bots/create_invoice_link.py
pyrogram/methods/bots/delete_bot_commands.py
pyrogram/methods/bots/get_bot_commands.py
pyrogram/methods/bots/get_bot_default_privileges.py
pyrogram/methods/bots/get_bot_info_description.py
pyrogram/methods/bots/get_bot_info_short_description.py
pyrogram/methods/bots/get_bot_name.py
pyrogram/methods/bots/get_chat_menu_button.py

@@ -160,2 +171,5 @@ pyrogram/methods/bots/get_game_high_scores.py

pyrogram/methods/bots/set_bot_default_privileges.py
pyrogram/methods/bots/set_bot_info_description.py
pyrogram/methods/bots/set_bot_info_short_description.py
pyrogram/methods/bots/set_bot_name.py
pyrogram/methods/bots/set_chat_menu_button.py

@@ -203,2 +217,3 @@ pyrogram/methods/bots/set_game_score.py

pyrogram/methods/chats/pin_chat_message.py
pyrogram/methods/chats/pin_forum_topic.py
pyrogram/methods/chats/promote_chat_member.py

@@ -223,2 +238,3 @@ pyrogram/methods/chats/restrict_chat_member.py

pyrogram/methods/chats/unpin_chat_message.py
pyrogram/methods/chats/unpin_forum_topic.py
pyrogram/methods/chats/update_chat_notifications.py

@@ -236,2 +252,3 @@ pyrogram/methods/chats/update_color.py

pyrogram/methods/decorators/on_callback_query.py
pyrogram/methods/decorators/on_chat_boost.py
pyrogram/methods/decorators/on_chat_join_request.py

@@ -245,5 +262,9 @@ pyrogram/methods/decorators/on_chat_member_updated.py

pyrogram/methods/decorators/on_message.py
pyrogram/methods/decorators/on_message_reaction.py
pyrogram/methods/decorators/on_message_reaction_count.py
pyrogram/methods/decorators/on_poll.py
pyrogram/methods/decorators/on_pre_checkout_query.py
pyrogram/methods/decorators/on_purchased_paid_media.py
pyrogram/methods/decorators/on_raw_update.py
pyrogram/methods/decorators/on_shipping_query.py
pyrogram/methods/decorators/on_story.py

@@ -284,2 +305,3 @@ pyrogram/methods/decorators/on_user_status.py

pyrogram/methods/messages/edit_message_text.py
pyrogram/methods/messages/forward_media_group.py
pyrogram/methods/messages/forward_messages.py

@@ -321,2 +343,3 @@ pyrogram/methods/messages/get_available_effects.py

pyrogram/methods/messages/send_paid_media.py
pyrogram/methods/messages/send_paid_reaction.py
pyrogram/methods/messages/send_photo.py

@@ -343,5 +366,14 @@ pyrogram/methods/messages/send_poll.py

pyrogram/methods/payments/__init__.py
pyrogram/methods/payments/apply_gift_code.py
pyrogram/methods/payments/check_gift_code.py
pyrogram/methods/payments/check_giftcode.py
pyrogram/methods/payments/convert_star_gift.py
pyrogram/methods/payments/get_payment_form.py
pyrogram/methods/payments/get_star_gifts.py
pyrogram/methods/payments/get_user_star_gifts.py
pyrogram/methods/payments/get_user_star_gifts_count.py
pyrogram/methods/payments/hide_star_gift.py
pyrogram/methods/payments/send_payment_form.py
pyrogram/methods/payments/send_star_gift.py
pyrogram/methods/payments/show_star_gift.py
pyrogram/methods/phone/__init__.py

@@ -354,2 +386,3 @@ pyrogram/methods/phone/get_call_members.py

pyrogram/methods/stories/__init__.py
pyrogram/methods/stories/can_post_stories.py
pyrogram/methods/stories/can_send_story.py

@@ -364,2 +397,3 @@ pyrogram/methods/stories/copy_story.py

pyrogram/methods/stories/get_all_stories.py
pyrogram/methods/stories/get_archived_stories.py
pyrogram/methods/stories/get_chat_stories.py

@@ -369,7 +403,12 @@ pyrogram/methods/stories/get_pinned_stories.py

pyrogram/methods/stories/get_stories_archive.py
pyrogram/methods/stories/hide_chat_stories.py
pyrogram/methods/stories/hide_stories.py
pyrogram/methods/stories/increment_story_views.py
pyrogram/methods/stories/pin_chat_stories.py
pyrogram/methods/stories/pin_stories.py
pyrogram/methods/stories/read_chat_stories.py
pyrogram/methods/stories/read_stories.py
pyrogram/methods/stories/send_story.py
pyrogram/methods/stories/show_chat_stories.py
pyrogram/methods/stories/unpin_chat_stories.py
pyrogram/methods/stories/view_stories.py

@@ -387,2 +426,3 @@ pyrogram/methods/users/__init__.py

pyrogram/methods/users/set_emoji_status.py
pyrogram/methods/users/set_personal_channel.py
pyrogram/methods/users/set_profile_photo.py

@@ -445,3 +485,2 @@ pyrogram/methods/users/set_username.py

pyrogram/types/object.py
pyrogram/types/pyromod.py
pyrogram/types/update.py

@@ -465,2 +504,3 @@ pyrogram/types/authorization/__init__.py

pyrogram/types/bots_and_keyboards/callback_query.py
pyrogram/types/bots_and_keyboards/chat_boost_updated.py
pyrogram/types/bots_and_keyboards/force_reply.py

@@ -477,4 +517,7 @@ pyrogram/types/bots_and_keyboards/game_high_score.py

pyrogram/types/bots_and_keyboards/menu_button_web_app.py
pyrogram/types/bots_and_keyboards/message_reaction_count_updated.py
pyrogram/types/bots_and_keyboards/message_reaction_updated.py
pyrogram/types/bots_and_keyboards/order_info.py
pyrogram/types/bots_and_keyboards/pre_checkout_query.py
pyrogram/types/bots_and_keyboards/purchased_paid_media.py
pyrogram/types/bots_and_keyboards/reply_keyboard_markup.py

@@ -489,2 +532,4 @@ pyrogram/types/bots_and_keyboards/reply_keyboard_remove.py

pyrogram/types/bots_and_keyboards/shipping_address.py
pyrogram/types/bots_and_keyboards/shipping_option.py
pyrogram/types/bots_and_keyboards/shipping_query.py
pyrogram/types/bots_and_keyboards/successful_payment.py

@@ -545,2 +590,3 @@ pyrogram/types/bots_and_keyboards/web_app_info.py

pyrogram/types/messages_and_media/chat_action.py
pyrogram/types/messages_and_media/chat_boost.py
pyrogram/types/messages_and_media/chat_event_action.py

@@ -552,2 +598,3 @@ pyrogram/types/messages_and_media/chat_member_status.py

pyrogram/types/messages_and_media/contact.py
pyrogram/types/messages_and_media/contact_registered.py
pyrogram/types/messages_and_media/dice.py

@@ -565,3 +612,6 @@ pyrogram/types/messages_and_media/document.py

pyrogram/types/messages_and_media/giveaway.py
pyrogram/types/messages_and_media/giveaway_completed.py
pyrogram/types/messages_and_media/giveaway_created.py
pyrogram/types/messages_and_media/giveaway_result.py
pyrogram/types/messages_and_media/giveaway_winners.py
pyrogram/types/messages_and_media/invoice.py

@@ -588,3 +638,6 @@ pyrogram/types/messages_and_media/location.py

pyrogram/types/messages_and_media/reaction.py
pyrogram/types/messages_and_media/refunded_payment.py
pyrogram/types/messages_and_media/screenshot_taken.py
pyrogram/types/messages_and_media/sent_code_type.py
pyrogram/types/messages_and_media/star_gift.py
pyrogram/types/messages_and_media/sticker.py

@@ -602,2 +655,3 @@ pyrogram/types/messages_and_media/story.py

pyrogram/types/messages_and_media/web_page.py
pyrogram/types/messages_and_media/write_access_allowed.py
pyrogram/types/user_and_chats/__init__.py

@@ -632,2 +686,4 @@ pyrogram/types/user_and_chats/birthday.py

pyrogram/types/user_and_chats/invite_link_importer.py
pyrogram/types/user_and_chats/phone_call_ended.py
pyrogram/types/user_and_chats/phone_call_started.py
pyrogram/types/user_and_chats/privacy_rule.py

@@ -634,0 +690,0 @@ pyrogram/types/user_and_chats/restriction.py

# 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 inspect
from typing import Union
import pyrogram
from pyrogram.types import Message, CallbackQuery
from .message_handler import MessageHandler
from .callback_query_handler import CallbackQueryHandler
class ConversationHandler(MessageHandler, CallbackQueryHandler):
"""The Conversation handler class."""
def __init__(self):
self.waiters = {}
async def check(self, client: "pyrogram.Client", update: Union[Message, CallbackQuery]):
if isinstance(update, Message) and update.outgoing:
return False
try:
chat_id = update.chat.id if isinstance(update, Message) else update.message.chat.id
except AttributeError:
return False
waiter = self.waiters.get(chat_id)
if not waiter or not isinstance(update, waiter['update_type']) or waiter['future'].done():
return False
filters = waiter.get('filters')
if callable(filters):
if inspect.iscoroutinefunction(filters.__call__):
filtered = await filters(client, update)
else:
filtered = await client.loop.run_in_executor(
client.executor,
filters,
client, update
)
if not filtered or waiter['future'].done():
return False
waiter['future'].set_result(update)
return True
@staticmethod
async def callback(_, __):
pass
def delete_waiter(self, chat_id, future):
if future == self.waiters[chat_id]['future']:
del self.waiters[chat_id]
from enum import Enum
class ListenerStopped(Exception):
pass
class ListenerTimeout(Exception):
pass
class ListenerTypes(Enum):
MESSAGE = "message"
CALLBACK_QUERY = "callback_query"

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display