为什么这段代码会弹出不同的错误?

问题描述 投票:0回答:1

机器人不断弹出随机错误,最终可能会完全停止工作。这是怎么回事?

import telebot
import keyboards as kb
import basedata as bd

id_TC = 6265540894

token = '6733560372:AAH-cBQegSoixNvA6thSX5_Jl8P2I8iW0s'
bot = telebot.TeleBot(token)

print(bot.get_me().username)

if bd.select_information('admin', 'user', id_TC).fetchone() == None:
    bd.add_admin(id_TC, 2, '123123')

@bot.message_handler(commands=['start']) #Обработчик старта
def start_command(msg):
    if bd.select_information('user', 'user', msg.from_user.id).fetchone() == None:
        bd.add_information('user', 'user', msg.from_user.id)
    if bd.select_information('user', 'language', msg.from_user.id).fetchone()[0] == None:
        bot.send_message(msg.from_user.id, 'Your language?', reply_markup=kb.language)
    else:
        if bd.select_information('user', 'language', msg.from_user.id).fetchone()[0] == 'USA':
            bot.send_message(msg.from_user.id, '👄Welcome to our bot - helper. If you would like to contact a member from the site, fill out the application form and she will write to you soon!', reply_markup=kb.application('Leave a request'))
        elif bd.select_information('user', 'language', msg.from_user.id).fetchone()[0] == 'Itali':
            bot.send_message(msg.from_user.id, '👄Benvenuti nel nostro bot - helper. Se vuoi contattare un membro del sito, compila il modulo di richiesta e lei ti scriverà presto!', reply_markup=kb.application('Lasciare una richiesta'))
        elif bd.select_information('user', 'language', msg.from_user.id).fetchone()[0] == 'Turkey':
            bot.send_message(msg.from_user.id, '👄Bot - yardımcımıza hoş geldiniz. Siteden bir üyeyle iletişime geçmek istiyorsanız, başvuru formunu doldurun ve yakında size yazacaktır!', reply_markup=kb.application('Bir istek bırakın'))

@bot.message_handler(commands=['alogin']) #Обработка входа в админку
def admin(msg):
    if bd.select_information('admin', 'user', msg.from_user.id).fetchone() != None:
        if msg.text[8:] == bd.select_information('admin', 'password', msg.from_user.id).fetchone()[0]:
            if bd.select_information('admin', 'lvl_admin', msg.from_user.id).fetchone()[0] == 2:
                bot.send_message(msg.from_user.id, f'💎{msg.from_user.first_name} вы вошли в админ панель, выберите нужный параметр\n\n🧸Ваш lvl: {bd.select_information("admin", "lvl_admin", msg.from_user.id).fetchone()[0]}', reply_markup=kb.admin_menu_TC)
            elif bd.select_information('admin', 'lvl_admin', msg.from_user.id).fetchone()[0] == 1:
                bot.send_message(msg.from_user.id, f'💎{msg.from_user.first_name} вы вошли в админ панель, выберите нужный параметр\n\n🧸Ваш lvl: {bd.select_information("admin", "lvl_admin", msg.from_user.id).fetchone()[0]}', reply_markup=kb.admin_menu_support)

@bot.callback_query_handler(func=lambda call:True) #Обработчик калл-бэка
def callback(call):
    #Языки
    print(call.data)
    if 'language' in call.data:
        bd.edit_information('user', 'language', call.data.split('_')[1], call.from_user.id)
        start_command(call)

    #Заявка
    if call.data == 'application':
        if bd.select_information('заявки', 'user', call.from_user.id).fetchone() == None:
            bd.add_information('заявки', 'user', call.from_user.id)
            if bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'USA':
                what = bot.send_message(call.from_user.id, 'Enter a name')
                bot.register_next_step_handler(what, name)
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Itali':
                what = bot.send_message(call.from_user.id, 'Inserire un nome')
                bot.register_next_step_handler(what, name)
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Turkey':
                what = bot.send_message(call.from_user.id, 'Bir ad girin')
                bot.register_next_step_handler(what, name)
        else:
            if bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'USA':
                bot.send_message(call.from_user.id, '✖You`re already sending an application', reply_markup=kb.cancel('Cancellation'))
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Itali':
                bot.send_message(call.from_user.id, '✖ State già inviando una candidatura', reply_markup=kb.cancel('Cancellazione'))
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Turkey':
                bot.send_message(call.from_user.id, '✖Halihazırda bir başvuru gönderiyorsunuz', reply_markup=kb.cancel('İptal'))

    elif 'product' in call.data:
        if bd.select_information('заявки', 'user', call.from_user.id).fetchone() != None:
            if call.data.split('_')[1] == 'трусики':
                bd.edit_information('заявки', 'product', 'Ношеные трусики', call.from_user.id)
            elif call.data.split('_')[1] == 'секс':
                bd.edit_information('заявки', 'product', 'Виртуальный секс', call.from_user.id)
            elif call.data.split('_')[1] == 'Интим':
                bd.edit_information('заявки', 'product', 'Интим видео/фото', call.from_user.id)
            
            if bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'USA':
                bot.send_message(call.from_user.id, 'Great! Click " submit application " and a member will contact you shortly in private messages!', reply_markup=kb.final('Send request'))
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Itali':
                bot.send_message(call.from_user.id, 'Ottimo! Clicca su "invia la candidatura" e il partecipante ti contatterà a breve in messaggi privati!', reply_markup=kb.final('Invia la richiesta'))
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Turkey':
                bot.send_message(call.from_user.id, 'Harika! "Başvuru gönder "e tıklayın ve katılımcı kısa süre içinde sizinle özel mesaj yoluyla iletişime geçecektir!', reply_markup=kb.final('İstek gönder'))
        else:
            bot.delete_message(call.message.chat.id, call.message.message_id)

    elif call.data == 'final':
        if bd.select_information('заявки', 'user', call.from_user.id).fetchone() != None:
            if bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'USA':
                bot.edit_message_text('Application successfully sent', call.from_user.id, call.message.message_id)
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Itali':
                bot.edit_message_text('Richiesta inviata con successo', call.from_user.id, call.message.message_id)
            elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Turkey':
                bot.edit_message_text('Başvuru başarıyla gönderildi', call.from_user.id, call.message.message_id)
            for i in bd.all_select_information('admin', 'user').fetchall():
                bot.send_message(i[0], f'⚠Новая заявка:\n\n🎱UserName: @{bot.get_chat(call.from_user.id).username}\n👑Имя/url: {bd.select_information("заявки", "name", call.from_user.id).fetchone()[0]}\n💎Товар: {bd.select_information("заявки", "product", call.from_user.id).fetchone()[0]}\n\n', reply_markup=kb.accept_types(str(call.from_user.id)))
        else:
            bot.delete_message(call.message.chat.id, call.message.message_id)

    elif call.data == 'cancel':
        bd.delete_information('заявки', call.from_user.id)
        if bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'USA':
            bot.send_message(call.from_user.id, 'The application was canceled', reply_markup=kb.application('Resend'))
        elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Itali':
            bot.send_message(call.from_user.id, 'La domanda è stata annullata', reply_markup=kb.application('Reinvio'))
        elif bd.select_information('user', 'language', call.from_user.id).fetchone()[0] == 'Turkey':
            bot.send_message(call.from_user.id, 'Başvuru iptal edildi', reply_markup=kb.application('Yeniden Gönder'))

    #Админка принятие заказа и тд
    elif 'accept' in call.data:
        if bd.select_information('заявки', 'user', call.data.split('_')[1]).fetchone() != None:
            bot.send_message(call.data.split('_')[1], 'Ваш заказ взялся в обработку, в ближайшее время вам ответят на сайте')
            bot.send_message(call.from_user.id, 'Вы взяли заказ в обработку')
            bot.send_message(id_TC, f'Воркер @{call.from_user.username} взялся за заказ @{bot.get_chat(call.data.split("_")[1]).username}')
            bd.edit_stats('stats', bd.all_select_information('stats', 'stats').fetchone()[0] + 1)
            bd.delete_information('заявки', call.from_user.id)
        else:
            bot.edit_message_text('Кто то уже взял этот заказ в обработку🙄', call.from_user.id, call.message.message_id)

    #Админ панель
    elif call.data == 'add_support':
        add = bot.send_message(call.from_user.id, '🎠Введите все нужные параментры через запятую:\n🎀id будующего support, лвл админа (1 - support, 2 - заместитель), будующий пароль\n\n🥽Пример: 1234567890, 2, fetishist_na_spermu_v_trusah')
        bot.register_next_step_handler(add, add_suport)
    elif call.data == 'del_support':
        delete = bot.send_message(call.from_user.id, '🎠Введите:\nid support')
        bot.register_next_step_handler(delete, delete_support)
    elif call.data == 'stats':
        bot.send_message(call.from_user.id, f'Всего было принято заявок: {bd.all_select_information("stats", "stats").fetchone()[0]}')
    elif call.data == 'all_message':
        all_message = bot.send_message(call.from_user.id, 'Введите нужное сообщение для рассылки напишите     "-" для отмены')
        bot.register_next_step_handler(all_message, delete_support)

    def name(msg): #Тут получение имени участницы
    bd.edit_information('заявки', 'name', msg.text, msg.from_user.id)
    print(bd.select_information('user', 'language', msg.from_user.id).fetchone()[0])
    if bd.select_information('user', 'language', msg.from_user.id).fetchone()[0] == 'USA':
        bot.send_message(msg.from_user.id, 'What service/good are you interested in? (Can be changed by clicking on another product)', reply_markup=kb.products('dirty panties,' 'Virtual Sex', 'Intimate Video or Photo'))
    elif bd.select_information('user', 'language', msg.from_user.id).fetchone()[0] == 'Itali':
        bot.send_message(msg.from_user.id, 'A quale servizio/bene siete interessati? (Può essere cambiato   cliccando su un altro prodotto)', reply_markup=kb.products('Mutande consumate', 'Sesso virtuale', 'Video o    foto intime'))
    elif bd.select_information('user', 'language', msg.from_user.id).fetchone()[0] == 'Turkey':
        bot.send_message(msg.from_user.id, 'Hangi hizmet/mal ile ilgileniyorsunuz? (Başka bir ürüne     tıklayarak değiştirilebilir)', reply_markup=kb.products('Yıpranmış külotlar', 'Sanal Seks', 'Samimi Video veya Fotoğraf'))

    def add_suport(msg): #Тут выдача прав
    params = msg.text.replace(' ', '').split(',')
    if len(params) == 3:
        if params[0].isdigit() and params[1].isdigit():
            bd.add_admin(params[0], params[1], params[2])
            bot.send_message(msg.from_user.id, f'✔Новый support был добавлен в базу данных (Для входа      /alogin {params[2]})')
        else:
            bot.send_message(msg.from_user.id, '✖Значение id и lvl должно быть численым')
    else:
        bot.send_message(msg.from_user.id, '✖Вы ввели не достаточно/много аргументов')
    def delete_support(msg): #Тут удаление суппорта
    if msg.text.isdigit():
        if bd.select_information('admin', 'user', msg.text).fetchone() != None:
            bot.send_message(msg.from_user.id, '✔Support был успешно удален с базы данных')
            bd.delete_information('admin', msg.text)
        else:
            bot.send_message(msg.from_user.id, '✖Данный пользователь отсутствует в списке админов')
    else:
        bot.send_message(msg.from_user.id, '✖id должно быть численым значением')
    def delete_support(msg): #Тут рассылка
    if msg.text == '-':
        start_command(msg)
    else:
        for i in bd.all_select_information('user', 'user').fetchall():
            try:
                bot.send_message(i[0], msg.text)
            except:
                print('Пользователь заблокировал бота')

    bot.polling()

抱歉,我不知道,我雇了一个承包商,付了钱,但他不知道机器人出了什么问题。

python telegram python-telegram-bot telethon py-telegram-bot-api
1个回答
0
投票

这些函数的代码似乎格式不正确。这是代码的修订版本,修复了缩进并正确定义了嵌套函数:

def name(msg):
    bd.edit_information('заявки', 'name', msg.text, msg.from_user.id)
    language = bd.select_information('user', 'language', msg.from_user.id).fetchone()[0]

    if language == 'USA':
        bot.send_message(msg.from_user.id, 'What service/good are you interested in? (Can be changed by clicking on another product)', reply_markup=kb.products('dirty panties', 'Virtual Sex', 'Intimate Video or Photo'))
    elif language == 'Itali':
        bot.send_message(msg.from_user.id, 'A quale servizio/bene siete interessati? (Può essere cambiato cliccando su un altro prodotto)', reply_markup=kb.products('Mutande consumate', 'Sesso virtuale', 'Video o foto intime'))
    elif language == 'Turkey':
        bot.send_message(msg.from_user.id, 'Hangi hizmet/mal ile ilgileniyorsunuz? (Başka bir ürüne tıklayarak değiştirilebilir)', reply_markup=kb.products('Yıpranmış külotlar', 'Sanal Seks', 'Samimi Video veya Fotoğraf'))

def add_support(msg):
    params = msg.text.replace(' ', '').split(',')
    if len(params) == 3:
        if params[0].isdigit() and params[1].isdigit():
            bd.add_admin(params[0], params[1], params[2])
            bot.send_message(msg.from_user.id, f'✔Новый support был добавлен в базу данных (Для входа /alogin {params[2]})')
        else:
            bot.send_message(msg.from_user.id, '✖Значение id и lvl должно быть численным')
    else:
        bot.send_message(msg.from_user.id, '✖Вы ввели не достаточно/много аргументов')

def delete_support(msg):
    if msg.text.isdigit():
        if bd.select_information('admin', 'user', msg.text).fetchone() is not None:
            bot.send_message(msg.from_user.id, '✔Support был успешно удален с базы данных')
            bd.delete_information('admin', msg.text)
        else:
            bot.send_message(msg.from_user.id, '✖Данный пользователь отсутствует в списке админов')
    else:
        bot.send_message(msg.from_user.id, '✖id должно быть численным значением')

def send_message_to_all_users(msg):
    if msg.text == '-':
        start_command(msg)
    else:
        for user_id in bd.all_select_information('user', 'user').fetchall():
            try:
                bot.send_message(user_id[0], msg.text)
            except:
                print('Пользователь заблокировал бота')

在此修订版中,我调整了缩进并正确分离了这些函数,确保它们定义正确并且可以在主代码中调用而不会出现问题。

对于一般格式和缩进的代码来说,Python 比其他语言更重要。

我还建议不要公开显示您的令牌,我建议编辑帖子并在字符串值中使用“#在此处插入令牌值”减去“”进行注释

© www.soinside.com 2019 - 2024. All rights reserved.