aprimore esse codigo e aperfeiçoando o output:

import discord
from discord import app_commands
from discord.ext import commands
import json
import os
from cohere import Client

# Configuração inicial do bot
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

# Função para carregar JSON com verificação de integridade
def load_json(filename, default_value):
    try:
        with open(filename, 'r') as f:
            data = json.load(f)
        if not isinstance(data, type(default_value)):
            raise ValueError("Arquivo corrompido")
        return data
    except (FileNotFoundError, json.JSONDecodeError, ValueError):
        print(f"Erro ao carregar {filename}. Criando novo arquivo com valores padrão.")
        save_json(filename, default_value)
        return default_value

# Função para salvar JSON
def save_json(filename, data):
    with open(filename, 'w') as f:
        json.dump(data, f, indent=4)

# Carregar configurações
def load_config():
    default_config = {
        "api_key": "",
        "model": "command-r-plus",
        "allowed_channels": [],
        "nicknames": {},
        "client_name": "YOUR_CLIENT_NAME"
    }
    return load_json('config.json', default_config)

# Carregar parâmetros do modelo
def load_model_params():
    default_params = {
        "temperature": 0.3,
        "max_tokens": 1024,
        "max_input_tokens": 1024,
        "k": 0,
        "p": 0,
        "frequency_penalty": 0,
        "seed": 10
    }
    return load_json('model_params.json', default_params)

# Carregar preamble
def load_preamble():
    default_preamble = "You are an AI-assistant chatbot. You are trained to assist users by providing thorough and helpful responses to their queries."
    return load_json('preamble.json', {"preamble": default_preamble})["preamble"]

# Carregar memória do bot
def load_memory():
    return load_json('memory.json', [])

config = load_config()
model_params = load_model_params()
memory = load_memory()
preamble = load_preamble()

# Configurar cliente Cohere
client = Client(client_name=config['client_name'], token=config['api_key'])

# Novo cache para mensagens com funcionalidades adicionais
message_cache = {}

# Função para salvar o cache de mensagens
def save_message_cache():
    with open('message_cache.json', 'w') as f:
        json.dump(message_cache, f, indent=4)

# Função para carregar o cache de mensagens
def load_message_cache():
    try:
        with open('message_cache.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

message_cache = load_message_cache()

# Função para adicionar mensagem ao cache
def add_to_cache(channel_id, user_message, user_message_id, bot_message, bot_message_id):
    global memory
    if channel_id not in message_cache:
        message_cache[channel_id] = []
    message_cache[channel_id].append({
        "user_message": user_message,
        "user_message_id": user_message_id,
        "bot_message": bot_message,
        "bot_message_id": bot_message_id
    })
    # Adicionar ao memory
    memory.append({"role": "USER", "message": user_message, "id": user_message_id})
    memory.append({"role": "CHATBOT", "message": bot_message, "id": bot_message_id})
    save_message_cache()
    save_json('memory.json', memory)

# Função para remover mensagem do cache
def remove_from_cache(channel_id, message_id):
    global memory
    channel_id = str(channel_id)
    if channel_id in message_cache:
        message_cache[channel_id] = [msg for msg in message_cache[channel_id] 
                                     if msg["user_message_id"] != message_id and msg["bot_message_id"] != message_id]
        save_message_cache()
    
    # Remove as mensagens correspondentes do memory
    memory = [m for m in memory if m.get("id") != message_id]
    save_json('memory.json', memory)

# Função para atualizar mensagem no cache
def update_cache(channel_id, message_id, new_content):
    global memory
    channel_id = str(channel_id)
    if channel_id in message_cache:
        for msg in message_cache[channel_id]:
            if msg["user_message_id"] == message_id:
                msg["user_message"] = new_content
                break
            elif msg["bot_message_id"] == message_id:
                msg["bot_message"] = new_content
                break
        save_message_cache()
    
    # Atualizar o memory
    for msg in memory:
        if msg.get("id") == message_id:
            msg["message"] = new_content
            break
    save_json('memory.json', memory)

# Função para sincronizar memory com message_cache
def sync_memory_with_cache():
    global memory
    memory = []
    for channel_id, messages in message_cache.items():
        for msg in messages:
            memory.append({"role": "USER", "message": msg["user_message"], "id": msg["user_message_id"]})
            memory.append({"role": "CHATBOT", "message": msg["bot_message"], "id": msg["bot_message_id"]})
    save_json('memory.json', memory)

# Função para gerar resposta
def generate_response(user_message):
    try:
        response = client.chat(
            message=user_message,
            model=config['model'],
            preamble=preamble,
            **model_params
        )
        
        return response.text
    except Exception as e:
        print(f"Erro ao gerar resposta: {e}")
        return None

class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Regenerar", style=discord.ButtonStyle.primary, custom_id="regenerate")
    async def regenerate(self, interaction: discord.Interaction, button: discord.ui.Button):
        channel_id = str(interaction.channel_id)
        message_id = str(interaction.message.id)
        for index, msg in enumerate(message_cache.get(channel_id, [])):
            if msg["bot_message_id"] == message_id:
                new_response = generate_response(msg["user_message"])
                if new_response:
                    try:
                        await interaction.response.defer()
                        await interaction.message.edit(content=new_response)
                        msg["bot_message"] = new_response
                        update_cache(channel_id, message_id, new_response)
                        await interaction.followup.send("Mensagem regenerada!", ephemeral=True)
                    except discord.errors.NotFound:
                        print("A interação expirou antes de podermos responder.")
                else:
                    try:
                        await interaction.response.send_message("Falha ao regenerar a mensagem.", ephemeral=True)
                    except discord.errors.NotFound:
                        print("A interação expirou antes de podermos responder.")
                return
        try:
            await interaction.response.send_message("Não foi possível encontrar a mensagem para regenerar.", ephemeral=True)
        except discord.errors.NotFound:
            print("A interação expirou antes de podermos responder.")

    @discord.ui.button(label="Deletar", style=discord.ButtonStyle.danger, custom_id="delete")
    async def delete(self, interaction: discord.Interaction, button: discord.ui.Button):
        channel_id = str(interaction.channel_id)
        message_id = str(interaction.message.id)
        remove_from_cache(channel_id, message_id)
        try:
            await interaction.response.defer()
            await interaction.message.delete()
            await interaction.followup.send("Mensagem deletada!", ephemeral=True)
        except discord.errors.NotFound:
            print("A interação expirou antes de podermos responder.")

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')
    sync_memory_with_cache()  # Sincronizar memory com message_cache na inicialização
    bot.add_view(PersistentView())
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(f"Error syncing commands: {e}")

@bot.tree.command(name="set_api", description="Set API key and model")
@app_commands.checks.has_permissions(administrator=True)
async def set_api(interaction: discord.Interaction, api_key: str, model: str, client_name: str):
    config['api_key'] = api_key
    config['model'] = model
    config['client_name'] = client_name
    save_json('config.json', config)
    global client
    client = Client(client_name=client_name, token=api_key)
    await interaction.response.send_message(f"API settings updated! Model set to: {model}", ephemeral=True)

@bot.tree.command(name="set_model_params", description="Set model parameters")
@app_commands.checks.has_permissions(administrator=True)
async def set_model_params(
    interaction: discord.Interaction, 
    temperature: float = 0.3,
    max_tokens: int = 1024,
    max_input_tokens: int = 1024,
    k: int = 0,
    p: float = 0.0,
    frequency_penalty: float = 0.0,
    seed: int = 10
):
    global model_params
    model_params = {
        "temperature": temperature,
        "max_tokens": max_tokens,
        "max_input_tokens": max_input_tokens,
        "k": k,
        "p": p,
        "frequency_penalty": frequency_penalty,
        "seed": seed
    }
    save_json('model_params.json', model_params)
    await interaction.response.send_message("Model parameters updated!", ephemeral=True)

@bot.tree.command(name="set_preamble", description="Set the preamble for the bot")
@app_commands.checks.has_permissions(administrator=True)
async def set_preamble(interaction: discord.Interaction, new_preamble: str):
    global preamble
    preamble = new_preamble
    save_json('preamble.json', {"preamble": preamble})
    await interaction.response.send_message("Preamble updated!", ephemeral=True)

@bot.tree.command(name="set_nickname", description="Set a nickname for the bot to use")
async def set_nickname(interaction: discord.Interaction, nickname: str):
    config['nicknames'][str(interaction.user.id)] = nickname
    save_json('config.json', config)
    await interaction.response.send_message(f"Your nickname has been set to {nickname}!", ephemeral=True)

@bot.tree.command(name="allow_channel", description="Allow the bot to respond in this channel")
@app_commands.checks.has_permissions(administrator=True)
async def allow_channel(interaction: discord.Interaction):
    if interaction.channel.id not in config['allowed_channels']:
        config['allowed_channels'].append(interaction.channel.id)
        save_json('config.json', config)
        await interaction.response.send_message("This channel is now allowed for bot interactions!", ephemeral=True)
    else:
        await interaction.response.send_message("This channel is already allowed!", ephemeral=True)

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if message.channel.id in config['allowed_channels'] or isinstance(message.channel, discord.DMChannel):
        nickname = config['nicknames'].get(str(message.author.id), message.author.name)
        user_message = f"{nickname}: {message.content}"
        
        bot_response = generate_response(user_message)
        
        if bot_response:
            # Usar a view persistente
            view = PersistentView()
            
            # Enviar mensagem com botões
            bot_message = await message.channel.send(bot_response, view=view)
            
            # Adicionar ao cache e memory
            add_to_cache(str(message.channel.id), user_message, str(message.id), bot_response, str(bot_message.id))
        else:
            await message.channel.send("Desculpe, ocorreu um erro ao processar sua mensagem.")

    await bot.process_commands(message)

@bot.event
async def on_message_edit(before, after):
    if before.author != bot.user:
        channel_id = str(before.channel.id)
        update_cache(channel_id, str(before.id), after.content)

@bot.event
async def on_message_delete(message):
    channel_id = str(message.channel.id)
    remove_from_cache(channel_id, str(message.id))

# Iniciar o bot
bot.run('YOUR_DISCORD_BOT_TOKEN')