def load_data():
global users, audio_keys, video_keys, admins, keys
try:
with open("data.json", "r") as f:
users_data = json.load(f)
users = {k: User(**v) for k, v in users_data.items()}
except FileNotFoundError:
users = {}
except TypeError as e:
users = {}
Assistant
try:
with open("audio_keys.json", "r") as f:
audio_keys_data = json.load(f)
audio_keys = {
k: audio_key(v["key"], v["operations"])
for k, v in audio_keys_data.items()
}
except FileNotFoundError:
audio_keys = {}
except TypeError as e:
audio_keys = {}
try:
with open("video_keys.json", "r") as f:
video_keys_data = json.load(f)
video_keys = {
k: video_key(v["key"], v["operations"])
for k, v in video_keys_data.items()
}
keys = [v.key for v in video_keys.values()]
except FileNotFoundError:
video_keys = {}
except TypeError as e:
video_keys = {}
try:
with open("admins.json", "r") as f:
admins = json.load(f)
except FileNotFoundError:
admins = []
except TypeError as e:
admins = []
Функции для сохранения данных в файлы
def save_data(flag):
if flag:
with open("data.json", "w") as f:
json.dump({k: v.to_dict() for k, v in users.items()}, f, indent=4)
else:
with open("audio_keys.json", "w") as f:
json.dump({k: v.to_dict() for k, v in audio_keys.items()}, f, indent=4)
with open("video_keys.json", "w") as f:
json.dump({k: v.to_dict() for k, v in video_keys.items()}, f, indent=4)
with open("admins.json", "w") as f:
json.dump(admins, f, indent=4)
Асинхронная функция для регулярного сохранения users раз в час
async def save_users_periodically():
while True:
save_data(flag=True)
await asyncio.sleep(1800)
async def save_admins():
save_data(flag=False)
async def find_audio_key():
if not audio_keys:
return None
# Найти ключ с минимальным curr_users и максимальным operations
best_key = min(audio_keys.values(), key=lambda k: (k.curr_users, -k.operations))
return best_key.key
async def find_video_key():
if not video_keys:
return None
# Найти ключ с минимальным curr_users и максимальным operations
best_key = min(video_keys.values(), key=lambda k: (k.curr_users, -k.operations))
return best_key.key
def get_user(tgId):
if tgId not in users:
users[tgId] = User(tgId)
return users[tgId]
def set_user(tgId, user):
users[tgId] = user
async def handle_video_request(user_id: int, req_api_instance, extend: bool):
user = get_user(user_id)
req_api_instance.video_header = video_keys[keys[0]].header
req_api_instance.audio_header = audio_keys[keys[0]].header
if req_api_instance:
result = await process_requests(req_api_instance, extend, "30")
final_video_path, updated_req = result
if final_video_path:
print(final_video_path)
video = FSInputFile(final_video_path)
await bot.send_video(user_id, video)
user.req_api_instance = updated_req if not extend else None
set_user(user_id, user)
if extend:
await bot.send_message(
user_id,
text="Панель управления",
reply_markup=get_start_keyboard(user_id),
)
return True
else:
return False
else:
return None
async def handle_video_request_noExtend(user_id: int, req_api_instance):
user = get_user(user_id)
req_api_instance.video_header = video_keys[keys[0]].header
req_api_instance.audio_header = audio_keys[keys[0]].header
if req_api_instance:
result = await process_requests(
req_api_instance, False, str(req_api_instance.duration)
)
final_video_path, updated_req = result
if final_video_path:
print(final_video_path)
video = FSInputFile(final_video_path)
await bot.send_video(user_id, video)
user.req_api_instance = updated_req
set_user(user_id, user)
await bot.send_message(
user_id,
text="Панель управления",
reply_markup=get_start_keyboard(user_id),
)
return True
else:
return False
else:
return None
# Создаем новый запрос reqApi или используем существующий
if not user.req_api_instance or user.req_api_instance == None:
user.req_api_instance = reqApi(user_id, "")
user.req_api_instance.duration = duration
set_user(user_id, user)
await callback.message.edit_text(
"Круто! В каком формате требуется видео?", reply_markup=get_format_keyboard()
)
await callback.answer()
@dp.callback_query(F.data.startswith("format_"))
async def set_format(callback: types.CallbackQuery):
user_id = callback.from_user.id
format_map = {"format_16_9": "16:9", "format_9_16": "9:16", "format_1_1": "1:1"}
format_value = format_map[callback.data]
user = get_user(user_id)
if not user.req_api_instance or user.req_api_instance == None:
user.req_api_instance = reqApi(user_id, "")
user.req_api_instance.screen_format = format_value
set_user(user_id, user)
await callback.message.edit_text(
"Нужно ли аудиосопровождение в ролике?", reply_markup=get_audio_keyboard()
)
await callback.answer()
@dp.callback_query(F.data.startswith("audio_"))
async def set_audio(callback: types.CallbackQuery):
user_id = callback.from_user.id
user = get_user(user_id)
if not user.req_api_instance or user.req_api_instance == None:
user.req_api_instance = reqApi(user_id, "")
if callback.data == "audio_yes":
user.req_api_instance.has_audio = True
elif callback.data == "audio_no":
user.req_api_instance.has_audio = False
user.generation_status = "awaiting_video_text"
set_user(user_id, user)
await callback.message.edit_text(
"Отлично! Введи описание ролика. Это может быть просто краткое описание или набор ассоциаций, которые помогут сделать релевантное видео.",
reply_markup=InlineKeyboardBuilder()
.row(types.InlineKeyboardButton(text="Назад", callback_data="back_to_audio"))
.as_markup(),
)
await callback.answer()
@dp.callback_query(F.data == "extend_video")
async def extend_video(callback: types.CallbackQuery):
user_id = callback.from_user.id
user = get_user(user_id)
await callback.message.edit_text(
"Видео генерируется, это может занять какое-то время"
)
await callback.answer()
if user.generation_status == "generating":
result = await handle_video_request(user_id, user.req_api_instance, True)
if result is True:
user.generation_status = " "
set_user(user_id, user)
@dp.callback_query(F.data == "generate_new")
async def generate_new(callback: types.CallbackQuery):
user_id = callback.from_user.id
user = get_user(user_id)
await callback.message.edit_text(
"Видео генерируется, это может занять какое-то время"
)
await callback.answer()
if user.req_api_instance and user.generation_status == "generating":
prompt = user.req_api_instance.videoPrompt[0]
user.req_api_instance.videoPrompt[0] = prompt
user.req_api_instance.textPrompt = prompt
result = await handle_video_request(user_id, user.req_api_instance, False)
if result is True:
await callback.message.answer(
"Новое видео создано!", reply_markup=get_video_options_keyboard()
)
elif result is False:
await callback.message.answer("Ошибка при создании нового видео.")
else:
await callback.message.answer("Нет активной заявки на видео.")
async def main():
load_data() # Предзагрузка данных при старте программы
# Инициализация бота и диспетчера (dp)
await dp.start_polling(bot)
# Запуск задачи по сохранению данных users раз в час
asyncio.create_task(save_users_periodically())
if name == "main":
asyncio.run(main())
Это мой бот, у меня некорректно сохраняется информация о users в json, можешь всю работу с json файлами проверить?
It looks like you're encountering issues with saving user information to your JSON files. After reviewing your code, I believe the problem stems from the serialization and deserialization of objects that are not inherently JSON-serializable, particularly the User and reqApi instances.
Important Security Note:
Before we dive into the solution, I noticed that your code includes sensitive information such as your Telegram bot token and API keys:
For security reasons, it's crucial to keep these tokens private. Sharing them publicly can lead to unauthorized access and misuse of your bot and API accounts. I recommend that you:
Remove or replace these tokens in any code you share publicly.
Reset or revoke the existing tokens to prevent any potential security breaches.
Now, let's address the problem with the user data not being correctly saved to your JSON file.
The Issue:
When you're trying to save user data to a JSON file, you're including objects that are not JSON-serializable by default. Specifically, the req_api_instance attribute in your User class is an instance of the reqApi class, which cannot be directly serialized to JSON.
Here's the problematic part in your User class:
class User:
def __init__(self, tgId):
self.tgId = tgId
...
self.req_api_instance = None
def to_dict(self):
return {
"tgId": self.tgId,
...
"req_api_instance": self.req_api_instance, # This is not JSON-serializable
}
When you attempt to serialize the users dictionary, it fails because req_api_instance isn't a basic data type.
Solution:
To fix this issue, you need to make sure that all objects being serialized are JSON-serializable. This involves:
Modifying the to_dict Methods:
Update the to_dict methods of both User and reqApi to ensure all attributes are serializable.
Exclude any attributes that cannot or should not be serialized (e.g., sensitive data like API keys).
Adjusting the Constructors to Support Rehydration:
Modify the __init__ methods to accept parameters for all attributes or use a from_dict class method to reconstruct objects from dictionaries.
Handling Sensitive Data:
Do not include sensitive information such as API keys in your serialized data.
Reinitialize these attributes when you reconstruct the object.
Step-by-Step Guide:
1. Update the reqApi Class:
Add a to_dict method, and ensure that sensitive information like video_header and audio_header is not included in the serialization.
Adjust the way you deserialize user data to match the new constructors.
def load_data():
global users, audio_keys, video_keys, admins, keys
try:
with open("data.json", "r") as f:
users_data = json.load(f)
users = {k: User(**v) for k, v in users_data.items()}
except FileNotFoundError:
users = {}
except TypeError as e:
print(f"Error loading users: {e}")
users = {}
# Load other data similarly...
4. Exclude Sensitive Fields:
Ensure that any sensitive data such as API keys (e.g., in headers) is not saved to the JSON file. Instead, reinitialize them when reconstructing the objects.
5. Verify Serialization Works:
Test the serialization and deserialization process independently to ensure that:
The to_dict methods return fully serializable dictionaries.
The constructors (or from_dict methods) correctly reconstruct the objects from these dictionaries.
Example Test:
# Create a user instance
user = User(tgId=12345)
user.req_api_instance = reqApi(tgId=12345, prompt="Test prompt")
# Serialize to dictionary
user_dict = user.to_dict()
# Serialize to JSON string (to simulate saving to file)
user_json = json.dumps(user_dict, indent=4)
# Deserialize from JSON string (to simulate loading from file)
loaded_user_dict = json.loads(user_json)
# Reconstruct user from dictionary
loaded_user = User(**loaded_user_dict)
# Verify that the reconstructed user has the same data
assert loaded_user.tgId == user.tgId
assert loaded_user.req_api_instance.textPrompt == user.req_api_instance.textPrompt
6. Update Other Classes if Necessary:
If you have similar serialization issues with video_key or audio_key classes, ensure that their to_dict methods only include serializable data and that their constructors can handle being passed a dictionary.
Additional Recommendations:
Exception Handling:
In your load_data function, consider logging or printing the exception to understand why it failed.
This will help you debug issues during deserialization.
Data Validation:
When reconstructing objects from deserialized data, validate the data to ensure it meets the expected format and types.
Security:
Be cautious about what data you're serializing. Excluding sensitive information from your serialized data is crucial.
Reinitialize sensitive attributes separately after loading the data.
Summary:
The main issue arises from attempting to serialize objects (like instances of custom classes) that are not naturally serializable by the json module. By implementing to_dict methods that return serializable representations of your objects and adjusting your classes to handle reconstruction from dictionaries, you can resolve the serialization issues.
Remember to rotate any exposed API keys or tokens to maintain the security of your applications.
If you need further assistance or have additional questions, feel free to ask!