Files
bot.py
README.md
requirements.txt
Code
3 543
bot.py
import discord
from discord import app_commands
from discord.ext import commands
import os
from dotenv import load_dotenv
import sqlite3
from datetime import datetime, timedelta
import random
from typing import Optional
load_dotenv()
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='/', intents=intents)
def init_db():
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
balance INTEGER DEFAULT 0,
last_daily TEXT,
last_work TEXT
)''')
c.execute('''CREATE TABLE IF NOT EXISTS inventory (
user_id INTEGER,
item_name TEXT,
quantity INTEGER DEFAULT 1,
PRIMARY KEY (user_id, item_name)
)''')
conn.commit()
conn.close()
def get_user(user_id):
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
user = c.fetchone()
if not user:
c.execute('INSERT INTO users (user_id, balance) VALUES (?, ?)', (user_id, 0))
conn.commit()
user = (user_id, 0, None, None)
conn.close()
return user
def update_balance(user_id, amount):
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('UPDATE users SET balance = balance + ? WHERE user_id = ?', (amount, user_id))
conn.commit()
conn.close()
def set_balance(user_id, amount):
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('UPDATE users SET balance = ? WHERE user_id = ?', (amount, user_id))
conn.commit()
conn.close()
def get_balance(user_id):
user = get_user(user_id)
return user[1]
def add_item(user_id, item_name, quantity=1):
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('SELECT quantity FROM inventory WHERE user_id = ? AND item_name = ?', (user_id, item_name))
result = c.fetchone()
if result:
c.execute('UPDATE inventory SET quantity = quantity + ? WHERE user_id = ? AND item_name = ?',
(quantity, user_id, item_name))
else:
c.execute('INSERT INTO inventory (user_id, item_name, quantity) VALUES (?, ?, ?)',
(user_id, item_name, quantity))
conn.commit()
conn.close()
def remove_item(user_id, item_name, quantity=1):
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('SELECT quantity FROM inventory WHERE user_id = ? AND item_name = ?', (user_id, item_name))
result = c.fetchone()
if not result or result[0] < quantity:
conn.close()
return False
new_quantity = result[0] - quantity
if new_quantity <= 0:
c.execute('DELETE FROM inventory WHERE user_id = ? AND item_name = ?', (user_id, item_name))
else:
c.execute('UPDATE inventory SET quantity = ? WHERE user_id = ? AND item_name = ?',
(new_quantity, user_id, item_name))
conn.commit()
conn.close()
return True
def get_inventory(user_id):
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('SELECT item_name, quantity FROM inventory WHERE user_id = ?', (user_id,))
items = c.fetchall()
conn.close()
return items
SHOP_ITEMS = {
'๐': {'name': 'Mela', 'price': 50, 'description': 'Una mela fresca e succosa'},
'๐': {'name': 'Pizza', 'price': 150, 'description': 'Una deliziosa pizza italiana'},
'โ๏ธ': {'name': 'Spada', 'price': 500, 'description': 'Una spada potente'},
'๐ก๏ธ': {'name': 'Scudo', 'price': 400, 'description': 'Uno scudo resistente'},
'๐': {'name': 'Diamante', 'price': 1000, 'description': 'Un diamante prezioso'},
'๐ฃ': {'name': 'Canna da Pesca', 'price': 300, 'description': 'Per pescare'},
'๐ช': {'name': 'Ascia', 'price': 350, 'description': 'Per tagliare legna'},
'๐': {'name': 'Stella', 'price': 2000, 'description': 'Un oggetto raro e magico'},
'๐': {'name': 'Pane', 'price': 20, 'description': 'Pane fresco'},
'๐ ': {'name': 'Casa', 'price': 5000, 'description': 'La tua casa virtuale'}
}
@bot.event
async def on_ready():
init_db()
try:
synced = await bot.tree.sync()
print(f'โ
Sincronizzati {len(synced)} comandi slash')
print(f'\n๐ URL di invito del bot:')
print(f'https://discord.com/api/oauth2/authorize?client_id={bot.user.id}&permissions=8&scope=bot%20applications.commands\n')
except Exception as e:
print(f'โ Errore sincronizzazione: {e}')
print(f'๐ค Bot pronto! Connesso come {bot.user}')
print(f'๐ Scrivi / su Discord per vedere i comandi!\n')
await bot.change_presence(activity=discord.Game(name="Usa i comandi /"))
@bot.tree.command(name='balance', description='Visualizza il saldo di un utente')
async def balance(interaction: discord.Interaction, utente: Optional[discord.Member] = None):
if utente is None:
utente = interaction.user
user_balance = get_balance(utente.id)
embed = discord.Embed(
title=f"๐ฐ Saldo di {utente.display_name}",
description=f"**{user_balance:,}** monete",
color=discord.Color.gold()
)
embed.set_thumbnail(url=utente.display_avatar.url)
await interaction.response.send_message(embed=embed)
@bot.tree.command(name='daily', description='Ritira il tuo premio giornaliero')
async def daily(interaction: discord.Interaction):
user_id = interaction.user.id
get_user(user_id)
conn = sqlite3.connect('economy.db')
c = conn.cursor()
c.execute('SELECT last_daily FROM users WHERE user_id = ?', (user_id,))
last_daily = c.fetchone()[0]
now = datetime.now()
if last_daily:
last_time = datetime.fromisoformat(last_daily)
if now - last_time < timedelta(hours=24):
remaining = timedelta(hours=24) - (now - last_time)
hours = remaining.seconds // 3600
minutes = (remaining.seconds % 3600) // 60
embed = discord.Embed(
title="โฐ Daily giร ritirato!",
description=f"Potrai ritirare il tuo daily tra **{hours}h {minutes}m**",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed)
conn.close()
return
reward = random.randint(100, 300)
update_balance(user_id, reward)
c.execute('UPDATE users SET last_daily = ? WHERE user_id = ?', (now.isoformat(), user_id))
conn.commit()
conn.close()
embed = discord.Embed(
title="๐ Daily ritirato!",
description=f"Hai ricevuto **{reward}** monete!",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed)
@bot.tree.command(name='work', description='Lavora per guadagnare monete')