import logging
import telebot
import os
from g4f.client import Client
import json
import boto3
import time
import multiprocessing
from datetime import datetime, timedelta
from collections import defaultdict

from g4f.Provider import RetryProvider,You, Liaobots, Chatgpt4o, AI365VIP, OpenaiChat, Marsyoo, LiteIcoding, MagickPenAsk

TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN")
TG_BOT_CHATS = os.environ.get("TG_BOT_CHATS").lower().split(",")
PROXY_API_KEY = os.environ.get("PROXY_API_KEY")
YANDEX_KEY_ID = os.environ.get("YANDEX_KEY_ID")
YANDEX_KEY_SECRET = os.environ.get("YANDEX_KEY_SECRET")
YANDEX_BUCKET = os.environ.get("YANDEX_BUCKET")
CHANNEL_ID_1 = os.environ.get("CHANNEL_ID_1")  # ID первого канала
CHANNEL_ID_2 = os.environ.get("CHANNEL_ID_2")  # ID второго канала
CHANNEL_LINK_1 = os.environ.get("CHANNEL_LINK_1")  # Ссылка на первый канал
CHANNEL_LINK_2 = os.environ.get("CHANNEL_LINK_2")  # Ссылка на второй канал
logger = telebot.logger
telebot.logger.setLevel(logging.INFO)

bot = telebot.TeleBot(TG_BOT_TOKEN, threaded=False)

alwd_usrs = [TG_BOT_CHATS]
lox_usr=True
cringe_usr=False
client = Client(
    provider=RetryProvider([You, Liaobots, Chatgpt4o, AI365VIP, OpenaiChat, Marsyoo, LiteIcoding, MagickPenAsk],shuffle=False),
    proxy="socks5://zZNu6c:jCTJYZ@194.33.32.64:8000"
)
INITIAL_FREE_REQUESTS = 2
init_cringe_requests= 3
# Dictionary to track request counts per user
user_request_count = defaultdict(int)

# Channel IDs to verify subscription (for illustration)
required_channels = {
    CHANNEL_ID_1: CHANNEL_LINK_1,
    CHANNEL_ID_2: CHANNEL_LINK_2
}

def has_exceeded_request_limit(user_id, username):
    if username in alwd_usrs:
        return False
    if user_request_count[user_id] < INITIAL_FREE_REQUESTS:
        return False  # User is within free request limit
    elif user_request_count[user_id] < init_cringe_requests and cringe_usr==True:
        return False
    else:
        pass
    return not is_user_subscribed_to_channels(username,user_id)

def is_user_subscribed_to_channels(username,user_id):
    if username.lower() in alwd_usrs:
        return True
    if cringe_usr:
        return True
    # TODO: Implement actual check using the Telegram Bot API
    for channel in [CHANNEL_ID_1, CHANNEL_ID_2]:
        user_channel_status = bot.get_chat_member(chat_id=channel, user_id=user_id)

        if user_channel_status["status"] != 'left':
            return True
        else:
            time.sleep(1)
            bot.send_message(message.from_user.id, 'Вы еще не подписались!')
    # This function should return True if the user is subscribed to all required channels
    # For now, assume False - meaning user hasn’t subscribed
    return False

def send_subscription_reminder(message):
    reminder_text = (
        "You have exhausted your free requests. "
        "Please subscribe to the following channels to continue:\n"
    )
    for channel_id in [CHANNEL_ID_1, CHANNEL_ID_2]:
        reminder_text += f"{channel_link}\n"

    bot.reply_to(message, reminder_text)

@bot.message_handler(func=lambda message: True, content_types=["text"])
def echo_message(message):
    user_id = message.from_user.id
    username = message.from_user.username
    time.sleep(1)
   

    if has_exceeded_request_limit(user_id, username):
        send_subscription_reminder(message)
        return

    # Increment request count
    user_request_count[user_id] += 1

    typing_process = multiprocessing.Process(target=typing, args=(message.chat.id,))
    typing_process.start()

    try:
        text = message.text
        ai_response = process_text_message(text, message.chat.id)
    except Exception as e:
        bot.reply_to(message, f'Error occurred, please try later! {e}')
        return

    typing_process.terminate()
    time.sleep(1)
    try:
        bot.reply_to(message, ai_response)
    except Exception as e:
        time.sleep(1)
        bot.reply_to(message, f'Error occurred, please try later! {e}')
    


def get_s3_client():
    session = boto3.session.Session(
        aws_access_key_id=YANDEX_KEY_ID, aws_secret_access_key=YANDEX_KEY_SECRET
    )
    return session.client(
        service_name="s3", endpoint_url="https://storage.yandexcloud.net"
    )


def typing(chat_id):
    while True:
        bot.send_chat_action(chat_id, "typing")
        time.sleep(5)


@bot.message_handler(commands=["help", "start"])
def send_welcome(message):
    bot.reply_to(
        message,
        ("Привет! Я ChatGPT бот. Спроси меня что-нибудь!"),
    )


@bot.message_handler(commands=["new"])
def clear_history(message):
    clear_history_for_chat(message.chat.id)
    bot.reply_to(message, "История чата очищена!")




def process_text_message(text, chat_id) -> str:
    model = "gpt-4o"

    # read current chat history
    s3client = get_s3_client()
    history = []
    try:
        history_object_response = s3client.get_object(
            Bucket=YANDEX_BUCKET, Key=f"{chat_id}.json"
        )
        history = json.loads(history_object_response["Body"].read())
    except:
        pass

    history.append({"role": "user", "content": text})

    try:
        chat_completion = client.chat.completions.create(
            model=model, messages=history
        )
    except Exception as e:
        if type(e).__name__ == "BadRequestError":
            clear_history_for_chat(chat_id)
            return process_text_message(text, chat_id)
        else:
            raise e

    ai_response = chat_completion.choices[0].message.content
    history.append({"role": "assistant", "content": ai_response})

    # save current chat history
    s3client.put_object(
        Bucket=YANDEX_BUCKET,
        Key=f"{chat_id}.json",
        Body=json.dumps(history),
    )

    return ai_response


def clear_history_for_chat(chat_id):
    try:
        s3client = get_s3_client()
        s3client.put_object(
            Bucket=YANDEX_BUCKET,
            Key=f"{chat_id}.json",
            Body=json.dumps([]),
        )
    except:
        pass


def handler(event, context):
    message = json.loads(event["body"])
    update = telebot.types.Update.de_json(message)

    if (
        update.message is not None
    ):
        try:
            bot.process_new_updates([update])
        except Exception as e:
            print(e)

    return {
        "statusCode": 200,
        "body": "ok",
    }

код сначала выдал ткаую ошибку:A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: message is too long
а потом такую: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: chat not found

как починить?