D
D
Denis2021-11-16 11:35:34
Python
Denis, 2021-11-16 11:35:34

Why doesn't callback_query_handler pyTelegramBotApi work twice?

Hello, I am writing a store bot, and I ran into a problem, I made the issuance function through register_next_step_handler and used inline buttons. When I try to issue access, everything works, but when I try to issue rubles, it does not work. Help

import telebot
import configure
import sqlite3
from telebot import types

client = telebot.TeleBot(configure.config['token'])
db = sqlite3.connect('baza.db', check_same_thread=False)
sql = db.cursor()

#database

sql.execute("""CREATE TABLE IF NOT EXISTS users (id BIGINT, nick TEXT, cash INT, access INT, bought INT)""")
sql.execute("""CREATE TABLE IF NOT EXISTS shop (id INT, name TEXT, price INT, tovar TEXT)""")
db.commit()

@client.message_handler(commands=['start'])
def start(message):
  getname = message.from_user.first_name
  cid = message.chat.id
  uid = message.from_user.id

  sql.execute(f"SELECT id FROM users WHERE id = {uid}")
  if sql.fetchone() is None:
    sql.execute(f"INSERT INTO users VALUES ({uid}, '{getname}', 0, 0, 0)")
    client.send_message(cid, f"Добро пожаловать, {getname}!\nТы попал в администраторский магазин Tucson!")
    db.commit()
  else:
    client.send_message(cid, f"Ты уже зарегистрирован! Пропиши /help чтобы узнать команды.")


@client.message_handler(commands=['profile', 'myinfo', 'myprofile'])
def myprofile(message):
  cid = message.chat.id
  uid = message.from_user.id
  sql.execute(f"SELECT * FROM users WHERE id = {uid}")
  getaccess = sql.fetchone()[3]
  if getaccess == 0:
    accessname = 'Пользователь'
  elif getaccess == 1:
    accessname = 'Администратор'
  elif getaccess == 777:
    accessname = 'Разработчик'
  for info in sql.execute(f"SELECT * FROM users WHERE id = {uid}"):
    client.send_message(cid, f"Твой профиль:\n\nВаш ID: {info[0]}\nБаланс: {info[2]}\nУровень доступа: {accessname}\nКуплено товаров: {info[4]}")

@client.message_handler(commands=['access', 'setaccess', 'dostup'])
def setaccess(message):
  cid = message.chat.id
  uid = message.from_user.id
  sql.execute(f"SELECT * FROM users WHERE id = {uid}")
  getaccess = sql.fetchone()[3]
  accessquery = 777
  if getaccess < accessquery:
    client.send_message(cid, f"⚠️ | У вас нет доступа!")
  else:
    for info in sql.execute(f"SELECT * FROM users WHERE id = {uid}"):
      msg = client.send_message(cid, 'Введите ID пользователя:\nПример: 596060542', parse_mode="Markdown")
      client.register_next_step_handler(msg, access_user_id_answer)

def access_user_id_answer(message):
  cid = message.chat.id
  uid = message.from_user.id
  if message.text == message.text:
    global usridaccess
    usridaccess = message.text
    rmk = types.ReplyKeyboardMarkup(resize_keyboard=True)
    rmk.add(types.KeyboardButton('Пользователь'), types.KeyboardButton('Администратор'), types.KeyboardButton('Разработчик'))
    msg = client.send_message(cid, 'Какой уровень доступа Вы хотите выдать?:', reply_markup=rmk, parse_mode="Markdown")
    client.register_next_step_handler(msg, access_user_access_answer)

def access_user_access_answer(message):
  global accessgaved
  global accessgavedname
  cid = message.chat.id
  uid = message.from_user.id
  rmk = types.InlineKeyboardMarkup()
  access_yes = types.InlineKeyboardButton(text='Да',callback_data='setaccessyes')
  access_no = types.InlineKeyboardButton(text='Нет',callback_data='setaccessno')
  rmk.add(access_yes, access_no)
  for info in sql.execute(f"SELECT * FROM users WHERE id = {usridaccess}"):
    if message.text == "Пользователь":
      accessgavedname = "Пользователь"
      accessgaved = 0
    elif message.text == "Администратор":
      accessgavedname = "Администратор"
      accessgaved = 1
    elif message.text == "Разработчик":
      accessgavedname = "Разработчик"
      accessgaved = 777

    client.send_message(cid, f'Данные для выдачи:\nID пользователя: {usridaccess} ({info[1]})\nУровень доступа: {message.text}\n\nВерно?', reply_markup=rmk)

@client.callback_query_handler(func=lambda call:True)
def access_user_gave_access(call):
  removekeyboard = types.ReplyKeyboardRemove()
  if call.data == 'setaccessyes':
    for info in sql.execute(f"SELECT * FROM users WHERE id = {usridaccess}"):
      sql.execute(f"UPDATE users SET access = {accessgaved} WHERE id = {usridaccess}")
      db.commit()
      client.send_message(call.message.chat.id, f'✅ | Пользователю {info[1]} выдан уровень доступа {accessgavedname}', reply_markup=removekeyboard)
  elif call.data == 'setaccessno':
    client.send_message(call.message.chat.id, f' | Вы отменили выдачу уровня доступа {accessgavedname} пользователю {info[1]}', reply_markup=removekeyboard)
  client.answer_callback_query(callback_query_id=call.id)

@client.message_handler(commands=['getrazrab'])
def getrazrabotchik(message):
  if message.from_user.id == 596060542:
    sql.execute(f"UPDATE users SET access = 777 WHERE id = 596060542")
    client.send_message(message.chat.id, f"✅ | Вы выдали себе Разработчика")
    db.commit()
  else:
    client.send_message(message.chat.id, f"⛔️ | Отказано в доступе!")

@client.message_handler(commands=['giverub', 'givedonate', 'givebal'])
def giverubles(message):
  cid = message.chat.id
  uid = message.from_user.id
  sql.execute(f"SELECT * FROM users WHERE id = {uid}")
  getaccess = sql.fetchone()[3]
  accessquery = 777
  if getaccess < accessquery:
    client.send_message(cid, f"⚠️ | У вас нет доступа!")
  else:
    for info in sql.execute(f"SELECT * FROM users WHERE id = {uid}"):
      msg = client.send_message(cid, 'Введите ID пользователя:\nПример: 596060542', parse_mode="Markdown")
      client.register_next_step_handler(msg, rubles_user_id_answer)

def rubles_user_id_answer(message):
  cid = message.chat.id
  uid = message.from_user.id
  if message.text == message.text:
    global usridrubles
    usridrubles = message.text
    rmk = types.ReplyKeyboardMarkup(resize_keyboard=True)
    rmk.add(types.KeyboardButton('10'), types.KeyboardButton('100'), types.KeyboardButton('1000'), types.KeyboardButton('Другая сумма'))
    msg = client.send_message(cid, 'Выберите сумму для выдачи:', reply_markup=rmk, parse_mode="Markdown")
    client.register_next_step_handler(msg, rubles_user_rubles_answer)

def rubles_user_rubles_answer(message):
  cid = message.chat.id
  uid = message.from_user.id
  global rublesgavedvalue
  rmk = types.InlineKeyboardMarkup()
  access_yes = types.InlineKeyboardButton(text='Да',callback_data='giverublesyes')
  access_no = types.InlineKeyboardButton(text='Нет',callback_data='giverublesno')
  rmk.add(access_yes, access_no)
  for info in sql.execute(f"SELECT * FROM users WHERE id = {usridrubles}"):
    if message.text == '10':
      rublesgavedvalue = 10
    elif message.text == '100':
      rublesgavedvalue = 100
    elif message.text == '1000':
      rublesgavedvalue = 1000
    client.send_message(cid, f'Данные для выдачи:\nID пользователя: {usridrubles} ({info[1]})\nСумма: {rublesgavedvalue}\n\nВерно?',reply_markup=rmk)

@client.callback_query_handler(func=lambda call:True)
def rubles_gave_rubles_user(call):
  removekeyboard = types.ReplyKeyboardRemove()
  if call.data == 'giverublesyes':
    for info in sql.execute(f"SELECT * FROM users WHERE id = {usridrubles}"):
      sql.execute(f"UPDATE users SET cash = {rublesgavedvalue} WHERE id = {usridrubles}")
      db.commit()
      client.send_message(call.message.chat.id, f'✅ | Пользователю {info[1]} выдано {rublesgavedvalue} рублей', reply_markup=removekeyboard)
  elif call.data == 'giverublesno':
    client.send_message(call.message.chat.id, f' | Вы отменили выдачу рублей пользователю {info[1]}', reply_markup=removekeyboard)
  client.answer_callback_query(callback_query_id=call.id)




client.polling(none_stop=True,interval=0)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-11-16
@nosemka

Because among several identical decorators

@client.callback_query_handler(func=lambda call:True)

only the top one works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question