Telegram Stars ⭐️ 支払いを Python ボットに統合

WBOY
リリース: 2024-08-27 06:06:02
オリジナル
653 人が閲覧しました

今日は、Telegram の内部通貨である Telegram Stars ⭐️ を使用してボットで支払いを設定する方法を説明します。

ステップ 1: ボットを作成する

まず、BotFather を使用してボットを作成します。このプロセスに慣れている場合は、独自のテスト ボットを使用できます。この例では、ボット @repeats_bot を使用します。

Integrating Telegram Stars ⭐️ Payment in a Python Bot

ステップ 2: プロジェクト構造を準備する

プロジェクト構造の例を次に示します:

TelegramStarsBot (root)
|-img/
  |-img-X9ptcIuiOMICY0BUQukCpVYS.png
|-bot.py
|-config.py
|-database.py
|-.env
ログイン後にコピー

ステップ 3: ボットコード

bot.py

import telebot
from telebot import types
from config import TOKEN
from database import init_db, save_payment
import os

bot = telebot.TeleBot(TOKEN)

# Initialize the database
init_db()

# Function to create a payment keyboard
def payment_keyboard():
    keyboard = types.InlineKeyboardMarkup()
    button = types.InlineKeyboardButton(text="Pay 1 XTR", pay=True)
    keyboard.add(button)
    return keyboard

# Function to create a keyboard with the "Buy Image" button
def start_keyboard():
    keyboard = types.InlineKeyboardMarkup()
    button = types.InlineKeyboardButton(text="Buy Image", callback_data="buy_image")
    keyboard.add(button)
    return keyboard

# /start command handler
@bot.message_handler(commands=['start'])
def handle_start(message):
    bot.send_message(
        message.chat.id,
        "Welcome! Click the button below to buy an image.",
        reply_markup=start_keyboard()
    )

# Handler for the "Buy Image" button press
@bot.callback_query_handler(func=lambda call: call.data == "buy_image")
def handle_buy_image(call):
    prices = [types.LabeledPrice(label="XTR", amount=1)]  # 1 XTR
    bot.send_invoice(
        call.message.chat.id,
        title="Image Purchase",
        description="Purchase an image for 1 star!",
        invoice_payload="image_purchase_payload",
        provider_token="",  # For XTR, this token can be empty
        currency="XTR",
        prices=prices,
        reply_markup=payment_keyboard()
    )

# Handler for pre-checkout queries
@bot.pre_checkout_query_handler(func=lambda query: True)
def handle_pre_checkout_query(pre_checkout_query):
    bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)

# Handler for successful payments
@bot.message_handler(content_types=['successful_payment'])
def handle_successful_payment(message):
    user_id = message.from_user.id
    payment_id = message.successful_payment.provider_payment_charge_id
    amount = message.successful_payment.total_amount
    currency = message.successful_payment.currency

    # Send a purchase confirmation message
    bot.send_message(message.chat.id, "✅ Payment accepted, please wait for the photo. It will arrive soon!")

    # Save payment information to the database
    save_payment(user_id, payment_id, amount, currency)

    # Send the image
    photo_path = 'img/img-X9ptcIuiOMICY0BUQukCpVYS.png'
    if os.path.exists(photo_path):
        with open(photo_path, 'rb') as photo:
            bot.send_photo(message.chat.id, photo, caption="?Thank you for your purchase!?")
    else:
        bot.send_message(message.chat.id, "Sorry, the image was not found.")

# /paysupport command handler
@bot.message_handler(commands=['paysupport'])
def handle_pay_support(message):
    bot.send_message(
        message.chat.id,
        "Purchasing an image does not imply a refund. "
        "If you have any questions, please contact us."
    )

# Start polling
bot.polling()
ログイン後にコピー

config.py

import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Get values from environment variables
TOKEN = os.getenv('TOKEN')
DATABASE = os.getenv('DATABASE')
ログイン後にコピー

データベース.py

import sqlite3
from config import DATABASE

def init_db():
    with sqlite3.connect(DATABASE) as conn:
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS payments (
                user_id INTEGER,
                payment_id TEXT,
                amount INTEGER,
                currency TEXT,
                PRIMARY KEY (user_id, payment_id)
            )
        ''')
        conn.commit()

def save_payment(user_id, payment_id, amount, currency):
    with sqlite3.connect(DATABASE) as conn:
        cursor = conn.cursor()
        cursor.execute('''
            INSERT INTO payments (user_id, payment_id, amount, currency)
            VALUES (?, ?, ?, ?)
        ''', (user_id, payment_id, amount, currency))
        conn.commit()
ログイン後にコピー

コードの説明

Telegram Stars での支払い

  • payment_keyboard と start_keyboard は、ユーザー操作のためのボタンを作成します。最初のボタンで支払いが可能になり、2 番目のボタンで画像の購入が開始されます。
  • handle_buy_image は、XTR 通貨を使用した支払いのための請求書を作成して送信します。ここで、XTR はトークンを必要としないため、provider_token は空にすることができます。
  • handle_pre_checkout_query と handle_payment_payment は、支払いの検証と確認のプロセスを処理します。
  • 支払いが成功すると、ボットはユーザーに画像を送信し、支払い情報をデータベースに保存します。

データベースの操作

  • init_db は支払いテーブルが存在しない場合に作成します。このテーブルには、ユーザー、支払い、金額、通貨に関する情報が保存されます。
  • save_payment は、支払い情報をデータベースに保存します。これは、払い戻しや取引レポートの可能性のために必要です。

重要な注意事項

  • ボット所有者の支払い: ボット所有者がボット内で購入を行おうとしても、購入は完了しません。これにより、管理者による詐欺や誤った購入が防止されます。
  • スターの管理: スターは Telegram ボット内に保存されます。残高を表示するには、Telegram のボット設定に移動し、[ボットの管理] を選択して、[残高] をクリックします。ここでは、獲得したスターを表示および管理したり、スターを引き出したり、広告に費やしたりできます。

Integrating Telegram Stars ⭐️ Payment in a Python Bot

Integrating Telegram Stars ⭐️ Payment in a Python Bot

Integrating Telegram Stars ⭐️ Payment in a Python Bot

Integrating Telegram Stars ⭐️ Payment in a Python Bot

結論

これで、ボットは Telegram Stars 経由で支払いを受け入れ、購入が成功した後に画像を送信するように設定されました。構成ファイル内のすべての設定とデータが正しいことを確認してください。

反応やコメントを残していただけると嬉しいです!完全なソース コードは GitHub で見つけることもできます。

以上がTelegram Stars ⭐️ 支払いを Python ボットに統合の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!