I am making a telegram bot using the telebot library. This function retrieves the city of residence, which was previously selected by the user in the city_living variable, from the SQL3 database.
def get_city_living(user_id: int):
with sqlite3.connect('server.db') as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
city_living TEXT DEFAULT 'null'
)
''')
city = cursor.execute('SELECT city_living FROM users WHERE user_id=?', (user_id,)).fetchone()
return city[0]
if callback.data == 'profile':
user_id=callback.message.from_user.id
kb = types.InlineKeyboardMarkup(row_width=1)
item1 = types.InlineKeyboardButton(text=' Назад в главное меню', callback_data='back1') #back to main menu
name = f' Имя: {callback.from_user.first_name}'
buys = '\n Совершено покупок: ' + str(buy)
cityl = '\n Город: ' + get_city_living(user_id) #City:
kb.add(item1)
bot.edit_message_text(chat_id=callback.message.chat.id, message_id=callback.message.id, text=name+buys+cityl, reply_markup=kb)
Line 129 is the return city[0]
. Why does this error occur? How to fix it?
File "<string>", line 492, in bot_message
File "<string>", line 129, in
get_city_living
TypeError: 'NoneType' object is not
subscriptable
To retrieve some data from the database, you should insert data into the table first. Your function get_city_living() creates the table if it does not exist and retrieves data from the table. But it doesn't insert anything into the table. And I don't see any other code here that would do it.
It looks like you don't have entries in the 'users' table, that's why the function returns None.