L
L
LulzLoL2312018-11-18 17:59:49
Python
LulzLoL231, 2018-11-18 17:59:49

Why does the "'NoneType' object is not callable" error occur?

The user enters variables (query, where) to search the local database, the code searches the ResID in the database using the passed variables, and displays the information received to the user. So it turns out that more than one ResID may appear in the database during the search, and the user is given brief information about an entry in the database, and asks you to select the right one, and while if 1 ResID is given when entering variables, everything goes perfectly, and the entry is shown, but if more than 1 entry falls out, Python recognizes in the function (func4) "NoneType" object , and an exception is thrown, which I still don’t understand the problem, I experimentally found out that func4 and if 1 ResID, and if more than one is - NoneType, but in the 1st case it is successfully executed, and in the 2nd it is no longer I don't understand what the problem is, please help!
Probable part of the code with an error:

def func0(message):
    global where
    global resID
    sumresid = func1(query, where)  # Возвращает ВСЕ найденные resID
    if len(sumresid) > 1:
        bot.send_message(message.chat.id, 'Info:')
        bot.send_message(message.chat.id, 'Results: ' + str(len(sumssid)))
        bot.register_next_step_handler(message, IPMO(message, sumresid))  # если найдено больше 1 resID, передаёт список функции IPMO которая показывает все найденные записи, и даёт выбрать нужную пользователю.
    else:
        resID = func2(query, where)  # Если найден был только 1 resID, возвращает resID
        compRes(message)

def IPMO(message, listOfresID):
    sumresid = listOfresID
    num = 0
    while True:
        print('DEBUG: sumResID: ' + str(sumresid))
        if str(sumresid) == '[]':
            print('DEBUG: IF construct (str(sumresid) == "[]") is Called!')
            bot.send_message(message.chat.id, 'Choice profile (enter resID):')
            bot.register_next_step_handler(message, IPMO_Choice)
            break
        print('DEBUG: While is Working!')
        readyResID = sumresid[0]  # Берёт 1 ResID из списка
        resultuple = func3(readyResID)  # Возвращает tuple с данными по ResID
        resid = resultuple[0]
        var1 = resultuple[1]
        var2 = resultuple[2]
        var3 = resultuple[3]
        bot.send_message(message.chat.id, '[ ! ]: Result #' + str(num))
        bot.send_message(message.chat.id, 'ResID: ' + ssid)
        bot.send_message(message.chat.id, 'Var1: ' + var1)
        bot.send_message(message.chat.id, 'Var2: ' + var2)
        bot.send_message(message.chat.id, 'Var3: ' + var3)
        num = num + 1
        sumresid.remove(sumresid[0])

def IPMO_Choice(message):
    print('DEBUG: Called local func: IPMO_Choice')
    global ResID
    ResID = message.text
    debugCheckResID()
    compRes(message)

def debugCheckResID():
    # Придумана чисто для теста
    print('DEBUG: Called local func: debugCheckResID')
    print('DEBUG: Selected ResID: ' + ResID)

def compRes(message):
    print('DEBUG: Called local func: compRes')
    print('DEBUG: Type of func Func5: ' + str(type(mainInfoResult())))  # Результат: DEBUG: Type of func Func4: <class 'NoneType'>
    bot.send_message(message.chat.id, 'ResID found! (' + ResID + ')')
    bot.send_message(message.chat.id, 'Compiling result...')
    Func4()
    bot.send_message(message.chat.id, 'Func4...COMPILED!')

This is the Traceback that returns:
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/telebot/util.py", line 59, in run
    task(*args, **kwargs)
TypeError: 'NoneType' object is not callable"
Traceback (most recent call last):
  File "bot.py", line 1587, in <module>
    bot.polling(none_stop=True, timeout=60)
  File "/usr/local/lib/python3.5/dist-packages/telebot/__init__.py", line 389, in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "/usr/local/lib/python3.5/dist-packages/telebot/__init__.py", line 413, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "/usr/local/lib/python3.5/dist-packages/telebot/util.py", line 108, in raise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "/usr/lib/python3/dist-packages/six.py", line 686, in reraise
    raise value
  File "/usr/local/lib/python3.5/dist-packages/telebot/util.py", line 59, in run
    task(*args, **kwargs)
TypeError: 'NoneType' object is not callable

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slavon93, 2018-11-19
@Slavon93

I have never written bots, but I will try to send:
Here, as far as I understand from the documentation, the second argument is callback. Apparently, this should be a pointer to a function that will be run when the message arrives. If you specify the function as you specified, you pass the return value there, and in your case it will be None, since it does not return anything, respectively, the bot will try to run None and you will get the error that you received.
If you look here (link to the Github bot) , you will see

# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
    msg = bot.reply_to(message, """\
Hi there, I am Example bot.
What's your name?
""")
    bot.register_next_step_handler(msg, process_name_step)


def process_name_step(message):
    try:
        chat_id = message.chat.id
        name = message.text
        user = User(name)
        user_dict[chat_id] = user
        msg = bot.reply_to(message, 'How old are you?')
        bot.register_next_step_handler(msg, process_age_step)
    except Exception as e:
        bot.reply_to(message, 'oooops')

Here, firstly, the callback line is set
bot.register_next_step_handler(msg, process_name_step)
and secondly, the process_name_step function itself takes message as an argument, that is, the message that was sent to the bot, and then all the information is taken from it.
In short, most likely, you need in the func0 function , as soon as you realize that the ID is greater than one, send messages to the user with information about the found IDs and wait for a response. When the answer comes, callback IMP0 will work with the message argument, from which it will become clear what exactly the user wants, and then your standard response processing.
Well, it’s probably worth saying that it would be better, of course, not to spam a bunch of messages to the user for each ID, but to form one message with all found IDs and send it to the user, and then wait for a response to it, since the message argument , which comes first in bot.register_next_step_handler - this, judging by the docs, is the message to which a response is expected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question