mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2024-11-22 07:06:26 +01:00
a4e78f6183
* Remove error handlers from examples
Most examples use the same error handler, that error handler logs
update.to_dict but doesn't log error traceback. Hiding error traceback
is quite bad, removing the error handler entirely causes PTB to use
default error logging which does include error traceback.
* adding error handling example
* Change error handler example
Including:
- Change the telegram message to include usual python error message.
- HTML-escape the strings used to build the telegram message.
- Capitalize comments and add more empty lines to hopefully unify the
style with other examples, at least a bit.
- Reorder imports.
* Add an error-rising command to the error handler example
* Slightly change example error handler docstring and comments
* Make telegram message sent by the error handler example more readable
* Rename error_handler.py to errorhandlerbot.py and add a start command
* Change error handler example to work without developer chat id
* Revert "Change error handler example to work without developer chat id"
This reverts commit c4efea6f
* Make bot token a module level constant in the error handler example
Otherwise the example will require two edits 40 lines apart to run.
* Show chat id in start command of the error handler example
The example requires you to set developer chat id, this change will
make things easier for users that don't know how to see their chat id.
* Add errorhandlerbot.py to the examples folder readme
Co-authored-by: poolitzer <25934244+poolitzer@users.noreply.github.com>
Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>
142 lines
5.3 KiB
Python
142 lines
5.3 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
# 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)
|
|
from telegram.ext import (Updater, CommandHandler, MessageHandler,
|
|
Filters, PreCheckoutQueryHandler, ShippingQueryHandler)
|
|
|
|
# Enable logging
|
|
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
level=logging.INFO)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def start_callback(update, context):
|
|
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, context):
|
|
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, context):
|
|
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, context):
|
|
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
|
|
else:
|
|
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, context):
|
|
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, context):
|
|
# 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.
|
|
# Make sure to set use_context=True to use the new context based callbacks
|
|
# Post version 12 this will no longer be necessary
|
|
updater = Updater("TOKEN", use_context=True)
|
|
|
|
# Get the dispatcher to register handlers
|
|
dp = updater.dispatcher
|
|
|
|
# simple start function
|
|
dp.add_handler(CommandHandler("start", start_callback))
|
|
|
|
# Add command handler to start the payment invoice
|
|
dp.add_handler(CommandHandler("shipping", start_with_shipping_callback))
|
|
dp.add_handler(CommandHandler("noshipping", start_without_shipping_callback))
|
|
|
|
# Optional handler if your product requires shipping
|
|
dp.add_handler(ShippingQueryHandler(shipping_callback))
|
|
|
|
# Pre-checkout handler to final check
|
|
dp.add_handler(PreCheckoutQueryHandler(precheckout_callback))
|
|
|
|
# Success! Notify your user!
|
|
dp.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()
|