def send_invoice(bot, update): query = update.callback_query chat_id = query.message.chat_id cart = get_cart(chat_id) title = f'Заказ {chat_id}' description = 'Пицца' payload = 'Pizza_payment' provider_token = TELEGRAM_PAYMENT_TOKEN start_parameter = TELEGRAM_PAYMENT_PARAMETER currency = 'RUB' prices = [ LabeledPrice(f'{pizza["name"]}, {pizza["quantity"]} шт.', pizza['unit_price'] * INVOICE_PRICE_MULTIPLIER) for pizza in cart['products'] if pizza["name"] != DELIVERY_ITEM_NAME ] delivery = next(item for item in cart['products'] if item['name'] == DELIVERY_ITEM_NAME) prices.append( LabeledPrice(delivery['name'], delivery['unit_price'] * INVOICE_PRICE_MULTIPLIER)) bot.sendInvoice(chat_id, title, description, payload, provider_token, start_parameter, currency, prices) return 'WAITING PAYMENT'
def shipping_callback(update: Update, context: CallbackContext): query = update.shipping_query if query.invoice_payload != 'Custom-Payload': query.answer(ok=False, error_message="Что-то сломалось.") options = list() options.append( ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)])) price_list = [LabeledPrice('B1', 150), LabeledPrice('B2', 200)] options.append(ShippingOption('2', 'Shipping Option B', price_list)) query.answer(ok=True, shipping_options=options)
class TestShippingOption: id_ = 'id' title = 'title' prices = [ LabeledPrice('Fish Container', 100), LabeledPrice('Premium Fish Container', 1000) ] def test_slot_behaviour(self, shipping_option, recwarn, mro_slots): inst = shipping_option for attr in inst.__slots__: assert getattr(inst, attr, 'err') != 'err', f"got extra slot '{attr}'" assert not inst.__dict__, f"got missing slot(s): {inst.__dict__}" assert len(mro_slots(inst)) == len(set( mro_slots(inst))), "duplicate slot" inst.custom, inst.id = 'should give warning', self.id_ assert len(recwarn) == 1 and 'custom' in str( recwarn[0].message), recwarn.list def test_expected_values(self, shipping_option): assert shipping_option.id == self.id_ assert shipping_option.title == self.title assert shipping_option.prices == self.prices def test_to_dict(self, shipping_option): shipping_option_dict = shipping_option.to_dict() assert isinstance(shipping_option_dict, dict) assert shipping_option_dict['id'] == shipping_option.id assert shipping_option_dict['title'] == shipping_option.title assert shipping_option_dict['prices'][0] == shipping_option.prices[ 0].to_dict() assert shipping_option_dict['prices'][1] == shipping_option.prices[ 1].to_dict() def test_equality(self): a = ShippingOption(self.id_, self.title, self.prices) b = ShippingOption(self.id_, self.title, self.prices) c = ShippingOption(self.id_, '', []) d = ShippingOption(0, self.title, self.prices) e = Voice(self.id_, 'someid', 0) assert a == b assert hash(a) == hash(b) assert a is not b assert a == c assert hash(a) == hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def test_equality(self): a = InputInvoiceMessageContent( self.title, self.description, self.payload, self.provider_token, self.currency, self.prices, ) b = InputInvoiceMessageContent( self.title, self.description, self.payload, self.provider_token, self.currency, self.prices, max_tip_amount=100, provider_data='foobar', ) c = InputInvoiceMessageContent( self.title, self.description, self.payload, self.provider_token, self.currency, # the first prices amount & the second lebal changed [LabeledPrice('label1', 24), LabeledPrice('label22', 314)], ) d = InputInvoiceMessageContent( self.title, self.description, 'different_payload', self.provider_token, self.currency, self.prices, ) e = InputTextMessageContent('text') assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def test_equality(self): a = LabeledPrice('label', 100) b = LabeledPrice('label', 100) c = LabeledPrice('Label', 101) d = Location(123, 456) assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d)
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)
def buy_callback(update, context): query = update.callback_query command, count_str = query.data.split('_') count = int(count_str) ok = (command == 'topup') print('Command: [{}]'.format("BUY : %s in chat %s" % (int(count), query.message.chat.id))) query.answer(ok) if not ok: return chat_id = query.message.chat.id title = 'Квота на публикацию обьявлений' description = 'Fusion Club Ukraine' payload = count_str token = get_pay_token() start_parameter = 'test-payment' currency = 'UAH' prices = [ LabeledPrice("Пополнение квоты x %d" % count, count * QUOTA_PRICE * 100) ] context.bot.send_invoice(chat_id, title, description, payload, token, start_parameter, currency, prices)
def parse_items(self): with open('items.json') as f: items = json.load(f) shopping_cart = [] for item in items: shopping_cart.append(LabeledPrice(item["name"], item["price"])) return shopping_cart
def send_payment_invoice( update: Update, context: CallbackContext, query: CallbackQuery, ): if query is None: message = update.effective_message label = message.text else: message = query.message label = query.data _ = set_lang(update, context) chat_id = message.chat_id title = _("Support PDF Bot") description = _("Say thanks to PDF Bot and help keep it running") price = PAYMENT_DICT[label] prices = [LabeledPrice(re.sub(r"\s\(.*", "", label), price * 100)] context.bot.send_invoice( chat_id, title, description, PAYMENT_PAYLOAD, STRIPE_TOKEN, CURRENCY, prices, max_tip_amount=1000, suggested_tip_amounts=[100, 300, 500, 1000], )
def send_payment_invoice(update, context, query=None, amount=None): if query is None: message = update.effective_message label = message.text else: message = query.message label = query.data _ = set_lang(update, context) chat_id = message.chat_id title = _("Support PDF Bot") description = _("Say thanks to PDF Bot and help keep it running") if amount is None: price = PAYMENT_DICT[label] else: label = CUSTOM price = amount prices = [LabeledPrice(re.sub(r"\s\(.*", "", label), price * 100)] context.bot.send_invoice( chat_id, title, description, PAYMENT_PAYLOAD, STRIPE_TOKEN, PAYMENT_PARA, CURRENCY, prices, )
def test_answer_shipping_query_ok(self, monkeypatch, bot): # For now just test that our internals pass the correct data def test(_, url, data, *args, **kwargs): return data == { 'shipping_query_id': 1, 'ok': True, 'shipping_options': [{ 'title': 'option1', 'prices': [{ 'label': 'price', 'amount': 100 }], 'id': 1 }] } monkeypatch.setattr('telegram.utils.request.Request.post', test) shipping_options = ShippingOption(1, 'option1', [LabeledPrice('price', 100)]) assert bot.answer_shipping_query(1, True, shipping_options=[shipping_options])
def start_without_shipping_callback(update, context): chat_id = update.message.chat_id p_obj = Students.objects.filter(student_id=chat_id, payment=None) if p_obj.count() < 1: update.message.reply_text('Вы еще не добавлены ни в одну группу.') return None p_obj = p_obj.last() p_obj.payment = Transactions.objects.create( student=p_obj.student, group=p_obj.group, amount=100, status=False, end_date=p_obj.group.first_date + timedelta(days=30)) p_obj.save() 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 = "381764678:TEST:12473" start_parameter = "test-payment" currency = "RUB" # price in dollars price = 100 # 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 start_with_shipping_callback(update: Update, context: CallbackContext): chat_id = update.effective_user.id title = "Оплата пиццы" description = "Оплата пиццы из ресторана DDOS PIZZA" payload = "Custom-Payload" provider_token = os.getenv('TRANZZO_TOKEN') start_parameter = "test-payment" currency = "RUB" price_delivery = context.user_data.get("price_delivery") pizza_cost = context.user_data.get("pizza_cost") price = pizza_cost + price_delivery prices = [LabeledPrice("Test", price * 100)] 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 callback(self, bot, update): query = update.callback_query user = bot_models.TelegramUser.get_user(query.from_user) data = self.get_callback_data(query.data) basket = bot_models.Basket.get_basket_by_id(data.get('basket_id', 0)) title = "Оплата за книги" description = "Оплата за книги на суму {}, для отримання доступу до книг.".format( basket.total_price) provider_data = {'user_id': user.id, 'basket_id': basket.id} price = int(basket.total_price * 100) prices = [LabeledPrice("Ціна оплати", price if price else 100)] query.edit_message_text("Очікується оплата на суму {} грн.".format( basket.total_price), reply_markup=keyboards.clear_inline) bot.send_invoice(query.message.chat_id, title, description, paypal.payload, paypal.provider_token, paypal.start_parameter, paypal.currency, prices, provider_data=provider_data) return True
def send_payment_invoice(update, context, amount=None): message = update.effective_message if message.chat.type in (Chat.GROUP, Chat.SUPERGROUP): message.reply_text("I've PM you the invoice.", reply_markup=ReplyKeyboardRemove()) chat_id = message.from_user.id title = f"Support {BOT_NAME}" description = f"Say thanks to {BOT_NAME} and help keep it running" if amount is None: label = message.text price = PAYMENT_DICT[message.text] else: label = PAYMENT_CUSTOM price = amount prices = [LabeledPrice(re.sub(r"\s\(.*", "", label), price * 100)] context.bot.send_invoice( chat_id, title, description, PAYMENT_PAYLOAD, STRIPE_TOKEN, PAYMENT_PARA, PAYMENT_CURRENCY, prices, )
def pay(update, context): chat_id = update.message.chat_id title = "Payment Example" description = "Payment example" payload = "Custom-Payload" provider_token = config.PROVIDER_TOKEN start_parameter = "test-payment" currency = "USD" price = 1 prices = [LabeledPrice("Test", price * 100)] 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_with_shipping_callback(update: Update, context: CallbackContext) -> None: """Sends an invoice with shipping-payment.""" 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" 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, currency, prices, need_name=True, need_phone_number=True, need_email=True, need_shipping_address=True, is_flexible=True, )
def start_with_shipping_callback(bot, update): 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 = "498721541:AAHd_9T23zJw7IwaUkrZd7FmoVkHQmE8ZLQ" start_parameter = "test-payment" currency = "USD" # price in dollars price = 1 # price * 100 so as to include 2 d.p. # 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 bot.sendInvoice(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 test_answer_shipping_query_errors(self, monkeypatch, bot): shipping_options = ShippingOption(1, 'option1', [LabeledPrice('price', 100)]) with pytest.raises( TelegramError, match='should not be empty and there should not be'): bot.answer_shipping_query(1, True, error_message='Not enough fish') with pytest.raises( TelegramError, match='should not be empty and there should not be'): bot.answer_shipping_query(1, False) with pytest.raises( TelegramError, match='should not be empty and there should not be'): bot.answer_shipping_query(1, False, shipping_options=shipping_options) with pytest.raises( TelegramError, match='should not be empty and there should not be'): bot.answer_shipping_query(1, True)
class TestShippingOption: id = 'id' title = 'title' prices = [ LabeledPrice('Fish Container', 100), LabeledPrice('Premium Fish Container', 1000) ] def test_expected_values(self, shipping_option): assert shipping_option.id == self.id assert shipping_option.title == self.title assert shipping_option.prices == self.prices def test_to_json(self, shipping_option): json.loads(shipping_option.to_json()) def test_to_dict(self, shipping_option): shipping_option_dict = shipping_option.to_dict() assert isinstance(shipping_option_dict, dict) assert shipping_option_dict['id'] == shipping_option.id assert shipping_option_dict['title'] == shipping_option.title assert shipping_option_dict['prices'][0] == shipping_option.prices[ 0].to_dict() assert shipping_option_dict['prices'][1] == shipping_option.prices[ 1].to_dict() def test_equality(self): a = ShippingOption(self.id, self.title, self.prices) b = ShippingOption(self.id, self.title, self.prices) c = ShippingOption(self.id, '', []) d = ShippingOption(0, self.title, self.prices) e = Voice(self.id, 0) assert a == b assert hash(a) == hash(b) assert a is not b assert a == c assert hash(a) == hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def shipping_callback(update: Update, context: CallbackContext) -> None: """Answers the ShippingQuery with ShippingOptions""" 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 # First option has a single LabeledPrice options = [ ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)]) ] # second option has 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)
async def shipping_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Answers the ShippingQuery with ShippingOptions""" query = update.shipping_query # check the payload, is this from your bot? if query.invoice_payload != "Custom-Payload": # answer False pre_checkout_query await query.answer(ok=False, error_message="Something went wrong...") return # First option has a single LabeledPrice options = [ ShippingOption("1", "Shipping Option A", [LabeledPrice("A", 100)]) ] # second option has an array of LabeledPrice objects price_list = [LabeledPrice("B1", 150), LabeledPrice("B2", 200)] options.append(ShippingOption("2", "Shipping Option B", price_list)) await query.answer(ok=True, shipping_options=options)
class TestShippingOption: id_ = "id" title = "title" prices = [LabeledPrice("Fish Container", 100), LabeledPrice("Premium Fish Container", 1000)] def test_slot_behaviour(self, shipping_option, mro_slots): inst = shipping_option for attr in inst.__slots__: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" def test_expected_values(self, shipping_option): assert shipping_option.id == self.id_ assert shipping_option.title == self.title assert shipping_option.prices == self.prices def test_to_dict(self, shipping_option): shipping_option_dict = shipping_option.to_dict() assert isinstance(shipping_option_dict, dict) assert shipping_option_dict["id"] == shipping_option.id assert shipping_option_dict["title"] == shipping_option.title assert shipping_option_dict["prices"][0] == shipping_option.prices[0].to_dict() assert shipping_option_dict["prices"][1] == shipping_option.prices[1].to_dict() def test_equality(self): a = ShippingOption(self.id_, self.title, self.prices) b = ShippingOption(self.id_, self.title, self.prices) c = ShippingOption(self.id_, "", []) d = ShippingOption(0, self.title, self.prices) e = Voice(self.id_, "someid", 0) assert a == b assert hash(a) == hash(b) assert a is not b assert a == c assert hash(a) == hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def invoice(bot, update): bot.send_invoice(chat_id=update.message.chat_id, title="title", description="description", payload="payload", provider_token="6037603760376037", start_parameter="", currency="IRR", prices=[LabeledPrice('label1', int(update.message.text))]) return PAYMENT
def donate(update, context, debug=False): chat_id = update.effective_chat.id text = update.message.text blog.info( f'Donation by user #{update.effective_user.id} in chat #{update.effective_chat.id}:' f' user wants to pay ${text}') enabled = _donate_info.test_enabled if debug else _donate_info.enabled payload = _donate_info.test_payload if debug else _donate_info.payload provider_token = _donate_info.test_provider_token if debug else _donate_info.provider_token start_parameter = _donate_info.test_start_parameter if debug else _donate_info.start_parameter assert enabled try: price = float(text.replace(',', '.')) except ValueError: blog.info( f'Donation by user #{update.effective_user.id} in chat #{update.effective_chat.id}:' f' invalid price: ${text}') update.message.reply_text('Эй, такого числа нет! Попробуйте снова') return AMOUNT if price < 1: blog.info( f'Donation by user #{update.effective_user.id} in chat #{update.effective_chat.id}:' f' price too low: ${text}') update.message.reply_text( 'Слишком маленькая сумма, мы принимает донаты от $1. Попробуйте снова!' ) return AMOUNT elif price > 10000: blog.info( f'Donation by user #{update.effective_user.id} in chat #{update.effective_chat.id}:' f' price too high: ${text}') update.message.reply_text( 'Ого, какотелей большой! Мы принимаем максимум $10,000. Попробуйте снова!' ) return AMOUNT title = "Уря, донатик!" description = "Проспонсируйте оплату сервера и кофе голодающему автору бота" currency = "USD" # price * 100 so as to include 2 decimal points prices = [LabeledPrice("Donate", int(price * 100))] blog.info( f'Donation by user #{update.effective_user.id} in chat #{update.effective_chat.id}:' f' sending invoice...') context.bot.send_invoice(chat_id, title, description, payload, provider_token, start_parameter, currency, prices) return ConversationHandler.END
def start_without_shipping(bot, update, price): chat_id = update.callback_query.message.chat.id title = f"Payment_{chat_id}" description = "Оплатите пиццу и мы сразу же начнем ее готовить :3" payload = f"Custom_Payload" provider_token = os.getenv('PAYMENT_TOKEN') start_parameter = f"Payment_{chat_id}" currency = "RUB" prices = [LabeledPrice("Test", price * 100)] bot.sendInvoice(chat_id, title, description, payload, provider_token, start_parameter, currency, prices)
def handle_payment(update, context): chat_id = update.message.chat_id amount = moltin.get_cart_total_sum(chat_id) currency = 'RUB' title = "Payment Example" description = "Payment Example using python-telegram-bot" payload = "Custom-Payload" provider_token = os.getenv('TELEGRAM_PAYMENTS_TOKEN') start_parameter = "test-payment" prices = [LabeledPrice("Test", int(amount['amount']))] context.bot.sendInvoice(chat_id, title, description, payload, provider_token, start_parameter, currency, prices)
def send_invoice(bot, update, job_queue): chat_id = update.callback_query.message.chat_id title = "Оплата за пиццу" description = "Тестовая оплата за пиццу" payload = "Custom-Payload" provider_token = os.getenv('TRANZZO_API') start_parameter = "test-payment" currency = "RUB" price = int(float(get_total_price(chat_id).replace(' ', '')) * 100) prices = [LabeledPrice("Test", price)] bot.sendInvoice(chat_id, title, description, payload, provider_token, start_parameter, currency, prices)
def register(bot, update): user = update.message.from_user logger.info(LogMessage.register.format(user)) bot.send_invoice(chat_id=update.message.chat_id, title=InvoiceData.title, description=InvoiceData.description, payload="payload", provider_token=InvoiceConfig.provider_token, start_parameter="", currency=InvoiceData.currency, prices=[LabeledPrice('label1', InvoiceConfig.amount)]) return BotState.pay
def test_equality(self): a = Invoice('invoice', 'desc', 'start', 'EUR', 7) b = Invoice('invoice', 'desc', 'start', 'EUR', 7) c = Invoice('invoices', 'description', 'stop', 'USD', 8) d = LabeledPrice('label', 5) assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d)