TelegramWalletPay
89 строк · 2.6 Кб
1import asyncio2import logging3import sys4from os import getenv5from uuid import uuid46
7# install popular Telegram Bot API framework:
8# pip install aiogram
9from aiogram import Bot, Dispatcher, Router, html10from aiogram.enums import ParseMode11from aiogram.types import InlineKeyboardButton, Message12from aiogram.utils.keyboard import InlineKeyboardBuilder13
14# install Telegram Wallet Pay API client library:
15# pip install telegram-wallet-pay
16from telegram_wallet_pay import TelegramWalletPay17from telegram_wallet_pay.enums import ButtonName18
19# store TELEGRAM_BOT_API_TOKEN to your .env
20# bot token can be issued via https://t.me/BotFather
21TELEGRAM_BOT_API_TOKEN = getenv("TELEGRAM_BOT_API_TOKEN")22
23# store TELEGRAM_WALLET_PAY_TOKEN to your .env
24# wallet token can be issued via https://pay.wallet.tg/
25TELEGRAM_WALLET_PAY_TOKEN = getenv("TELEGRAM_WALLET_PAY_TOKEN")26
27# message handlers should be attached to the Router, so let's create it
28router = Router()29
30
31@router.message()32async def message_handler(message: Message, wallet: TelegramWalletPay) -> None:33"""Handle any received message."""34# prepare answer text35header = html.bold("Welcome to Telegram Wallet API example")36body = "Click on the button below to make payment"37
38# create an order39wallet_response = await wallet.create_order(40amount=4.2,41currency_code="USD",42description="Example payment description",43external_id=str(uuid4()),44timeout_seconds=5 * 60,45customer_telegram_user_id=message.from_user.id,46)47order = wallet_response.data48
49# prepare keyboard50keyboard = InlineKeyboardBuilder()51wallet_button = InlineKeyboardButton(52text=ButtonName.PAY_VIA_WALLET,53url=order.pay_link,54)55keyboard.add(wallet_button)56
57# send answer message with prepared content and keyboard markup58await message.answer(59text=f"{header}\n{body}",60reply_markup=keyboard.as_markup(),61parse_mode=ParseMode.HTML,62)63
64
65async def main() -> None:66"""Set up and run bot application."""67# create wallet client68wallet = TelegramWalletPay(TELEGRAM_WALLET_PAY_TOKEN)69
70# create dispatcher and pass wallet client to every bot handler71dp = Dispatcher(wallet=wallet)72
73# include router with handlers74dp.include_router(router)75
76# initialize Bot instance77bot = Bot(TELEGRAM_BOT_API_TOKEN)78
79# start polling Telegram Bot API80try:81await dp.start_polling(bot)82finally: # gracefully close sessions on stop83await wallet.close()84await bot.session.close()85
86
87if __name__ == "__main__":88logging.basicConfig(level=logging.INFO, stream=sys.stdout)89asyncio.run(main())90