The following code isn't working because it's checking by art ID, but it doesn't check for owner ID neither the image index, fix that. ADD A COMMAND THAT ALLOWS BUYING ART COPYRIGHTS FOR YOURSELF.
"import discord
from discord.ext import commands, tasks
import json
import os
import random
from discord.ext.commands import BucketType
import logging
import datetime
import asyncio
from PIL import Image
import imagehash
import io
Configurar logging
logging.basicConfig(level=logging.INFO)
Definir as intents
intents = discord.Intents.default()
intents.members = True # Necessário para acessar informações dos membros
intents.message_content = True # Necessário para ler o conteúdo das mensagens para comandos de prefixo
-------------------- Funções de Carregamento e Salvamento --------------------
def load_data(file_path, default):
try:
if not os.path.isfile(file_path):
with open(file_path, 'w') as f:
json.dump(default, f, indent=4)
with open(file_path, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
logging.error(f"Erro ao decodificar {file_path}. Reiniciando o arquivo.")
return default
except Exception as e:
logging.error(f"Erro ao carregar {file_path}: {e}")
return default
def save_data(file_path, data):
try:
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)
except Exception as e:
logging.error(f"Erro ao salvar em {file_path}: {e}")
-------------------- Funções de Copyright --------------------
def calculate_similarity(hash1, hash2):
# Calcula a similaridade baseada na distância entre hashes
return 1 - (hash1 - hash2) / len(hash1.hash) ** 2
async def notify_owner(original_message, infringing_message, art_id):
"""
Notifica o dono da arte sobre a infração e oferece opções.
"""
owner_id = int(original_message['owner_id'])
owner = bot.get_user(owner_id)
if not owner:
logging.error(f"Usuário com ID {owner_id} não encontrado.")
return
code
# Envia uma mensagem direta ao dono com as opções
embed = discord.Embed(
title="Infringimento de Copyright",
description=f"O usuário {infringing_message.author.mention} usou sua arte **{original_message['name']}** sem permissão.",
color=discord.Color.red()
)
embed.add_field(name="Opções:", value="✋ `permitir`\n💰 `multar`\n🗑️ `remover`", inline=False)
embed.set_footer(text="Responda com um dos comandos para tomar uma ação.")
try:
dm_channel = await owner.create_dm()
notification = await dm_channel.send(embed=embed)
def check(m):
return m.author == owner and m.channel == dm_channel and m.content.lower() in ['permitir', 'multar', 'remover']
try:
response = await bot.wait_for('message', check=check, timeout=300) # 5 minutos para resposta
except asyncio.TimeoutError:
await dm_channel.send("Tempo esgotado para responder à notificação.")
return
action = response.content.lower()
await handle_owner_action(action, owner_id, art_id, infringing_message)
except Exception as e:
logging.error(f"Erro ao notificar o dono da arte: {e}")
async def handle_owner_action(action, owner_id, art_id, infringing_message):
"""
Processa a ação escolhida pelo dono da arte.
"""
art_prices = load_art_prices()
copyright_data = load_copyright()
code
if art_id not in art_prices:
logging.error(f"Art ID {art_id} não encontrado em art_prices.")
return
if action == 'permitir':
# Reduz o preço da arte
decrement = random.randint(1, 10) # RNG pequeno para decrementar
art_prices[art_id]['price'] = max(art_prices[art_id]['price'] - decrement, ART_PRICE_MIN)
save_art_prices(art_prices)
await infringing_message.channel.send(
f"{infringing_message.author.mention}, o uso de **{art_prices[art_id]['name']}** foi permitido pelo dono. O preço da arte foi reduzido em {decrement}."
)
elif action == 'multar':
# Calcula a multa baseada no algoritmo
usage = art_prices[art_id].get('usage', 0)
denials = art_prices[art_id].get('denials', 0)
fine = max(int(10 * usage / (denials + 1)) + random.randint(1, 5), 1) # Exemplo de cálculo com RNG
art_prices[art_id]['price'] += fine
save_art_prices(art_prices)
# Adiciona a multa ao dono
currency_data = load_currency()
add_currency(owner_id, fine, currency_data)
save_currency(currency_data)
await infringing_message.channel.send(
f"{infringing_message.author.mention}, você foi multado em {fine} moedas pelo uso não autorizado de **{art_prices[art_id]['name']}**."
)
# Atualiza uso
art_prices[art_id]['usage'] = usage + 1
save_art_prices(art_prices)
elif action == 'remover':
# Remove a mensagem infratora
try:
await infringing_message.delete()
await infringing_message.channel.send(
f"{infringing_message.author.mention}, sua mensagem contém conteúdo removido devido ao uso não autorizado de **{art_prices[art_id]['name']}**."
)
except discord.errors.Forbidden:
logging.error("Permissão insuficiente para deletar mensagens.")
except Exception as e:
logging.error(f"Erro ao remover mensagem: {e}")
# Atualiza uso
art_prices[art_id]['usage'] = art_prices[art_id].get('usage', 0) + 1
save_art_prices(art_prices)
else:
logging.error(f"Ação desconhecida: {action}")
-------------------- Eventos do Bot --------------------
@bot.event
async def on_ready():
logging.info(f'Logado como {bot.user.name} - {bot.user.id}')
if not periodic_check.is_running():
periodic_check.start()
@bot.event
async def on_message(message):
if message.author == bot.user:
return
code
logging.info(f'Mensagem de {message.author}: {message.content}')
# Processa comandos primeiro
await bot.process_commands(message)
# Processa imagens no conteúdo da mensagem
if message.attachments:
for attachment in message.attachments:
if attachment.content_type and attachment.content_type.startswith('image'):
try:
# Baixa a imagem
image_bytes = await attachment.read()
image = Image.open(io.BytesIO(image_bytes))
img_hash = imagehash.average_hash(image)
# Verifica se é uma nova arte COPYRIGHT na mensagem.
if 'COPYRIGHT' in message.content.lower():
save_new_art(message, attachment, img_hash)
else:
# Verifica similaridades com artes existentes
copyright_data = load_copyright()
art_prices = load_art_prices()
for art_id, art in copyright_data.items():
existing_hash = imagehash.hex_to_hash(art['hash'])
similarity = calculate_similarity(img_hash, existing_hash)
if similarity >= SIMILARITY_THRESHOLD:
# Encontra a mensagem original
original_message = art
await notify_owner(original_message, message, art_id)
break # Apenas notifica uma vez
except Exception as e:
logging.error(f"Erro ao processar a imagem: {e}")
# Salva os dados da arte
copyright_data[art_id] = {
'owner_id': str(message.author.id),
'hash': str(img_hash),
'name': attachment.filename,
'usage': 0,
'denials': 0
}
save_copyright(copyright_data)
# Inicializa o preço da arte
art_prices[art_id] = {
'price': random.randint(ART_PRICE_INITIAL - 10, ART_PRICE_INITIAL + 10), # Preço inicial balanceado e minimamente aleatório
'name': attachment.filename,
'usage': 0,
'denials': 0
}
save_art_prices(art_prices)
logging.info(f"Nova arte salva: ID {art_id}, Nome {attachment.filename}, Proprietário {message.author}")
# Opcional: Enviar confirmação no canal
@bot.event
async def on_message_confirmation():
await message.channel.send(
f"{message.author.mention}, sua arte **{attachment.filename}** foi registrada com sucesso!"
)
bot.loop.create_task(message.channel.send(
f"{message.author.mention}, sua arte **{attachment.filename}** foi registrada com sucesso!"
))
-------------------- Comandos de Economia e Ranking --------------------
@bot.command(name='balance', help='Verifique seu saldo')
async def balance(ctx):
data = load_currency()
user_id = ctx.author.id
bal = get_balance(user_id, data)
await ctx.send(f'{ctx.author.mention}, você tem {bal} moedas.')
@balance.error
async def balance_error(ctx, error):
if isinstance(error, commands.CommandError):
await ctx.send('Ocorreu um erro ao buscar seu saldo.')
@bot.command(name='work', help='Ganhe uma pequena quantidade de moedas. Tempo de espera: 1 hora')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hora de espera por usuário
async def work(ctx):
currency_data = load_currency()
ranking_data = load_ranking()
user_id = ctx.author.id
# Definir a quantidade ganha com trabalho
earned = random.randint(10, 50)
add_currency(user_id, earned, currency_data)
save_currency(currency_data)
code
# Adicionar pontos ao ranking (1 ponto por moeda ganha)
add_ranking(user_id, earned, ranking_data)
save_ranking(ranking_data)
await ctx.send(f'{ctx.author.mention}, você trabalhou e ganhou {earned} moedas!')
@work.error
async def work_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você pode usar o comando work novamente em {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('Ocorreu um erro ao processar o comando.')
@bot.command(name='crime', help='Tente cometer um crime para uma grande recompensa ou enfrente uma perda. Tempo de espera: 1 hora')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hora de espera por usuário
async def crime(ctx):
currency_data = load_currency()
ranking_data = load_ranking()
user_id = ctx.author.id
# Definir taxa de sucesso
success_chance = 0.3 # 30% de chance de sucesso
if random.random() < success_chance:
# Sucesso: Ganhar uma grande quantidade
earned = random.randint(100, 500)
add_currency(user_id, earned, currency_data)
save_currency(currency_data)
code
# Adicionar pontos ao ranking (1 ponto por moeda ganha)
add_ranking(user_id, earned, ranking_data)
save_ranking(ranking_data)
await ctx.send(f'🎉 {ctx.author.mention}, você cometeu um crime com sucesso e ganhou {earned} moedas!')
else:
# Falha: Perder uma quantidade significativa
lost = random.randint(50, 300)
if subtract_currency(user_id, lost, currency_data):
save_currency(currency_data)
await ctx.send(f'⚠️ {ctx.author.mention}, sua tentativa de crime falhou! Você perdeu {lost} moedas.')
else:
# Usuário não tem saldo suficiente para perder
await ctx.send(f'⚠️ {ctx.author.mention}, sua tentativa de crime falhou! Mas você não tem moedas suficientes para perder.')
# Adicionar pontos negativos ao ranking (0.5 pontos por moeda perdida)
add_ranking(user_id, -lost * 0.5, ranking_data)
save_ranking(ranking_data)
@crime.error
async def crime_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você pode usar o comando crime novamente em {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('Ocorreu um erro ao processar o comando.')
-------------------- Comandos de Jogos e Ranking --------------------
(Inclua aqui as modificações nos comandos de jogos conforme explicado anteriormente)
@bot.command(name='daily', help='Receba uma quantia diária de moedas. Uso: !daily')
async def daily(ctx):
global daily_cooldowns
user_id = ctx.author.id
current_time = int(datetime.datetime.utcnow().timestamp())
code
last_time = daily_cooldowns.get(user_id, 0)
if current_time - last_time < DAILY_COOLDOWN:
remaining = DAILY_COOLDOWN - (current_time - last_time)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você já recebeu suas recompensas diárias! Volte em {hours}h {minutes}m {seconds}s.')
return
# Atualizar o timestamp
daily_cooldowns[user_id] = current_time
# Dar moedas ao usuário
currency_data = load_currency()
ranking_data = load_ranking()
add_currency(user_id, DAILY_AMOUNT, currency_data)
save_currency(currency_data)
# Adicionar pontos fixos ao ranking
add_ranking(user_id, DAILY_POINTS, ranking_data)
save_ranking(ranking_data)
await ctx.send(f'{ctx.author.mention}, você recebeu suas {DAILY_AMOUNT} moedas diárias!')
@daily.error
async def daily_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você já recebeu suas recompensas diárias! Volte em {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('Ocorreu um erro ao processar o comando !daily.')
@bot.command(name='rank', help='Mostra o top 10 jogadores do ranking.')
async def rank(ctx):
ranking_data = load_ranking()
top_ranking = get_top_ranking(ranking_data, top=10)
code
if not top_ranking:
await ctx.send('Ainda não há jogadores no ranking.')
return
embed = discord.Embed(title="🏆 Top 10 Ranking", color=discord.Color.gold())
for idx, (user_id, points) in enumerate(top_ranking, start=1):
user = bot.get_user(int(user_id))
if user:
name = user.name
else:
name = f'Usuário ID: {user_id}'
embed.add_field(name=f'{idx}. {name}', value=f'**Pontos:** {int(points)}', inline=False)
await ctx.send(embed=embed)
@rank.error
async def rank_error(ctx, error):
await ctx.send('Ocorreu um erro ao exibir o ranking.')
-------------------- Funções adicionais para gerenciamento de preços --------------------
@bot.command(name='artprice', help='Verifica o preço de uma arte. Uso: !artprice <art_id>')
async def artprice(ctx, art_id: str):
art_prices = load_art_prices()
if art_id in art_prices:
price = art_prices[art_id]['price']
await ctx.send(f"A arte {art_prices[art_id]['name']} (ID: {art_id}) tem um preço de {price} moedas.")
else:
await ctx.send("Arte não encontrada.")
@bot.command(name='toparts', help='Mostra as artes com os maiores preços.')
async def toparts(ctx, top: int = 10):
art_prices = load_art_prices()
sorted_arts = sorted(art_prices.items(), key=lambda x: x[1]['price'], reverse=True)[:top]
code
if not sorted_arts:
await ctx.send('Ainda não há artes registradas.')
return
embed = discord.Embed(title="🏆 Top Artes por Preço", color=discord.Color.blue())
for idx, (art_id, art) in enumerate(sorted_arts, start=1):
embed.add_field(name=f"{idx}. {art['name']} (ID: {art_id})", value=f"**Preço:** {art['price']} moedas", inline=False)
await ctx.send(embed=embed)
-------------------- Tratamento de perda de copyright --------------------
def check_art_prices():
"""
Verifica as artes cujo preço chegou a zero e remove o copyright.
"""
copyright_data = load_copyright()
art_prices = load_art_prices()
removed_arts = []
code
for art_id, art in list(copyright_data.items()):
price = art_prices.get(art_id, {}).get('price', ART_PRICE_INITIAL)
if price <= ART_PRICE_MIN:
removed_arts.append(art_id)
del copyright_data[art_id]
del art_prices[art_id]
logging.info(f"Arte {art_id} removida devido ao preço zero.")
if removed_arts:
save_copyright(copyright_data)
save_art_prices(art_prices)
# Opcional: Notificar em um canal específico
# Exemplo:
# channel = bot.get_channel(YOUR_CHANNEL_ID)
# if channel:
#=- await channel.send(f"As seguintes artes tiveram seus direitos removidos devido ao preço zero: {', '.join(removed_arts)}")
This poses a significant security risk, as anyone with access to this token can control your bot. Immediately reset your bot token through the Discord Developer Portal to prevent unauthorized access.
Now, let's address the issues you've mentioned and enhance your bot accordingly.
1. Fixing the Art ID Check to Include Owner ID and Image Index
Issue:
The current implementation checks for art similarity based solely on the Art ID. It doesn't verify the owner ID or handle multiple images within a single message (image index).
Solution:
Owner ID Check: Ensure that the bot doesn't notify the owner if they're reusing their own art.
Image Index Handling: Process each image separately within a message and track their respective indices.
2. Adding a Command to Buy Art Copyrights
Feature:
Implement a !buycopyright <art_id> command that allows users to purchase ownership of a specific art piece, provided they have sufficient in-game currency.
Modified Code Sections
Below are the necessary modifications and additions to your existing bot code.
1. Updating on_message Event Handler
We'll update the on_message event to:
Iterate through each image in a message.
Check if the message author is not the owner of the art.
Notify the owner appropriately.
python
@bot.event
async def on_message(message):
if message.author == bot.user:
return
logging.info(f'Mensagem de {message.author}: {message.content}')
# Process commands first
await bot.process_commands(message)
# Process images in the message content
if message.attachments:
for index, attachment in enumerate(message.attachments, start=1):
if attachment.content_type and attachment.content_type.startswith('image'):
try:
# Download the image
image_bytes = await attachment.read()
image = Image.open(io.BytesIO(image_bytes))
img_hash = imagehash.average_hash(image)
# Check if it's a new art with COPYRIGHT tag
if 'COPYRIGHT' in message.content.upper():
save_new_art(message, attachment, img_hash)
else:
# Check for similarity with existing arts
copyright_data = load_copyright()
art_prices = load_art_prices()
for art_id, art in copyright_data.items():
existing_hash = imagehash.hex_to_hash(art['hash'])
similarity = calculate_similarity(img_hash, existing_hash)
if similarity >= SIMILARITY_THRESHOLD:
# Check if the message author is not the owner
if str(message.author.id) != art['owner_id']:
# Notify the owner about the infringement
original_message = art
await notify_owner(original_message, message, art_id)
break # Notify once per image
except Exception as e:
logging.error(f"Erro ao processar a imagem {index} na mensagem: {e}")
Explanation of Changes:
Image Index: Added enumerate to track the index of each image within the message.
Owner Verification: Before notifying, the bot checks if the message author is not the owner of the art (str(message.author.id) != art['owner_id']).
Uppercase Check for COPYRIGHT: Changed the check to message.content.upper() to make it case-insensitive.
2. Adjusting the notify_owner Function
Ensure that when notifying the owner, the bot references the correct owner and handles multiple infringements properly.
python
async def notify_owner(original_message, infringing_message, art_id):
"""
Notifies the owner of the art about an infringement and provides action options.
"""
owner_id = int(original_message['owner_id'])
if infringing_message.author.id == owner_id:
# Don't notify if the owner is reusing their own art
return
owner = bot.get_user(owner_id)
if not owner:
logging.error(f"Usuário com ID {owner_id} não encontrado.")
return
# Create an embed message for the notification
embed = discord.Embed(
title="Infringimento de Copyright",
description=f"O usuário {infringing_message.author.mention} usou sua arte **{original_message['name']}** sem permissão.",
color=discord.Color.red()
)
embed.add_field(name="Opções:", value="✋ `permitir`\n💰 `multar`\n🗑️ `remover`", inline=False)
embed.set_footer(text="Responda com um dos comandos para tomar uma ação.")
try:
dm_channel = await owner.create_dm()
notification = await dm_channel.send(embed=embed)
def check(m):
return m.author == owner and m.channel == dm_channel and m.content.lower() in ['permitir', 'multar', 'remover']
try:
response = await bot.wait_for('message', check=check, timeout=300) # 5 minutes timeout
except asyncio.TimeoutError:
await dm_channel.send("Tempo esgotado para responder à notificação.")
return
action = response.content.lower()
await handle_owner_action(action, owner_id, art_id, infringing_message)
except Exception as e:
logging.error(f"Erro ao notificar o dono da arte: {e}")
Explanation of Changes:
Self-Infringement Prevention: Added a check to prevent the owner from being notified if they are reusing their own art.
python
if infringing_message.author.id == owner_id:
# Don't notify if the owner is reusing their own art
return
3. Adding the Buy Copyright Command
We'll introduce a new command !buycopyright that allows users to purchase ownership of an art piece.
python
@bot.command(name='buycopyright', help='Compre os direitos autorais de uma arte. Uso: !buycopyright <art_id>')
async def buy_copyright(ctx, art_id: str):
currency_data = load_currency()
art_prices = load_art_prices()
copyright_data = load_copyright()
user_id = ctx.author.id
if art_id not in art_prices or art_id not in copyright_data:
await ctx.send("Arte não encontrada.")
return
price = art_prices[art_id]['price']
current_balance = get_balance(user_id, currency_data)
if current_balance < price:
await ctx.send(f"{ctx.author.mention}, você não tem moedas suficientes para comprar esta arte. **Preço:** {price} moedas.")
return
# Proceed with the purchase
subtract_currency(user_id, price, currency_data)
add_currency(copyright_data[art_id]['owner_id'], price, currency_data)
# Transfer ownership
old_owner_id = copyright_data[art_id]['owner_id']
new_owner_id = str(user_id)
copyright_data[art_id]['owner_id'] = new_owner_id
# Optionally, you can reset usage and denials or adjust as needed
copyright_data[art_id]['usage'] = 0
copyright_data[art_id]['denials'] = 0
# Increase the price after purchase to make it valuable
art_prices[art_id]['price'] = int(art_prices[art_id]['price'] * 1.2) # Increase by 20%
# Save all changes
save_currency(currency_data)
save_copyright(copyright_data)
save_art_prices(art_prices)
# Notify the buyer and the old owner
old_owner = bot.get_user(int(old_owner_id))
new_owner = ctx.author
if old_owner:
await old_owner.send(f"A arte **{copyright_data[art_id]['name']}** (ID: {art_id}) foi comprada por {new_owner.mention}.")
await ctx.send(f"🎉 {ctx.author.mention}, você comprou a arte **{copyright_data[art_id]['name']}** \
(ID: {art_id}) por {price} moedas!")
Explanation of the New Command:
Command Signature:
Name:buycopyright
Usage:!buycopyright <art_id>
Process Flow:
Validation: Check if the provided art_id exists.
Balance Check: Ensure the user has enough currency to make the purchase.
Transaction:
Deduct the price from the buyer's balance.
Add the price to the seller's (current owner's) balance.
Transfer ownership by updating the owner_id.
Optionally reset usage and denials.
Increase the art's price by 20% to reflect increased demand/value.
Notifications:
Notify the previous owner via DM about the sale.
Confirm the purchase to the buyer in the channel.
Edge Cases Handled:
Non-existent Art ID: Alerts the user if the art doesn't exist.
Insufficient Funds: Notifies the user if they lack the required currency.
Old Owner Notification: Attempts to DM the old owner about the sale.
4. Adding Ownership Verification in on_message
Ensure that when an art is used by its new owner, the bot doesn't treat it as an infringement.
python
# Already handled in the modified on_message event with the owner check
# (
# if str(message.author.id) != art['owner_id']:
# ...notify owner...
# )
This check ensures that only users who aren't the current owners are flagged for infringement.
5. Example: Handling Multiple Image Attachments
If you want to provide feedback on each image processed within a message, you can modify the loop to include the image index.
python
@bot.event
async def on_message(message):
if message.author == bot.user:
return
logging.info(f'Mensagem de {message.author}: {message.content}')
# Process commands first
await bot.process_commands(message)
# Process images in the message content
if message.attachments:
for index, attachment in enumerate(message.attachments, start=1):
if attachment.content_type and attachment.content_type.startswith('image'):
try:
# Download the image
image_bytes = await attachment.read()
image = Image.open(io.BytesIO(image_bytes))
img_hash = imagehash.average_hash(image)
# Check if it's a new art with COPYRIGHT tag
if 'COPYRIGHT' in message.content.upper():
save_new_art(message, attachment, img_hash)
else:
# Check for similarity with existing arts
copyright_data = load_copyright()
art_prices = load_art_prices()
infringement_found = False
for art_id, art in copyright_data.items():
existing_hash = imagehash.hex_to_hash(art['hash'])
similarity = calculate_similarity(img_hash, existing_hash)
if similarity >= SIMILARITY_THRESHOLD:
# Check if the message author is not the owner
if str(message.author.id) != art['owner_id']:
# Notify the owner about the infringement
original_message = art
await notify_owner(original_message, message, art_id)
infringement_found = True
break # Notify once per image
if not infringement_found:
logging.info(f'Nenhuma infração encontrada para a imagem {index} na mensagem de {message.author}.')
except Exception as e:
logging.error(f"Erro ao processar a imagem {index} na mensagem: {e}")
Explanation of Changes:
Infringement Feedback: If no infringement is found for a specific image, log that information. This can be useful for debugging and auditing.
Final Notes
Data Consistency: Ensure that all related data files (currency_data.json, art_prices.json, etc.) are consistently updated to reflect ownership and currency changes.
Error Handling: Always handle potential errors, especially when dealing with file I/O and user inputs, to prevent the bot from crashing.
Security: Never share your Discord bot token publicly. If you believe it has been compromised, regenerate it immediately.
Testing: After making these changes, thoroughly test each feature in a controlled environment (like a test server) to ensure they work as expected before deploying them to your main server.
Feel free to integrate these changes into your bot. If you encounter any further issues or need additional features, feel free to ask!