Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitffe23be

Browse files
Bibo-JoshiSnehashish BiswasPoolitzer
authored
Co-authored-by: Snehashish Biswas <coderrx06@gmail.com>Co-authored-by: poolitzer <github@poolitzer.eu>
1 parentef1685c commitffe23be

File tree

4 files changed

+63
-44
lines changed

4 files changed

+63
-44
lines changed

‎AUTHORS.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ The following wonderful people contributed directly or indirectly to this projec
111111
- `Rahiel Kasim<https://github.com/rahiel>`_
112112
- `Riko Naka<https://github.com/rikonaka>`_
113113
- `Rizlas<https://github.com/rizlas>`_
114+
- `Snehashish Biswas<https://github.com/Snehashish06>`_
114115
- `Sahil Sharma<https://github.com/sahilsharma811>`_
115116
- `Sam Mosleh<https://github.com/sam-mosleh>`_
116117
- `Sascha<https://github.com/saschalalala>`_

‎examples/paymentbot.py

Lines changed: 39 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# pylint: disable=unused-argument
33
# This program is dedicated to the public domain under the CC0 license.
44

5-
"""Basic example for a bot that can receivepayment fromuser."""
5+
"""Basic example for a bot that can receivepayments fromusers."""
66

77
importlogging
88

@@ -26,36 +26,36 @@
2626

2727
logger=logging.getLogger(__name__)
2828

29+
# Insert the token from your payment provider.
30+
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
2931
PAYMENT_PROVIDER_TOKEN="PAYMENT_PROVIDER_TOKEN"
3032

3133

3234
asyncdefstart_callback(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:
33-
"""Displays info on how to use the bot."""
35+
"""Provides instructions on how to use the bot."""
3436
msg= (
35-
"Use /shipping toget an invoicefor shipping-payment, or /noshipping for an "
37+
"Use /shipping toreceive an invoicewith shipping included, or /noshipping for an "
3638
"invoice without shipping."
3739
)
38-
3940
awaitupdate.message.reply_text(msg)
4041

4142

4243
asyncdefstart_with_shipping_callback(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:
43-
"""Sends an invoicewithshipping-payment."""
44+
"""Sends an invoicewhich triggers ashipping query."""
4445
chat_id=update.message.chat_id
4546
title="Payment Example"
46-
description="PaymentExample using python-telegram-bot"
47-
#select apayloadjust for you to recognize its the donation from your bot
47+
description="Exampleof a payment processusingthepython-telegram-bot library."
48+
#Uniquepayloadto identify this payment request as being from your bot
4849
payload="Custom-Payload"
49-
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
50+
# Set up the currency.
51+
# List of supported currencies: https://core.telegram.org/bots/payments#supported-currencies
5052
currency="USD"
51-
#price in dollars
53+
#Price in dollars
5254
price=1
53-
# price * 100 so as to include 2 decimal points
54-
# check https://core.telegram.org/bots/payments#supported-currencies for more details
55+
# Convert price to cents from dollars.
5556
prices= [LabeledPrice("Test",price*100)]
56-
57-
# optionally pass need_name=True, need_phone_number=True,
58-
# need_email=True, need_shipping_address=True, is_flexible=True
57+
# Optional parameters like need_shipping_address and is_flexible trigger extra user prompts
58+
# https://docs.python-telegram-bot.org/en/stable/telegram.bot.html#telegram.Bot.send_invoice
5959
awaitcontext.bot.send_invoice(
6060
chat_id,
6161
title,
@@ -75,17 +75,16 @@ async def start_with_shipping_callback(update: Update, context: ContextTypes.DEF
7575
asyncdefstart_without_shipping_callback(
7676
update:Update,context:ContextTypes.DEFAULT_TYPE
7777
)->None:
78-
"""Sends an invoice without shipping-payment."""
78+
"""Sends an invoice withoutrequiringshipping details."""
7979
chat_id=update.message.chat_id
8080
title="Payment Example"
81-
description="PaymentExample using python-telegram-bot"
82-
#select apayloadjust for you to recognize its the donation from your bot
81+
description="Exampleof a payment processusingthepython-telegram-bot library."
82+
#Uniquepayloadto identify this payment request as being from your bot
8383
payload="Custom-Payload"
84-
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
8584
currency="USD"
86-
#price in dollars
85+
#Price in dollars
8786
price=1
88-
# price* 100 so astoinclude 2 decimal points
87+
#Convertprice tocents from dollars.
8988
prices= [LabeledPrice("Test",price*100)]
9089

9190
# optionally pass need_name=True, need_phone_number=True,
@@ -96,65 +95,65 @@ async def start_without_shipping_callback(
9695

9796

9897
asyncdefshipping_callback(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:
99-
"""Answers the ShippingQuery withShippingOptions"""
98+
"""Handles the ShippingQuery withavailable shipping options."""
10099
query=update.shipping_query
101-
#checkthe payload, is this from your bot?
100+
#Verify ifthe payload matches, ensure it's from your bot
102101
ifquery.invoice_payload!="Custom-Payload":
103-
#answer False pre_checkout_query
102+
#If not, respond with an error
104103
awaitquery.answer(ok=False,error_message="Something went wrong...")
105104
return
106105

107-
# First option has a single LabeledPrice
106+
# Define available shipping options
107+
# First option with a single price entry
108108
options= [ShippingOption("1","Shipping Option A", [LabeledPrice("A",100)])]
109-
#second optionhas an array of LabeledPrice objects
109+
#Second optionwith multiple price entries
110110
price_list= [LabeledPrice("B1",150),LabeledPrice("B2",200)]
111111
options.append(ShippingOption("2","Shipping Option B",price_list))
112112
awaitquery.answer(ok=True,shipping_options=options)
113113

114114

115-
#after (optional) shipping,it's the pre-checkout
115+
#After (optional) shipping,process the pre-checkout step
116116
asyncdefprecheckout_callback(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:
117-
"""AnswersthePreQecheckoutQuery"""
117+
"""Responds tothePreCheckoutQuery as the final confirmation for checkout."""
118118
query=update.pre_checkout_query
119-
#checkthe payload, is this from your bot?
119+
#Verify ifthe payload matches, ensure it's from your bot
120120
ifquery.invoice_payload!="Custom-Payload":
121-
#answer False pre_checkout_query
121+
#If not, respond with an error
122122
awaitquery.answer(ok=False,error_message="Something went wrong...")
123123
else:
124124
awaitquery.answer(ok=True)
125125

126126

127-
#finally,aftercontacting thepayment provider...
127+
#Final callbackaftersuccessfulpayment
128128
asyncdefsuccessful_payment_callback(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:
129-
"""Confirms the successful payment."""
130-
# do something after successfully receiving payment?
131-
awaitupdate.message.reply_text("Thank you for your payment!")
129+
"""Acknowledges successful payment and thanks the user."""
130+
awaitupdate.message.reply_text("Thank you for your payment.")
132131

133132

134133
defmain()->None:
135-
"""Run the bot."""
134+
"""Starts the bot and sets up handlers."""
136135
# Create the Application and pass it your bot's token.
137136
application=Application.builder().token("TOKEN").build()
138137

139-
#simple start function
138+
#Start command to display usage instructions
140139
application.add_handler(CommandHandler("start",start_callback))
141140

142-
#Add command handler to startthe paymentinvoice
141+
#Command handlers for startingthe paymentprocess
143142
application.add_handler(CommandHandler("shipping",start_with_shipping_callback))
144143
application.add_handler(CommandHandler("noshipping",start_without_shipping_callback))
145144

146-
#Optional handler if yourproduct requires shipping
145+
#Handler for shipping query (ifproduct requires shipping)
147146
application.add_handler(ShippingQueryHandler(shipping_callback))
148147

149-
# Pre-checkout handlerto final check
148+
# Pre-checkout handlerfor verifying payment details.
150149
application.add_handler(PreCheckoutQueryHandler(precheckout_callback))
151150

152-
#Success!Notifyyour user!
151+
#Handler for successful payment.Notifythe user that the payment was successful.
153152
application.add_handler(
154153
MessageHandler(filters.SUCCESSFUL_PAYMENT,successful_payment_callback)
155154
)
156155

157-
#Run the botuntilthe user presses Ctrl-C
156+
#Start polling for updatesuntilinterrupted (CTRL+C)
158157
application.run_polling(allowed_updates=Update.ALL_TYPES)
159158

160159

‎telegram/ext/_aioratelimiter.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,19 @@ class AIORateLimiter(BaseRateLimiter[int]):
8888
necessary in some cases, e.g. the bot may hit a rate limit in one group but might still
8989
be allowed to send messages in another group.
9090
91+
Tip:
92+
With `Bot API 7.1 <https://core.telegram.org/bots/api-changelog#october-31-2024>`_
93+
(PTB v27.1), Telegram introduced the parameter
94+
:paramref:`~telegram.Bot.send_message.allow_paid_broadcast`.
95+
This allows bots to send up to
96+
:tg-const:`telegram.constants.FloodLimit.PAID_MESSAGES_PER_SECOND` messages per second by
97+
paying a fee in Telegram Stars.
98+
99+
.. caution::
100+
This class currently doesn't take the
101+
:paramref:`~telegram.Bot.send_message.allow_paid_broadcast` parameter into account.
102+
This means that the rate limiting is applied just like for any other message.
103+
91104
Note:
92105
This class is to be understood as minimal effort reference implementation.
93106
If you would like to handle rate limiting in a more sophisticated, fine-tuned way, we

‎telegram/ext/_handlers/commandhandler.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,11 @@
3636
classCommandHandler(BaseHandler[Update,CCT,RT]):
3737
"""Handler class to handle Telegram commands.
3838
39-
Commands are Telegram messages that start with ``/``, optionally followed by an ``@`` and the
40-
bot's name and/or some additional text. The handler will add a :obj:`list` to the
41-
:class:`CallbackContext` named :attr:`CallbackContext.args`. It will contain a list of strings,
42-
which is the text following the command split on single or consecutive whitespace characters.
39+
Commands are Telegram messages that start with a :attr:`telegram.MessageEntity.BOT_COMMAND`
40+
(so with ``/``, optionally followed by an ``@`` and the bot's name and/or some additional
41+
text). The handler will add a :obj:`list` to the :class:`CallbackContext` named
42+
:attr:`CallbackContext.args`. It will contain a list of strings, which is the text following
43+
the command split on single or consecutive whitespace characters.
4344
4445
By default, the handler listens to messages as well as edited messages. To change this behavior
4546
use :attr:`~filters.UpdateType.EDITED_MESSAGE <telegram.ext.filters.UpdateType.EDITED_MESSAGE>`
@@ -53,6 +54,11 @@ class CommandHandler(BaseHandler[Update, CCT, RT]):
5354
:attr:`telegram.ext.filters.CAPTION` and :class:`telegram.ext.filters.Regex`) to handle
5455
those messages.
5556
57+
Note:
58+
If you want to support a different entity in the beginning, e.g. if a command message is
59+
wrapped in a :attr:`telegram.MessageEntity.CODE`, use the
60+
:class:`telegram.ext.PrefixHandler`.
61+
5662
Warning:
5763
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
5864
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp