TelegramWalletPay

Форк
0
/
02_telegram_bot.py 
89 строк · 2.6 Кб
1
import asyncio
2
import logging
3
import sys
4
from os import getenv
5
from uuid import uuid4
6

7
# install popular Telegram Bot API framework:
8
#   pip install aiogram
9
from aiogram import Bot, Dispatcher, Router, html
10
from aiogram.enums import ParseMode
11
from aiogram.types import InlineKeyboardButton, Message
12
from aiogram.utils.keyboard import InlineKeyboardBuilder
13

14
# install Telegram Wallet Pay API client library:
15
#   pip install telegram-wallet-pay
16
from telegram_wallet_pay import TelegramWalletPay
17
from telegram_wallet_pay.enums import ButtonName
18

19
# store TELEGRAM_BOT_API_TOKEN to your .env
20
# bot token can be issued via https://t.me/BotFather
21
TELEGRAM_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/
25
TELEGRAM_WALLET_PAY_TOKEN = getenv("TELEGRAM_WALLET_PAY_TOKEN")
26

27
# message handlers should be attached to the Router, so let's create it
28
router = Router()
29

30

31
@router.message()
32
async def message_handler(message: Message, wallet: TelegramWalletPay) -> None:
33
    """Handle any received message."""
34
    # prepare answer text
35
    header = html.bold("Welcome to Telegram Wallet API example")
36
    body = "Click on the button below to make payment"
37

38
    # create an order
39
    wallet_response = await wallet.create_order(
40
        amount=4.2,
41
        currency_code="USD",
42
        description="Example payment description",
43
        external_id=str(uuid4()),
44
        timeout_seconds=5 * 60,
45
        customer_telegram_user_id=message.from_user.id,
46
    )
47
    order = wallet_response.data
48

49
    # prepare keyboard
50
    keyboard = InlineKeyboardBuilder()
51
    wallet_button = InlineKeyboardButton(
52
        text=ButtonName.PAY_VIA_WALLET,
53
        url=order.pay_link,
54
    )
55
    keyboard.add(wallet_button)
56

57
    # send answer message with prepared content and keyboard markup
58
    await message.answer(
59
        text=f"{header}\n{body}",
60
        reply_markup=keyboard.as_markup(),
61
        parse_mode=ParseMode.HTML,
62
    )
63

64

65
async def main() -> None:
66
    """Set up and run bot application."""
67
    # create wallet client
68
    wallet = TelegramWalletPay(TELEGRAM_WALLET_PAY_TOKEN)
69

70
    # create dispatcher and pass wallet client to every bot handler
71
    dp = Dispatcher(wallet=wallet)
72

73
    # include router with handlers
74
    dp.include_router(router)
75

76
    # initialize Bot instance
77
    bot = Bot(TELEGRAM_BOT_API_TOKEN)
78

79
    # start polling Telegram Bot API
80
    try:
81
        await dp.start_polling(bot)
82
    finally:  # gracefully close sessions on stop
83
        await wallet.close()
84
        await bot.session.close()
85

86

87
if __name__ == "__main__":
88
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
89
    asyncio.run(main())
90

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.