0

Я пишу своего бота на telebot. Если я быстро нажму несколько раз на кнопку то бот будет отвечать кучей сообщений. Пример: Нажатие на кнопку несколько раз Бот отвечает на 1 нажатие после

Код:

import telebot
import pymysql
import requests
from random import *
import json



tovarii=[]
files_n=[]
count_tov=[]
price_tov=[]
notes=[]

admin_id=''
def zagr(name,price,fname,note):
    con = pymysql.connect('host', 'hse', 'fea', 'zopa')
    cur = con.cursor()
    sql = """INSERT INTO tovars(name, count, price, fname, note)
   VALUES ('"""+name+"', 1, "+str(price)+", '"+fname+"', '"+note+"')"

    cur.execute(sql)
    con.commit()
    con.close()
def get_tov():
    sql = "SELECT * FROM tovars \
    WHERE name > '%d'" % (1000)
    tovarii.clear()
    count_tov.clear()
    price_tov.clear()
    files_n.clear()
    notes.clear()
    con = pymysql.connect('rel.com', 'iNfmdq','zQN', 'iNIq')
    cur = con.cursor()
    cur.execute(sql)
    results = cur.fetchall()
    for row in results:
        print(row)
        if int(row[1])==0:
            continue
        tovarii.append(row[0])
        count_tov.append(row[1])
        price_tov.append(row[2])
        files_n.append(row[3])
        notes.append(row[4])
    con.close()
def add_new_us(chatid):
    con = pymysql.connect('rmyggm', 'iNuq', 'zogghN', 'iNghgbluq')
    cur = con.cursor()
    sql = "SELECT * FROM users"
    cur.execute(sql)
    results = cur.fetchall()
    estv=0
    for row in results:
        if str(row[0])==str(chatid):
            estv=1
    if estv==0:
        sql = """INSERT INTO users(chaid) VALUES ('"""+chatid+"')"
        cur.execute(sql)
        con.commit()
        con.close()
        print('Added')
    else:
        con.close()
        print('User have in baza')
st_kanala= ['creator', 'administrator', 'member']
bot = token

adm_men=telebot.types.ReplyKeyboardMarkup(True, True,
                                                                                   True, True)
adm_men.row('Добавить товар 💼','Рассылка 🔔')
adm_men.row('Назад ◀')
@bot.message_handler(commands=['start'])
def start_message(message):
    add_new_us(str(message.chat.id))
    if bot.get_chat_member(chat_id='@qechannel', user_id=message.from_user.id).status in st_kanala:
        if str(message.chat.id)==admin_id:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)

            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')
        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id, 'hi',reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
    else:
        bot.send_message(message.chat.id, 'Подпишитесь на канал @qechannel')
@bot.message_handler(content_types=['text'])
def send_text(message):
    if bot.get_chat_member(chat_id='@qechannel', user_id=message.from_user.id).status in st_kanala:
        bot.send_message(message.chat.id, 'Извините я вас не понел 😕')
        if str(message.chat.id)==admin_id:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')
        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id, 'Главное меню',reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
    else:
        bot.send_message(message.chat.id, 'Подпишитесь на канал @qechannel')


key3 = telebot.types.ReplyKeyboardMarkup(True, True)
key3.row('Купить ✅','Отмена ➖')

key_o= telebot.types.ReplyKeyboardMarkup(True)
key_o.row('Отмена ➖')
key2= telebot.types.ReplyKeyboardMarkup(True)
def main_func(message):
    if message.text =='Помощь ❗':
        bot.send_message(message.chat.id, 'Для покупки товаров нажмите на кнопку „Товары 📦“. Выберите интересующий вас товар, и следуйте инструкциям бота')
        bot.register_next_step_handler(message,main_func)
    if message.text=='Товары 📦':
        key2= telebot.types.ReplyKeyboardMarkup(True)
        del key2
        key2= telebot.types.ReplyKeyboardMarkup(True)
        get_tov()
        for txt in tovarii:
            key2.row(txt)
        bot.send_message(message.chat.id,'Выберите товар из списка :', reply_markup=key2)
        bot.register_next_step_handler(message,tovari)
    if message.text=='Админка 🔑':
        bot.send_message(message.chat.id,'Здравствуйте Администратор! Выберите опцию:', reply_markup=adm_men)
        bot.register_next_step_handler(message,adm_panel)
def tovari(message):
    global id_it
    global xas
    global naj
    global path_file
    if message.text in tovarii:
        id_it=tovarii.index(message.text)
        xas=price_tov[id_it]
        naj=message.text
        path_file=files_n[id_it]
        bot.send_message(message.chat.id,'📦 Товар: '+message.text+'\n'+'💲 Цена: '+str(price_tov[id_it])+' руб'+'\n'+'📜 Описание: '+ notes[id_it],reply_markup=key3)
        bot.send_message(message.chat.id,'Вы уверены что хотите купить "'+message.text+'"?')
        bot.register_next_step_handler(message,dn)
key1 = telebot.types.ReplyKeyboardMarkup(True, True)
def adm_panel(message):
    if message.text=='Назад ◀':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')
        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
    if message.text=='Добавить товар 💼':
        bot.send_message(message.chat.id,'Введите имя товара: ',reply_markup=key_o)
        bot.register_next_step_handler(message,nameoftov)
    if message.text=='Рассылка 🔔':
        bot.send_message(message.chat.id,'Введите текст рассылки: : ',reply_markup=key_o)
        bot.register_next_step_handler(message,rasslk) 
ras_m=telebot.types.ReplyKeyboardMarkup(True, True)
ras_m.row('Разослать 📊', 'Отмена ➖')
def rasslk(message):
    global erur
    if message.text=='Отмена ➖':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')
        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
        return 0
    elif message.text=='Разослать 📊':
        con = pymysql.connect('refdnemysql', 'ihfnduq', 'zondddnN', 'iNndnsndm21uq')
        cur = con.cursor()
        sql = "SELECT * FROM users"
        cur.execute(sql)
        results = cur.fetchall()
        for row in results:
            bot.send_message(int(row[0]),erur)
        con.close()
        bot.send_message(message.chat.id,'Рассылка успешно запущена!')
        return 0
    bot.send_message(message.chat.id,'Текст:')
    erur=message.text
    bot.send_message(message.chat.id,message.text,reply_markup=ras_m)
    bot.register_next_step_handler(message,rasslk)
def nameoftov(message):
    global tov_naz
    if message.text=='Отмена ➖':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')

        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
        return 0
    tov_naz=message.text
    bot.send_message(message.chat.id,'Введите цену товара: ',reply_markup=key_o)
    bot.register_next_step_handler(message,sena)
def sena(message):
    global tov_sena

    if message.text=='Отмена ➖':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')

        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
        return 0
    try:
        tov_sena=int(message.text)
    except:
        bot.send_message(message.chat.id,'Введите ЧИСЛО без слов и тд.')
        bot.register_next_step_handler(message,sena)
        return 0
    bot.send_message(message.chat.id,'Введите описание товара: ',reply_markup=key_o)
    bot.register_next_step_handler(message,opis)
def opis(message):
    global tov_opis
    if message.text=='Отмена ➖':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')

        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
        return 0
    tov_opis=message.text

    bot.send_message(message.chat.id,'Отправте файл товара: ',reply_markup=key_o)
    bot.register_next_step_handler(message,opfile)
addt = telebot.types.ReplyKeyboardMarkup(True, True)
addt.row('Выставить ✅')
addt.row('Изменить данные 📝')
addt.row('Отмена ➖')
def opfile(message):
    global src
    if message.text=='Отмена ➖':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары ??','Помощь ❗')
            key1.row('Админка 🔑')

        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
        return 0
    try:
        d_id=message.document.file_id
    except:
        bot.send_message(message.chat.id,'Отправте ФАЙЛ который содержит товар', reply_markup=key_o)
        bot.register_next_step_handler(message,opfile)
    else:
        chat_id = message.chat.id
        file_info = bot.get_file(d_id)
        downloaded_file = bot.download_file(file_info.file_path)
        src = 'tovars/'+message.document.file_name;
        filenas=open(src, 'w')
        filenas.close()
        with open(src, 'wb') as new_file:
            new_file.write(downloaded_file)
        new_file.close()
        bot.send_message(chat_id,'Пожалуйста, проверьте правильность ввода данных об товаре:')
        bot.send_message(chat_id,'📦 Название: '+tov_naz+'\n'+'💰 Цена: '+str(tov_sena)+'\n'+'📜 Описание: '+tov_opis, reply_markup=addt)
        bot.register_next_step_handler(message,opre)
# tov=message.text
    #bot.send_message(message.chat.id,'Введите цену товара: ',reply_markup=key_o)
    #bot.register_next_step_handler(message,sena)
def opre(message):
    if message.text=='Выставить ✅':
        zagr(tov_naz,tov_sena,src,tov_opis)
        if message.text=='Отмена ➖':
            if str(message.chat.id)==admin_id:
                key1=0
                del key1
                key1 = telebot.types.ReplyKeyboardMarkup(True, True)
                key1.row('Товары 📦','Помощь ❗')
                key1.row('Админка 🔑')    
            else:
                key1 = telebot.types.ReplyKeyboardMarkup(True, True)
                key1.row('Товары 📦','Помощь ❗')
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')    
        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Товар успешно добавлен ✅', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
    elif message.text=='Изменить данные 📝':
        bot.send_message(message.chat.id,'Введите имя товара: ',reply_markup=key_o)
        bot.register_next_step_handler(message,nameoftov)
    elif message.text == 'Отмена ➖':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')

        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
keyboard = telebot.types.InlineKeyboardMarkup()
callback_button = telebot.types.InlineKeyboardButton(text="Проверить платеж ✅", callback_data="check")
keyboard.add(callback_button)

def dn(message):
    global chatx
    global rnd_n
    if message.text=='Отмена ➖':
        if str(message.chat.id)==admin_id:
            key1=0
            del key1
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
            key1.row('Админка 🔑')
        else:
            key1 = telebot.types.ReplyKeyboardMarkup(True, True)
            key1.row('Товары 📦','Помощь ❗')
        bot.send_message(message.chat.id,'Операция отменена ❎', reply_markup=key1)
        bot.register_next_step_handler(message,main_func)
    if message.text=='Купить ✅':
        rnd_n=randint(100000, 999999)
        chatx=message.chat.id
        QIWI_ACCOUNT='+7000000200'
        bot.send_message(message.chat.id,'Для оплаты, переведите на '+QIWI_ACCOUNT+'💲'+'\n'+'Сумму: '+str(price_tov[id_it])+'\n'+'С коментарием: '+str(rnd_n), reply_markup=keyboard)
        bot.send_message(message.chat.id, str(rnd_n))
@bot.callback_query_handler(func=lambda call: True)
def query_handler(call):
     if call.data == 'check':
        ity=1
        s = requests.Session()
        QIWI_TOKEN='token'
        QIWI_ACCOUNT='700000000'
        s.headers['authorization'] = 'Bearer ' + QIWI_TOKEN  
        parameters = {'rows': '15'}
        h = s.get('https://edge.qiwi.com/payment-history/v1/persons/'+ QIWI_ACCOUNT +'/payments', params = parameters)
        req= json.loads(h.text)
        for i in range(len(req['data'])):
            if 1==1:
                if str(req['data'][i]['comment']) == str(rnd_n):
                    if str(req['data'][i]['sum']['amount']) == str(xas):
                        ity=0
        print(req['data'][i]['comment'])
        print(req['data'][i]['sum']['amount'])
        if ity==0:
            bot.send_message(chatx, 'Спасибо за покупку! Ваш товар:')
            sql="DELETE FROM tovars WHERE name = '"+naj+"';"
            con = pymysql.connect('alex.com', 'luq', 'QN', 'uq')
            cur = con.cursor()
            cur.execute(sql)
            con.commit()
            con.close()
            doc = open(path_file, 'rb')
            bot.send_document(chatx, doc)

        else:
            bot.send_message(chatx, 'Невижу оплату')
        print(req)
bot.polling(none_stop=True) 
3
  • В чём ваш вопрос?
    – CrazyElf
    13 апр 2020 в 14:37
  • Я не хочу чтобы бот выводил несколько сообщений 13 апр 2020 в 15:39
  • поставьте bool и ловите повторное нажатие
    – JopaBoga
    13 апр 2020 в 18:16

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.