python telebot KeyError:
Ошибка
Traceback (most recent call last):
File "c:\Users\Winner\PycharmProjects\pythonProject\popa.py", line 55, in <module>
bot.polling(none_stop=True)
File "C:\Users\Winner\PycharmProjects\pythonProject\venv\Lib\site-packages\telebot\__init__.py", line 1169, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "C:\Users\Winner\PycharmProjects\pythonProject\venv\Lib\site-packages\telebot\__init__.py", line 1244, in __threaded_polling
raise e
File "C:\Users\Winner\PycharmProjects\pythonProject\venv\Lib\site-packages\telebot\__init__.py", line 1206, in __threaded_polling
self.worker_pool.raise_exceptions()
File "C:\Users\Winner\PycharmProjects\pythonProject\venv\Lib\site-packages\telebot\util.py", line 150, in raise_exceptions
raise self.exception_info
File "C:\Users\Winner\PycharmProjects\pythonProject\venv\Lib\site-packages\telebot\util.py", line 93, in run
task(*args, **kwargs)
File "C:\Users\Winner\PycharmProjects\pythonProject\venv\Lib\site-packages\telebot\__init__.py", line 8404, in _run_middlewares_and_handler
result = handler['function'](message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Winner\PycharmProjects\pythonProject\popa.py", line 39, in handle_message
if give_bonus(message.from_user.id):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Winner\PycharmProjects\pythonProject\popa.py", line 47, in give_bonus
if user_data[user_id]['last_bonus'] is None or (now - user_data[user_id]['last_bonus']).total_seconds() >= 86400:
~~~~~~~~~^^^^^^^^^
KeyError: 2019983510
Код:
import telebot
import os
import random
import json
import datetime
from datetime import datetime
bot = telebot.TeleBot('TOKEN')
user_data_file = 'user_data.json'
def load_user_data():
try:
with open(user_data_file, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {}
def save_user_data(user_data):
with open(user_data_file, 'w') as f:
json.dump(user_data, f)
user_data = load_user_data()
@bot.message_handler(content_types=['text'])
def handle_message(message):
if message.text == '/start':
if message.from_user.id not in user_data:
user_data[message.from_user.id] = {'balance': 0, 'last_bonus': None}
save_user_data(user_data)
bot.send_message(message.chat.id, f"Привет! Я бот для нашей беседы. ? У вас на счету {user_data[message.from_user.id]['balance']} дрочекойнов.")
elif message.text == '/help':
bot.send_message(message.chat.id, "/help - список команд, доступные в боте\n/balance - узнать свой баланс\n/bonus - получить бонусные дрочекойны")
elif message.text == '/balance':
bot.send_message(message.chat.id, f"Ваш баланс: {user_data[message.from_user.id]['balance']} дрочекойнов.")
elif message.text == '/bonus':
if give_bonus(message.from_user.id):
bot.send_message(message.chat.id, "Ты получил бонус!")
else:
bot.send_message(message.chat.id, "Бонус не может быть выдан, так как ещё не прошло 24 часа")
else:
bot.send_message(message.chat.id)
def give_bonus(user_id):
now = datetime.now()
if user_data[user_id]['last_bonus'] is None or (now - user_data[user_id]['last_bonus']).total_seconds() >= 86400:
user_data[user_id]['balance'] += random.randint(3, 15)
user_data[user_id]['last_bonus'] = now
save_user_data(user_data)
return True
return False
if __name__ == '__main__':
bot.polling(none_stop=True)
Помогите пофиксить