D
D
Daniil Igumenshev2022-04-20 23:01:24
Python
Daniil Igumenshev, 2022-04-20 23:01:24

The 'Yes' button and the 'No' button do not work in the telegram bot, and could you give advice on how to improve it?

Код из файла бота ниже


import random
import sqlite3
import re
from tracemalloc import stop
from xml.etree.ElementTree import Comment
from payments import Database
from aiogram import Bot, types
from aiogram.types import CallbackQuery
from aiogram.dispatcher import Dispatcher, FSMContext
from aiogram.utils import executor
from config import TOKEN, Qiwi_token
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher.filters import Text
from keyboard import payment_kb, search_kb, buy_menu, yes_no_kb
from aiogram.types.message import ContentType


db = Database('payments.db')
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)

def is_number(_str):
    try:
        int(_str)
        return True
    except ValueError:
        return False

#Тут добавляем пользователя в БД
@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
    if message.chat.type == 'private':
        if not db.user_exists(message.from_user.id):
            db.add_user(message.from_user.id)
    await bot.send_message (message.from_user.id, f'Добро пожаловать в наш телеграмм бот для поиска плохих гостей! Напишите <b>Проверить гостя!</b>\nВаш баланс: <b>{db.user_money(message.from_user.id)} ₸.</b>',reply_markup=search_kb, parse_mode=types.ParseMode.HTML)
#Поиск по бд номера телефона    
@dp.message_handler(text=['Проверить гостя'])
async def process_search_command(message: types.Message):
    await message.reply ('Введите номер гостя ниже! <b>В форме +7xxxxxxxxx</b>. <u>Пример: +77052223333</u>. Без знаков и пробелов!', reply_markup=types.ReplyKeyboardRemove(), parse_mode=types.ParseMode.HTML)
    @dp.message_handler()
    async def process_search_command(message: types.Message):
        if re.search (r'^((\+7)+([0-9]){10})$', message.text) != None:
            global nomer
            nomer = str(message.text)
            print (nomer)
            if db.search_sql(nomer) == True:
                await message.reply ('<b>Гость был найден!</b>', reply_markup=payment_kb, parse_mode=types.ParseMode.HTML)
            else:
                await message.reply ('<b>Гостя нет в базе данных</b>, <u>хотите ли добавить?!</u>', reply_markup=yes_no_kb, parse_mode=types.ParseMode.HTML)
        else:
            await message.reply ('<b>Номер введён не корректно!</b>', parse_mode=types.ParseMode.HTML)
        return
#Проблемные кнопки
@dp.message_handler(text=['yes_btn'])
async def adding_number (message: types.Message):
    await message.reply('<b>Напишите описание ниже!</b>',  parse_mode=types.ParseMode.HTML)
    str(nomer)
    @dp.message_handler()
    async def same (message: types.Message):
        des = str(message.text)
        db.add_description(des)
        await message.answer('<b>Гость был добавлен!</b>', parse_mode=types.ParseMode.HTML)
@dp.message_handler(text = ['no_btn'])
async def cancel (message: types.Message):
    await message.reply('Возврат к поиску!', reply_markup=types.ReplyKeyboardRemove())
    return                     

Ниже функции БД и в принципе работа БД


class Database:
    def __init__ (self, db_file):
        self.connection = sqlite3.connect(db_file)
        self.cursor = self.connection.cursor()

   def add_number(self,number):
        with self.connection:
            return self.cursor.execute('INSERT INTO `weirdguests` (`number`) VALUES(?)', (number,))

    def add_description(self,description):
        with self.connection:
            return self.cursor.execute('INSERT INTO `weirdguests` (`description`) VALUES(?)', (description,))
    
    def search_sql(self, number):
        with self.connection:
            for number, in self.cursor.execute('SELECT number FROM weirdguests WHERE number LIKE (?)', (number,)):
                return True

Клавиатуры ниже

from re import search
from aiogram.types import ReplyKeyboardRemove, \
    ReplyKeyboardMarkup, KeyboardButton, \
    InlineKeyboardMarkup, InlineKeyboardButton

payment_btn = InlineKeyboardButton('Получить описание и фотографии!', callback_data='payment_btn')
payment_kb = InlineKeyboardMarkup().add(payment_btn)

yes_btn = InlineKeyboardButton('Да!', callback_data='yes_btn')
no_btn = InlineKeyboardButton('Нет.', callback_data='no_btn')
yes_no_kb = InlineKeyboardMarkup().add(yes_btn, no_btn)



search_kb = ReplyKeyboardMarkup(resize_keyboard=True)
search_btn = ['Проверить гостя']
search_kb.add(*search_btn)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2022-04-20
@senku1435

To process inline button presses, another decorator is used
https://github.com/aiogram/aiogram/blob/dev-2.x/ex...

def is_number(_str):
    try:
        int(_str)
        return True
    except ValueError:
        return False

String method isdigit ?
For some reason, the function inside the function is declared again
Global variables in the multi-user
FSM application from the aiogram should be used, or db, since there is a
return at the end of the function, it is also not clear why
nomer = str(message.text)
This is the line anyway

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question