Нужен код для экономического бота с использованием библиотек discord.py и sqlite3, в котором будет система предметов и инвентаря, а также магазина.
Вот код который есть на данный момент:
import discord
from discord.ext import commands
import sqlite3
from config import settings
client = commands.Bot(command_prefix = settings['PREFIX'], intents = discord.Intents.all())
client.remove_command('help')
connection = sqlite3.connect('server.db')
cursor = connection.cursor()
@client.event
async def on_ready():
cursor.execute("""CREATE TABLE IF NOT EXISTS users (
name TEXT,
id INT,
cash BIGINT,
rep INT,
lvl INT
)""")
cursor.execute("""CREATE TABLE IF NOT EXISTS shop (
role_id INT,
id INT,
cost BIGINT
)""")
for guild in client.guilds:
for member in guild.members:
if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
cursor.execute(f"INSERT INTO users VALUES ('{member}', {member.id}, 0, 0, 1)")
else:
pass
connection.commit()
print('Бот работает!')
@client.event
async def on_member_join(member):
for member in guild.members:
if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
cursor.execute(f"INSERT INTO users VALUES ('{member}'. {member.id}, 0, 0, 1)")
connection.commit()
else:
pass
@client.command(aliases = ["balance", "cash"])
async def _balance(ctx, member: discord.Member = None):
if member is None:
await ctx.send(embed = discord.Embed(
description = f"""Баланс игрока **{ctx.author}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :dollar:**"""
))
else:
await ctx.send(embed = discord.Embed(
description = f"""Баланс игрока **{member}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(member.id)).fetchone()[0]} :dollar:**"""
))
@client.command(aliases = ["award"])
@commands.has_permissions(administrator = True)
async def _award(ctx, member:discord.Member = None, amount: int = None):
if member is None:
await ctx.send(f":x:**{ctx.author}**, не указан пользователь!")
else:
if amount is None:
await ctx.send(f":x:**{ctx.author}**, не указана сумма начисления!")
elif amount < 1:
await ctx.send(f":x:**{ctx.author}**, сумма должна быть больше больше 1 :dollar:!")
else:
cursor.execute("UPDATE users SET cash = cash + {} WHERE id = {}".format(amount, member.id))
connection.commit()
#await ctx.message.add_reaction(":white_check_mark:")
await ctx.send(f":white_check_mark: Сумма успешно добавлена!")
@client.command(aliases = ["take"])
@commands.has_permissions(administrator = True)
async def _take(ctx, member:discord.Member = None, amount = None):
if member is None:
await ctx.send(f":x:**{ctx.author}**, не указан пользователь!")
else:
if amount is None:
await ctx.send(f":x:**{ctx.author}**, не указана сумма снятия!")
elif amount == "all":
cursor.execute("UPDATE users SET cash = {} WHERE id = {}".format(0, member.id))
connection.commit()
await ctx.send(f":white_check_mark: Баланс успешно обнулен")
elif int(amount) < 1:
await ctx.send(f":x:**{ctx.author}**, сумма должна быть больше больше 1 :dollar:!")
else:
cursor.execute("UPDATE users SET cash = cash - {} WHERE id = {}".format(int(amount), member.id))
connection.commit()
#await ctx.message.add_reaction(":white_check_mark:")
await ctx.send(f":white_check_mark: Сумма успешно снята!")
@client.command(aliases = ["addrole"])
@commands.has_permissions(administrator = True)
async def _add_shop(ctx, role: discord.Role = None, cost: int = None):
if role is None:
await ctx.send(f":x:**{ctx.author}**, роль не указана! ")
else:
if cost is None:
await ctx.send(f"**{ctx.author}, стоимость не указана!")
elif cost < 0:
await ctx.send(f":x:**{ctx.author}**, стоимомть должна быть больше нуля!")
else:
cursor.execute("INSERT INTO shop VALUES ({}, {}, {})".format(role.id, ctx.guild.id, cost))
connection.commit()
#await ctx.message.add_reaction(":white_check_mark:")
await ctx.send(f":white_check_mark: Предмет успешно добавлен!")
@client.command(aliases = ["removerole", "deleterole"])
@commands.has_permissions(administrator = True)
async def _remove_shop(ctx, role: discord.Role = None):
if role is None:
await ctx.send(f":x:**{ctx.author}**, роль не указана! ")
else:
cursor.execute("DELETE FROM shop WHERE role_id = {}".format(role.id))
connection.commit()
await ctx.send(f":white_check_mark: Предмет успешно удален!")
@client.command(aliases = ["shop"])
async def _shop(ctx):
embed = discord.Embed(title = "Магазин ролей")
for row in cursor.execute("SELECT role_id, cost FROM shop WHERE id = {}".format(ctx.guild.id)):
if ctx.guild.get_role(row[0]) !=None:
embed.add_field(
name = f"Стоимость {row[1]}",
value = f"Вы приобретете роль {ctx.guild.get_role(row[0]).mention}",
inline = False)
else:
pass
await ctx.send(embed = embed)
@client.command(aliases = ['buy', 'buy-role'])
async def _buy(ctx, role: discord.Role = None):
if role is None:
await ctx.send(f":x:**{ctx.author}**, роль не указана")
else:
if role in ctx.author.roles:
await ctx.send(f":x:**{ctx.author}**, у вас уже имеется данная роль!")
elif cursor.execute("SELECT cost FROM shop WHERE role_id = {}".format(role.id)).fetchone()[0] > cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]:
await ctx.send(f":x:**{ctx.author}**, Не хватает :dollar:!")
else:
await ctx.author.add_roles(role)
cursor.execute("UPDATE users SET cash = cash - {0} WHERE id = {1}".format(cursor.execute("SELECT cost FROM shop WHERE role_id = {}".format(role.id)).fetchone()[0], ctx.author.id))
connection.commit()
await ctx.send(f":white_check_mark: Предмет успешно приобретен!")
@client.event
async def on_command_error(ctx, error):
print(error)
if isinstance(error, discord.ext.commands.errors.MissingPermissions):
await ctx.send(f":x:**{ctx.author}**, у вас недостаточно прав для выполнения данной команды!")
elif isinstance(error, commands.UserInputError):
await ctx.send(embed=embed)
client.run(settings['TOKEN'])
У меня получилось сделать лишь магазин ролей, а сделать возможность добавлять в него предметы и сохранять их в инвентарь после покупки - нет