Good day,Everyone
I am trying to build a telegram bot that fetchs all rows from database and shows message by 5 rows in tg bot with next page inline_keybord
here is my code
from aiogram import Bot, Dispatcher, executor, types
import mysql.connector as connector
from config import TOKEN_API
bot = Bot(TOKEN_API)
dp = Dispatcher(bot)
conn = connector.connect(
database = 'awesugn_products',
host = 'localhost',
username = 'root',
password = 'root'
)
cursor = conn.cursor()
def construct_keyboard(data: tuple, page: int) -> types.InlineKeyboardMarkup:
length=len(data)
kb={'inline_keyboard': []}
buttons=[]
if page > 1: #preventing going to -1 page
buttons.append({'text':'<-', 'callback_data':f'page_{page-1}'})
#adding a neat page number
buttons.append({'text':f'{page}/{length}', 'callback_data':'none'})
if page < length: #preventing going out of range
buttons.append({'text':'->', 'callback_data':f'page_{page+1}'})
kb['inline_keyboard'].append(buttons)
return kb
@dp.message_handler(commands='start')
async def start (message: types.Message):
cursor.execute("SELECT product_name, discount_price, regualar_price FROM discount_products")
objs = cursor.fetchall()
json_data = []
for obj in objs:
json_data.append({
"product_name" : obj[0],
"discount_price" : obj[1],
"regualar_price" : obj[2]
})
await message.answer(json_data[0], reply_markup=construct_keyboard(objs, 1))
@dp.callback_query_handler(text_startswith='page_')
async def page(call: types.CallbackQuery):
page=int(call.data.split('_')[1])
cursor.execute("SELECT product_name, discount_price, regualar_price FROM discount_products")
objs = cursor.fetchall()
json_data = []
for obj in objs:
json_data.append({
"product_name" : obj[0],
"discount_price" : obj[1],
"regualar_price" : obj[2]
})
await bot.send_message(call.message.chat.id, json_data[page - 1], reply_markup=construct_keyboard(objs, page))
if __name__ == "__main__":
executor.start_polling(dp)
my code is working like this in tg bot
I want see the result in beautiful content with bold labels and display by 5 rows on each page on telegram bot.
for example:
**product_name**: banana 240 kg
**discount_price**: 21990
**regualar_price**: 31990
**product_name**: biscuit 10 kg
**discount_price**: 21990
**regualar_price**: 31990
in this example I showed by 2 rows in message, how to display message like this with 5 rows in each message and with next page inline_keyboard where there bulk of rows are fetched from database?
