python-telegram-bot/examples/paymentbot.py
Bibo-Joshi 36d49ea9cd
Doc Fixes (#2253)
* Render-fixes for BP

* docs: fix simple typo, submition -> submission (#2260)

There is a small typo in tests/test_bot.py.

Should read `submission` rather than `submition`.

* Type on rawapibot.py docstring

* typo

* Typo: Filters.document(s)

* Typo fix

* Doc fix for messageentity (#2311)

* Add New Shortcuts to Chat (#2291)

* Add shortcuts

* Add a note

* Add run_async Parameter to ConversationHandler (#2292)

* Add run_async parameter

* Update docstring

* Update test to explicitly specify parameter

* Fix test job queue

* Add version added tag to docs

* Update docstring

Co-authored-by: Poolitzer <25934244+Poolitzer@users.noreply.github.com>

* Doc nitpicking

Co-authored-by: Poolitzer <25934244+Poolitzer@users.noreply.github.com>
Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>

* Fix rendering in messageentity

Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>
Co-authored-by: zeshuaro <joshuaystang@gmail.com>
Co-authored-by: Poolitzer <25934244+Poolitzer@users.noreply.github.com>

* fix: type hints for TelegramError

changed :class:`telegram.TelegramError` to :class:`telegram.error.TelegramError`

* fix: the error can be more then just a Telegram error

* Doc fix for inlinekeyboardbutton.py

added missing colon which broke rendering

* fix: remove context argument and doc remark

look at us already being in post 12

* use rtd badge

* filters doc fixes

* fix some rendering

* Doc & Rendering fixes for helpers.py

Co-authored-by: Tim Gates <tim.gates@iress.com>
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
Co-authored-by: zeshuaro <joshuaystang@gmail.com>
Co-authored-by: Poolitzer <25934244+Poolitzer@users.noreply.github.com>
Co-authored-by: Harshil <ilovebhagwan@gmail.com>
2021-02-01 17:59:39 +01:00

161 lines
5.5 KiB
Python

#!/usr/bin/env python
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.
"""
Basic example for a bot that can receive payment from user.
"""
import logging
from telegram import LabeledPrice, ShippingOption, Update
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
PreCheckoutQueryHandler,
ShippingQueryHandler,
CallbackContext,
)
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
def start_callback(update: Update, context: CallbackContext) -> None:
msg = "Use /shipping to get an invoice for shipping-payment, "
msg += "or /noshipping for an invoice without shipping."
update.message.reply_text(msg)
def start_with_shipping_callback(update: Update, context: CallbackContext) -> None:
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
# select a payload just for you to recognize its the donation from your bot
payload = "Custom-Payload"
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
provider_token = "PROVIDER_TOKEN"
start_parameter = "test-payment"
currency = "USD"
# price in dollars
price = 1
# price * 100 so as to include 2 decimal points
# check https://core.telegram.org/bots/payments#supported-currencies for more details
prices = [LabeledPrice("Test", price * 100)]
# optionally pass need_name=True, need_phone_number=True,
# need_email=True, need_shipping_address=True, is_flexible=True
context.bot.send_invoice(
chat_id,
title,
description,
payload,
provider_token,
start_parameter,
currency,
prices,
need_name=True,
need_phone_number=True,
need_email=True,
need_shipping_address=True,
is_flexible=True,
)
def start_without_shipping_callback(update: Update, context: CallbackContext) -> None:
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
# select a payload just for you to recognize its the donation from your bot
payload = "Custom-Payload"
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
provider_token = "PROVIDER_TOKEN"
start_parameter = "test-payment"
currency = "USD"
# price in dollars
price = 1
# price * 100 so as to include 2 decimal points
prices = [LabeledPrice("Test", price * 100)]
# optionally pass need_name=True, need_phone_number=True,
# need_email=True, need_shipping_address=True, is_flexible=True
context.bot.send_invoice(
chat_id, title, description, payload, provider_token, start_parameter, currency, prices
)
def shipping_callback(update: Update, context: CallbackContext) -> None:
query = update.shipping_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
query.answer(ok=False, error_message="Something went wrong...")
return
options = list()
# a single LabeledPrice
options.append(ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)]))
# an array of LabeledPrice objects
price_list = [LabeledPrice('B1', 150), LabeledPrice('B2', 200)]
options.append(ShippingOption('2', 'Shipping Option B', price_list))
query.answer(ok=True, shipping_options=options)
# after (optional) shipping, it's the pre-checkout
def precheckout_callback(update: Update, context: CallbackContext) -> None:
query = update.pre_checkout_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
query.answer(ok=False, error_message="Something went wrong...")
else:
query.answer(ok=True)
# finally, after contacting the payment provider...
def successful_payment_callback(update: Update, context: CallbackContext) -> None:
# do something after successfully receiving payment?
update.message.reply_text("Thank you for your payment!")
def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# simple start function
dispatcher.add_handler(CommandHandler("start", start_callback))
# Add command handler to start the payment invoice
dispatcher.add_handler(CommandHandler("shipping", start_with_shipping_callback))
dispatcher.add_handler(CommandHandler("noshipping", start_without_shipping_callback))
# Optional handler if your product requires shipping
dispatcher.add_handler(ShippingQueryHandler(shipping_callback))
# Pre-checkout handler to final check
dispatcher.add_handler(PreCheckoutQueryHandler(precheckout_callback))
# Success! Notify your user!
dispatcher.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()