0 / 0 / 0
Регистрация: 01.02.2019
Сообщений: 39
1

TypeError: 'NoneType' object is not callable

03.08.2019, 18:08. Показов 11847. Ответов 2
Метки нет (Все метки)

вот код
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# -*- coding: utf-8 -*-
"""
This Example will show you how to use register_next_step handler.
"""
import constants
#!/usr/bin/python
 
# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.
import sqlite3
import telebot
import constants
from telebot import types
 
#Подключение к базе
conn = sqlite3.connect('my.sqlite',check_same_thread=False )
#Создание курсора
c = conn.cursor()
#Функция занесения пользователя в базу
def add_user(userid,username,usersurname,userage,userlongtitude,userlaltitude,photoid):
    c.execute("INSERT INTO users (id,name,surname,aage,longitude,latitude,photoid) VALUES ('%s','%s','%s','%s','%s','%s')"%(userid,username,usersurname,userage,longitude,latitude, photoid))
    conn.commit()
#Вводим данные
id = ''
name = ''
surname = ''
age = ''
global longitude
longitude = ''
global latitude
latitude = ''
print('\n')
#Делаем запрос в базу
print("Список пользователей:\n")
 
c.execute('SELECT * FROM users')
row = c.fetchone()
#выводим список пользователей в цикле
while row is not None:
   print("id:"+str(row[0])+" Логин: "+row[1]+" | Пароль: "+row[2])
   row = c.fetchone()
 
 
 
 
 
API_TOKEN = constants.token
 
bot = telebot.TeleBot(API_TOKEN)
 
@bot.message_handler(commands=['commands'])
def send_welcome(message):
    bot.send_message(message.from_user.id, """
---- \n
     all commands \n
     - /help - о проекте \n
     - /start - главное меню \n
     - /reg - регистрация анкеты \n
----
    """)
 
# Handle '/start' and '/help'
@bot.message_handler(commands=['help'])
def send_welcome(message):
    bot.reply_to(message, """\
    Hi, I'm healthy lifestyle bot. I help you to find any coaches & partners for your training""")
 
@bot.message_handler(commands=['start'])
def handle_start(message):
 
    user_markup = telebot.types.ReplyKeyboardMarkup(True)
    user_markup.row('Поиск пары','Найти тренера')
    user_markup.row('Посмотреть анкету ')
    user_markup.row('Ближайшая открытая тренировка')
    bot.send_message(message.from_user.id, 'Добро пожаловать ', reply_markup=user_markup)
 
 
@bot.message_handler(content_types=['text'])
def start(message):
    conn = sqlite3.connect('my.sqlite', check_same_thread=False)
    # Создание курсора
    c = conn.cursor()
    try:
        c.execute("SELECT * FROM Users WHERE (id = ?) ",
                  (message.from_user.id,))
        FindUsers = c.fetchone()
        permid, permname, permsurname, permage, longitude, latitude, photoid = FindUsers
        IsRegister = True
    except TypeError:
        bot.send_message(message.from_user.id,'Вы ещё не зарегестрированы, пожалуйста создайте анкету /reg')
        IsRegister = False
 
 
    if message.text == 'Посмотреть анкету' or '/reg':
 
        if IsRegister:
            bot.send_message(message.from_user.id, """
                    ---- \n
              Так выглядит твоя анкета:
              
                  Имя - """ + str(permname) + """
                  Фамилия - """ + str(permsurname) + """
                  Возраст - """ + str(permage) + """                  
 
----
                        """)
            bot.send_location(message.from_user.id,latitude,longitude)
            question = 'Хочешь изменить анкету ' + permname + ' ?';
        else:
            question = 'Хочешь создать а анкету?';
        keyboard = types.InlineKeyboardMarkup();  # наша клавиатура
        key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes1');  # кнопка «Да»
        keyboard.add(key_yes);  # добавляем кнопку в клавиатуру
        key_no = types.InlineKeyboardButton(text='Нет', callback_data='no1');
        keyboard.add(key_no);
        global namepromo
        namepromo = message
 
        bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
 
 
 
    else:
        bot.send_message(message.from_user.id, 'для посмотра комманд введите /commands');
 
def get_name(message): #получаем фамилию
    global name;
    name = message.text;
    bot.send_message(message.from_user.id, 'Какая у тебя фамилия?');
    bot.register_next_step_handler(message, get_surname);
 
def get_surname(message):
    global surname;
    surname = message.text;
    bot.send_message(message.from_user.id, 'Сколько тебе лет?');
    bot.register_next_step_handler(message, get_age);
 
def get_age(message):
    global age;
    while True: #проверяем что возраст изменился
        try:
            age = int(message.text)
        except ValueError:
            bot.send_message(message.from_user.id,"Цифрами пожалуйста")
            bot.register_next_step_handler(message, get_age)
            return
 
        if age < 0:
            print("Возраст не может быть отрицательным")
            continue
        else:
            bot.send_message(message.from_user.id, 'Пришли мне своё фото');
            bot.register_next_step_handler(message, geo(message));
            # age was successfully parsed, and we're happy with its value.
            # we're ready to exit the loop.
            break
 
 
def geo(message):
    keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
    button_geo = types.KeyboardButton(text="Отправить местоположение", request_location=True, )
    keyboard.add(button_geo)
    bot.send_message(message.chat.id, "Привет! Нажми на кнопку и передай мне свое местоположение", reply_markup=keyboard)
 
 
@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    if call.data == "yes": #call.data это callback_data, которую мы указали при объявлении кнопки
         #код сохранения данных, или их обработки
        mydata = c.execute("DELETE FROM Users WHERE (id = ?) ",
                  (call.from_user.id,))
        conn.commit()
        id = call.from_user.id
        add_user(id, name, surname, age, longitude, latitude)
        print("""
                    ---- \n
             New/Edit User
                  ID -  """+ str(id) +""" 
                  Name -  """+ str(name) + """
                  Surname - """ + str(surname) + """
                  Age - """ + str(age) + """
                  Location - latitude: %s; longitude: %s """% (latitude, longitude)+ """
 
                    ----
                        """)
        key = telebot.types.ReplyKeyboardMarkup(True, False)
        user_markup = telebot.types.ReplyKeyboardMarkup(True)
        user_markup.row('Поиск пары', 'Найти тренера')
        user_markup.row('Посмотреть анкету ')
        user_markup.row('Ближайшая открытая тренировка')
        bot.send_message(call.from_user.id, 'Запомню)', reply_markup=user_markup)
 
 
    elif call.data == "no":
 
        bot.send_message(call.message.chat.id, 'Мне пофиг, будешь ' + name + ' ' + surname);
 
    if call.data == "yes1":  # call.data это callback_data, которую мы указали при объявлении кнопки
        bot.send_message(call.from_user.id, 'Как тебя зовут?');
        bot.register_next_step_handler(namepromo, get_name);
 
 
 
    elif call.data == "no1":
 
        bot.send_message(call.message.chat.id, 'Хорошо ' + name + ' ' + surname);
 
@bot.message_handler(content_types=['location'])
def location(message):
    if message.location is not None:
        print(message.location)
        print("latitude: %s; longitude: %s" % (message.location.latitude, message.location.longitude))
        global latitude, longitude
        latitude = message.location.latitude
        longitude = message.location.longitude
        user_markup = telebot.types.ReplyKeyboardMarkup(True)
        user_markup.row('Поиск пары', 'Найти тренера')
        user_markup.row('Посмотреть анкету ')
        user_markup.row('Ближайшая открытая тренировка')
        bot.send_message(message.from_user.id, 'Геолокация отправлена.', reply_markup=user_markup)
        keyboard = types.InlineKeyboardMarkup();  # наша клавиатура
        key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes');  # кнопка «Да»
        keyboard.add(key_yes);  # добавляем кнопку в клавиатуру
        key_no = types.InlineKeyboardButton(text='Нет', callback_data='no');
        keyboard.add(key_no);
 
        question = 'Тебе ' + str(age) + ' лет, тебя зовут ' + name + ' ' + surname + '?';
        bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
 
 
bot.polling(none_stop=True, interval=0)
Вот Traceback

2019-08-03 18:00:27,701 (util.py:65 WorkerThread2) ERROR - TeleBot: "TypeError occurred, args=("'NoneType' object is not callable",)
Traceback (most recent call last):
File "C:\Users\tihon\AppData\Local\Programs\Python\Pyth on37-32\lib\site-packages\telebot\util.py", line 59, in run
task(*args, **kwargs)
TypeError: 'NoneType' object is not callable
"
Traceback (most recent call last):
File "C:/Users/tihon/PycharmProjects/TelBotRESET/main.py", line 231, in <module>
bot.polling(none_stop=True, interval=0)
File "C:\Users\tihon\AppData\Local\Programs\Python\Pyth on37-32\lib\site-packages\telebot\__init__.py", line 389, in polling
self.__threaded_polling(none_stop, interval, timeout)
File "C:\Users\tihon\AppData\Local\Programs\Python\Pyth on37-32\lib\site-packages\telebot\__init__.py", line 413, in __threaded_polling
self.worker_pool.raise_exceptions()
File "C:\Users\tihon\AppData\Local\Programs\Python\Pyth on37-32\lib\site-packages\telebot\util.py", line 108, in raise_exceptions
six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
File "C:\Users\tihon\AppData\Local\Programs\Python\Pyth on37-32\lib\site-packages\six.py", line 693, in reraise
raise value
File "C:\Users\tihon\AppData\Local\Programs\Python\Pyth on37-32\lib\site-packages\telebot\util.py", line 59, in run
task(*args, **kwargs)
TypeError: 'NoneType' object is not callable

ошибка где-то в районе @bot.message_handler(content_types=['location']) или def geo(message):
помогите плз
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
03.08.2019, 18:08
Ответы с готовыми решениями:

TypeError: 'int' object is not callable
Начал изучать питон но столкнулся с проблемой. def d(): x=int(input(&quot;Введите: &quot;))...

TypeError: 'list' object is not callable
Только учусь программированию, при написании кода выдают ошибку &quot;TypeError: 'list' object is not...

TypeError: 'module' object is not callable
Помогите, пожалуйста, не понимаю, в чем ошибка. Выводится такая ошибка: Traceback (most recent...

TypeError: object of type 'NoneType' has no len()
Кусок кода(2, который), выводит ошибку(TypeError: object of type 'NoneType' has no len()), решение,...

2
Эксперт Python
5403 / 3827 / 1214
Регистрация: 28.10.2013
Сообщений: 9,554
Записей в блоге: 1
03.08.2019, 22:05 2
В строчке 153 замените geo(message) на просто geo. В этот обработчик судя по документации telebot нужно передавать просто имя функции, а аргументом у нее будет тот самый message, который уже передан.

P.S. Посмотрел исходник кода (в песочнице хабра) с которого этот пример скопипащен - ужасный говнокод.
Кстати сами исходник вовсе не исходник, а тоже скопипиазжщен из примеров самой библиотеки.
Только там пример нормальный, а потом его изгадили всякие говнописатели.

Вывод - читайте оригиналы, а не всякие говнопримеры.
0
0 / 0 / 0
Регистрация: 01.02.2019
Сообщений: 39
03.08.2019, 22:18  [ТС] 3
Garry Galler, Спасибо, очень признателен. И по поводу перепрыгивания через 3-4 ступени. Согласен, но это единственный интересный мне способ изучения)
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
03.08.2019, 22:18
Помогаю со студенческими работами здесь

Max(): TypeError: 'Series' object is not callable
Добрый вечер! Объясните пожалуйста, почему это не работает a=0.1 b=0.2 c=0.3 s= max(s)

Ошибка TypeError: 'int' object is not callable
print(&quot;Введите аргумент вычисляемого выражения: &quot;, end=&quot;&quot;) from math import * a =...

Выдаётся ошибка: TypeError: 'set' object is not callable
#Путь до файла folder = input('Введите полный путь до файла: ') trash_domens =...

TypeError: 'str' object is not callable. Как исправить?
import string file = open(&quot;input.txt&quot;, &quot;r&quot;) db = file.readlines() file.close() file =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru