Ошибка TypeError: string indices must be integers. Python
Пишу бота, который собирает данные с Telegram профиля пользователя. Вот блок кода с которым возникли проблемы.
DATABASE_FILE = 'user_profiles.json'
def load_user_profiles():
try:
with open(DATABASE_FILE, 'r') as file:
return json.load(file)
except FileNotFoundError:
return []
def save_user_profiles(user_profiles):
with open(DATABASE_FILE, 'w') as file:
json.dump(user_profiles, file, indent=4)
@dp.message_handler(commands=['start'])
async def start(msg: types.Message):
user_profiles = load_user_profiles()
user_id = str(msg.from_user.id)
profile = next((user for user in user_profiles if user['user_id'] == user_id), None)
if profile:
# Пользователь уже есть в базе данных, обновляем данные
profile['username'] = msg.from_user.username
profile['profile_link'] = f"https://telegram.me/{msg.from_user.username}"
profile['phone_number'] = msg.from_user.phone_number or None
else:
# Новый пользователь, добавляем профиль в базу данных
profile = {
'user_id': user_id,
'username': msg.from_user.username,
'profile_link': f"https://telegram.me/{msg.from_user.username}",
'phone_number': msg.from_user.phone_number or None
}
user_profiles.append(profile)
save_user_profiles(user_profiles)
После команды /start
терминал выдает ошибку TypeError: string indices must be integers
ссылаясь на profile = next((user for user in user_profiles if user['user_id'] == user_id), None)
Помогите в решении данной задачи.
Источник: Stack Overflow на русском