Skip to content

Commit

Permalink
pyrofork: Add high level support for pre-checkout queries and service…
Browse files Browse the repository at this point in the history
… messages for successful payments

* Add high level support for pre-checkout queries

* Add high level support for incoming payments

* Update and fix documentation

---------

Co-authored-by: KurimuzonAkuma <31959970+KurimuzonAkuma@users.noreply.github.com>
Signed-off-by: wulan17 <wulan17@nusantararom.org>
  • Loading branch information
2 people authored and wulan17 committed Jun 1, 2024
1 parent d7c58c0 commit 1329f8e
Show file tree
Hide file tree
Showing 19 changed files with 619 additions and 7 deletions.
13 changes: 13 additions & 0 deletions compiler/docs/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ def get_title_list(s: str) -> list:
set_chat_menu_button
get_chat_menu_button
answer_web_app_query
answer_pre_checkout_query
get_bot_info
set_bot_info
""",
Expand Down Expand Up @@ -504,6 +505,7 @@ def get_title_list(s: str) -> list:
ReactionType
MessageReactionUpdated
MessageReactionCountUpdated
SuccessfulPayment
""",
stories="""
Stories
Expand Down Expand Up @@ -546,6 +548,9 @@ def get_title_list(s: str) -> list:
MenuButtonWebApp
MenuButtonDefault
SentWebAppMessage
PaymentInfo
PreCheckoutQuery
ShippingAddress
""",
bot_commands="""
Bot commands
Expand Down Expand Up @@ -592,6 +597,10 @@ def get_title_list(s: str) -> list:
InlineQueryResultVoice
ChosenInlineResult
""",
pre_checkout_query="""
PreCheckoutQuery
PreCheckoutQuery.answer
""",
input_message_content="""
InputMessageContent
InputMessageContent
Expand Down Expand Up @@ -742,6 +751,10 @@ def get_title_list(s: str) -> list:
InlineQuery
InlineQuery.answer
""",
pre_checkout_query="""
PreCheckoutQuery
PreCheckoutQuery.answer
""",
chat_join_request="""
ChatJoinRequest
ChatJoinRequest.approve
Expand Down
13 changes: 13 additions & 0 deletions compiler/docs/template/bound-methods.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,19 @@ InlineQuery

{inline_query_toctree}

PreCheckoutQuery
-----------

.. hlist::
:columns: 2

{pre_checkout_query_hlist}

.. toctree::
:hidden:

{pre_checkout_query_toctree}

ChatJoinRequest
---------------

Expand Down
11 changes: 10 additions & 1 deletion pyrogram/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
RawUpdateHandler,
InlineQueryHandler,
PollHandler,
PreCheckoutQueryHandler,
ConversationHandler,
ChosenInlineResultHandler,
ChatMemberUpdatedHandler,
Expand All @@ -51,7 +52,7 @@
UpdateBotNewBusinessMessage, UpdateBotDeleteBusinessMessage, UpdateBotEditBusinessMessage,
UpdateEditMessage, UpdateEditChannelMessage,
UpdateDeleteMessages, UpdateDeleteChannelMessages,
UpdateBotCallbackQuery, UpdateInlineBotCallbackQuery,
UpdateBotCallbackQuery, UpdateInlineBotCallbackQuery, UpdateBotPrecheckoutQuery,
UpdateUserStatus, UpdateBotInlineQuery, UpdateMessagePoll,
UpdateBotInlineSend, UpdateChatParticipant, UpdateChannelParticipant, UpdateBotStopped,
UpdateBotChatInviteRequester, UpdateStory,
Expand Down Expand Up @@ -80,6 +81,7 @@ class Dispatcher:
MESSAGE_BOT_NA_REACTION_UPDATES = (UpdateBotMessageReaction,)
MESSAGE_BOT_A_REACTION_UPDATES = (UpdateBotMessageReactions,)
BOT_BUSSINESS_CONNECT_UPDATES = (UpdateBotBusinessConnect,)
PRE_CHECKOUT_QUERY_UPDATES = (UpdateBotPrecheckoutQuery,)

def __init__(self, client: "pyrogram.Client"):
self.client = client
Expand Down Expand Up @@ -191,6 +193,12 @@ async def story_parser(update, users, chats):
StoryHandler
)

async def pre_checkout_query_parser(update, users, chats):
return (
await pyrogram.types.PreCheckoutQuery._parse(self.client, update, users),
PreCheckoutQueryHandler
)

async def message_bot_na_reaction_parser(update, users, chats):
return (
pyrogram.types.MessageReactionUpdated._parse(self.client, update, users, chats),
Expand Down Expand Up @@ -224,6 +232,7 @@ async def bot_business_connect_parser(update, users, chats):
Dispatcher.CHAT_MEMBER_UPDATES: chat_member_updated_parser,
Dispatcher.CHAT_JOIN_REQUEST_UPDATES: chat_join_request_parser,
Dispatcher.NEW_STORY_UPDATES: story_parser,
Dispatcher.PRE_CHECKOUT_QUERY_UPDATES: pre_checkout_query_parser,
Dispatcher.MESSAGE_BOT_NA_REACTION_UPDATES: message_bot_na_reaction_parser,
Dispatcher.MESSAGE_BOT_A_REACTION_UPDATES: message_bot_a_reaction_parser,
Dispatcher.BOT_BUSSINESS_CONNECT_UPDATES: bot_business_connect_parser
Expand Down
3 changes: 3 additions & 0 deletions pyrogram/enums/message_service_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,6 @@ class MessageServiceType(AutoName):

BOOST_APPLY = auto()
"Boost apply"

SUCCESSFUL_PAYMENT = auto()
"Successful payment"
17 changes: 16 additions & 1 deletion pyrogram/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
InlineKeyboardMarkup,
InlineQuery,
Message,
PreCheckoutQuery,
ReplyKeyboardMarkup,
Story,
Update,
Expand Down Expand Up @@ -697,6 +698,17 @@ async def video_chat_members_invited_filter(_, __, m: Message):
"""Filter messages for voice chat invited members"""


# endregion

# region successful_payment_filter
async def successful_payment_filter(_, __, m: Message):
return bool(m.successful_payment)


successful_payment = create(successful_payment_filter)
"""Filter messages for successful payments"""


# endregion

# region service_filter
Expand All @@ -710,7 +722,7 @@ async def service_filter(_, __, m: Message):
A service message contains any of the following fields set: *left_chat_member*,
*new_chat_title*, *new_chat_photo*, *delete_chat_photo*, *group_chat_created*, *supergroup_chat_created*,
*channel_chat_created*, *migrate_to_chat_id*, *migrate_from_chat_id*, *pinned_message*, *game_score*,
*video_chat_started*, *video_chat_ended*, *video_chat_members_invited*.
*video_chat_started*, *video_chat_ended*, *video_chat_members_invited*, *successful_payment*, *successful_payment*.
"""


Expand Down Expand Up @@ -909,6 +921,7 @@ def regex(pattern: Union[str, Pattern], flags: int = 0):
- :obj:`~pyrogram.types.Message`: The filter will match ``text`` or ``caption``.
- :obj:`~pyrogram.types.CallbackQuery`: The filter will match ``data``.
- :obj:`~pyrogram.types.InlineQuery`: The filter will match ``query``.
- :obj:`~pyrogram.types.PreCheckoutQuery`: The filter will match ``payload``.
When a pattern matches, all the `Match Objects <https://docs.python.org/3/library/re.html#match-objects>`_ are
stored in the ``matches`` field of the update object itself.
Expand All @@ -928,6 +941,8 @@ async def func(flt, _, update: Update):
value = update.data
elif isinstance(update, InlineQuery):
value = update.query
elif isinstance(update, PreCheckoutQuery):
value = update.payload
else:
raise ValueError(f"Regex filter doesn't work with {type(update)}")

Expand Down
1 change: 1 addition & 0 deletions pyrogram/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from .inline_query_handler import InlineQueryHandler
from .message_handler import MessageHandler
from .poll_handler import PollHandler
from .pre_checkout_query_handler import PreCheckoutQueryHandler
from .raw_update_handler import RawUpdateHandler
from .user_status_handler import UserStatusHandler
from .story_handler import StoryHandler
Expand Down
49 changes: 49 additions & 0 deletions pyrogram/handlers/pre_checkout_query_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 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 PreCheckoutQueryHandler(Handler):
"""The PreCheckoutQueryHandler handler class. Used to handle pre-checkout queries coming from buy buttons.
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_pre_checkout_query` decorator.
Parameters:
callback (``Callable``):
Pass a function that will be called when a new PreCheckoutQuery arrives. It takes *(client, pre_checkout_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 message handler.
pre_checkout_query (:obj:`~pyrogram.types.PreCheckoutQuery`):
The received callback query.
"""

def __init__(self, callback: Callable, filters=None):
super().__init__(callback, filters)
4 changes: 3 additions & 1 deletion pyrogram/methods/bots/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from .answer_callback_query import AnswerCallbackQuery
from .answer_inline_query import AnswerInlineQuery
from .answer_pre_checkout_query import AnswerPreCheckoutQuery
from .answer_web_app_query import AnswerWebAppQuery
from .delete_bot_commands import DeleteBotCommands
from .get_bot_commands import GetBotCommands
Expand Down Expand Up @@ -55,6 +56,7 @@ class Bots(
GetBotInfo,
SetChatMenuButton,
GetChatMenuButton,
AnswerWebAppQuery
AnswerWebAppQuery,
AnswerPreCheckoutQuery
):
pass
64 changes: 64 additions & 0 deletions pyrogram/methods/bots/answer_pre_checkout_query.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.

import pyrogram
from pyrogram import raw


class AnswerPreCheckoutQuery:
async def answer_pre_checkout_query(
self: "pyrogram.Client",
pre_checkout_query_id: str,
success: bool = None,
error: str = None
):
"""Send answers to pre-checkout queries.
.. include:: /_includes/usable-by/bots.rst
Parameters:
pre_checkout_query_id (``str``):
Unique identifier for the query to be answered.
success (``bool``, *optional*):
Set this flag if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order.
Otherwise do not set it, and set the error field, instead.
error (``str``, *optional*):
Error message in human readable form that explains the reason for failure to proceed with the checkout.
Required if ``success`` isn't set.
Returns:
``bool``: True, on success.
Example:
.. code-block:: python
# Proceed with the order
await app.answer_pre_checkout_query(query_id, success=True)
# Answer with error message
await app.answer_pre_checkout_query(query_id, error=error)
"""
return await self.invoke(
raw.functions.messages.SetBotPrecheckoutResults(
query_id=int(pre_checkout_query_id),
success=success or None,
error=error or None
)
)
2 changes: 1 addition & 1 deletion pyrogram/methods/chats/get_chat_member.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def get_chat_member(
Unique identifier (int) or username (str) of the target chat.
You can also use chat public link in form of *t.me/<username>* (str).
user_id (``int`` | ``str``)::
user_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target user.
For you yourself you can simply use "me" or "self".
For a contact that exists in your Telegram address book you can use his phone number (str).
Expand Down
4 changes: 3 additions & 1 deletion pyrogram/methods/decorators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from .on_inline_query import OnInlineQuery
from .on_message import OnMessage
from .on_poll import OnPoll
from .on_pre_checkout_query import OnPreCheckoutQuery
from .on_raw_update import OnRawUpdate
from .on_user_status import OnUserStatus
from .on_story import OnStory
Expand All @@ -57,6 +58,7 @@ class Decorators(
OnChatJoinRequest,
OnStory,
OnMessageReactionUpdated,
OnMessageReactionCountUpdated
OnMessageReactionCountUpdated,
OnPreCheckoutQuery
):
pass
Loading

0 comments on commit 1329f8e

Please sign in to comment.