Certainly! Below is an example of how you can create a simple Telegram bot using aiogram to display products from a file (goods.txt), and allow users to make payments.
This example requires:
- A
goods.txt file where each line contains the item name and price separated by a comma.
- You will need to replace
'YOUR_BOT_TOKEN' and 'YOUR_PAYMENT_PROVIDER_TOKEN' with your bot's token and payment provider token respectively.
First, ensure you have the necessary dependencies installed:
pip install aiogram
Now, here is the Python script for the bot:
import logging
import csv
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import LabeledPrice, InputFile, InlineKeyboardButton, InlineKeyboardMarkup
from aiogram.utils.callback_data import CallbackData
API_TOKEN = 'YOUR_BOT_TOKEN'
PAYMENT_PROVIDER_TOKEN = 'YOUR_PAYMENT_PROVIDER_TOKEN'
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
callback_data_factory = CallbackData("item", "name", "price")
# Read the goods from goods.txt
def load_goods():
goods = []
with open('goods.txt', 'r') as f:
reader = csv.reader(f)
for row in reader:
name, price = row
goods.append((name, int(float(price) * 100))) # Convert to smallest currency unit
return goods
goods = load_goods()
@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
await message.reply("Welcome to our shop! Use /shop to see our goods.")
@dp.message_handler(commands=['shop'])
async def show_goods(message: types.Message):
markup = InlineKeyboardMarkup(row_width=1)
for name, price in goods:
item_button = InlineKeyboardButton(
text=f"{name} - ${price / 100:.2f}",
callback_data=callback_data_factory.new(name=name, price=price)
)
markup.add(item_button)
await message.reply("Select an item to purchase:", reply_markup=markup)
@dp.callback_query_handler(callback_data_factory.filter())
async def handle_item_purchase(call: types.CallbackQuery, callback_data: dict):
item_name = callback_data['name']
item_price = int(callback_data['price'])
prices = [LabeledPrice(label=item_name, amount=item_price)]
await bot.send_invoice(
call.from_user.id,
title=item_name,
description=f"Purchase {item_name}",
provider_token=PAYMENT_PROVIDER_TOKEN,
currency='USD',
prices=prices,
payload='invoice-payload'
)
@dp.pre_checkout_query_handler(lambda query: True)
async def process_pre_checkout_query(pre_checkout_query: types.PreCheckoutQuery):
await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)
@dp.message_handler(content_types=types.ContentType.SUCCESSFUL_PAYMENT)
async def process_successful_payment(message: types.Message):
payment_info = message.successful_payment.to_python()
await message.answer(f"Payment successful! Thank you for purchasing {payment_info['invoice_payload']} for ${payment_info['total_amount'] / 100:.2f}.")
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
Step-by-Step Explanation:
-
Dependencies and Configuration:
- Import necessary modules from
aiogram.
- Set your API token and payment provider token.
-
Function to Load Goods:
- Create a function to read goods from
goods.txt, where each line should contain the item name and price separated by a comma.
-
Message Handlers:
- Define message handlers for
/start and /shop commands to greet the user and display goods respectively.
- Generate inline buttons for each item in the goods for users to click.
-
Callback Query Handler:
- Handle item selection and prepare the payment invoice when a user clicks on an item button.
-
Pre-Checkout and Payment Handlers:
- Confirm the checkout query to complete the payment process.
- Inform the user of a successful payment.
Goods File (goods.txt):
An example goods.txt should look like this:
Item1,10.99
Item2,15.49
Item3,20.00
Running the Bot:
- Save the script to a file, e.g.,
shop_bot.py.
- Ensure
goods.txt is in the same directory.
- Run the bot using Python:
python shop_bot.py
This script will set up a Telegram bot that users can interact with to purchase goods listed in goods.txt.