Найти в Дзене
Ростовский маппер

Код для Дискорд-бота по экономике

import discord
import os
from discord.ext import commands

TOKEN = Ваш токен
PREFIX = ?

bot = commands.AutoShardedBot(command_prefix=?)
@bot.event
async def on_ready():
print(f"{bot.user.name} готов!")
activity = discord.Activity(type=discord.ActivityType.listening, name=F"{?}help")
await bot.change_presence(status=discord.Status.dnd, activity=activity)


for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
bot.load_extension(f"cogs.{fn[:-3]}")

bot.run(ваш токен)

import discord
import sqlite3
import random
from discord.ext import commands

def get_random_color():
return random.choice([0x4287f5, 0xf54242, 0xf5f242])

def open_account(user: discord.Member):
db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * FROM main WHERE member_id = {user.id}")
result = cursor.fetchone()

if result:
return
if not result:
sql = "INSERT INTO main(member_id, wallet, bank) VALUES(?,?,?)"
val = (user.id, 500, 0)

cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()

def check_bal_greater_than(user: discord.Member, amount: int):
db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * FROM main WHERE member_id = {user.id}")
result = cursor.fetchone()

if result[1] >= amount:
return True
return False

def add_bal(user: discord.Member, amount: int):
db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * from main WHERE member_id = {user.id}")
result = cursor.fetchone()

sql = f"UPDATE main SET wallet = ? WHERE member_id = ?"
val = (result[1] + amount, user.id)

cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()

def remove_bal(user: discord.Member, amount: int):
db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * from main WHERE member_id = {user.id}")
result = cursor.fetchone()

sql = f"UPDATE main SET wallet = ? WHERE member_id = ?"
val = (result[1] - amount, user.id)

cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()

class Economy(commands.Cog):
def __init__(self, client):
self.client = client

@commands.command(name="счёт", aliases=['баланс'])
@commands.cooldown(1, 3, commands.BucketType.user)
async def счёт(self, ctx, member: discord.Member=None):
if member == None:
member = ctx.author
open_account(member)

db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * FROM main WHERE member_id = {member.id}")
result = cursor.fetchone()

embed = discord.Embed(color=get_random_color(), timestamp=ctx.message.created_at)
embed.set_author(name=f"{member.name}'s бал", icon_url=member.avatar_url)
embed.add_field(name="казино", value=f"{result[1]}")
embed.add_field(name="банк", value=f"{result[2]}")
embed.set_footer(text=f"Requested by {ctx.author}", icon_url=member.avatar_url)
embed.set_thumbnail(url=ctx.guild.icon_url)

await ctx.send(embed=embed)

@commands.command(name="милостыня", aliases=['прошение'])
async def милостыня(self, ctx):
open_account(user=ctx.author)
possibility = random.randint(1, 5)
if possibility == 3:
return await ctx.send(
"Вы попросили денег, но вам дали примерно ничего. "
)

amount = random.randrange(600000, 2000000)

outcomes = [
f"Тебя дали **{amount}**",
f"Тебе дал Путин **{amount}**",
f"Ты попросил у США **{amount}**. И они тебе дали!"
]

add_bal(ctx.author, amount)
await ctx.send(random.choice(outcomes))

@commands.command(name="банк", aliases=['депозит'])
@commands.cooldown(1, 3, commands.BucketType.user)
async def банк(self, ctx, amount):
open_account(user=ctx.author)
db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * from main WHERE member_id = {ctx.author.id}")
result = cursor.fetchone()

if result[1] == 0:
return await ctx.send(
"Ты - банкрот. Ты что забыл?! :|"
)
done = False
if amount == "all" or amount == "max":
sql = "UPDATE main SET bank = ? WHERE member_id = ?"
val = (result[2] + result[1], ctx.author.id)
await ctx.send(f"Успешно положено **{result[1]}** в банк!")
remove_bal(ctx.author, result[1])
done = True
if not done:
try:
amount = int(amount)
except ValueError:
return await ctx.send(
"Only `integers | max | all` will be excepted as the amount"
)

if result[1] < amount:
return await ctx.send(
f"Ты не можешь взять больше чем **{result[1]}**"
)

sql = "UPDATE main SET bank = ? WHERE member_id = ?"
val = (result[2] + amount, ctx.author.id)
await ctx.send(
f"Успешно положено **{amount}** в банк!"
)
remove_bal(ctx.author, amount)

cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()


@commands.command(name="взять", aliases=['взять_деньги_из_банка'])
async def взять(self, ctx, amount: str):
open_account(user=ctx.author)
db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * FROM main WHERE member_id = {ctx.author.id}")
result = cursor.fetchone()
if result[2] == 0:
return await ctx.send(
"Внимание! Верни маме карточку! И больше так не делай!"
)
done = False
if amount == "max" or amount == "all":
sql = "UPDATE main SET bank = ? WHERE member_id = ?"
val = (0, ctx.author.id)
add_bal(ctx.author, result[2])
await ctx.send(
f"Ты успешно снял **{result[2]}** со своего банковского счёта!"
)
done = True

if not done:
try:
amount = int(amount)
except ValueError:
return await ctx.send(
"Only `integers | max | all` will be accepted"
)

if amount >= result[2]:
sql = "UPDATE main SET bank = ? WHERE member_id = ?"
val = (0, ctx.author.id)
add_bal(ctx.author, result[2])
await ctx.send(
f"Вы успешно сняли **{result[2]}** со своего банковского счёта!"
)
else:
sql = "UPDATE main SET bank = ? WHERE member_id = ?"
val = (result[2] - amount, ctx.author.id)
add_bal(ctx.author, amount)
await ctx.send(
f"Вы успешно сняли **{amount}** со своего банковского счёта!"
)

cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()

@commands.command(name='работать')
@commands.cooldown(1, 3600, commands.BucketType.user)
async def работать(self, ctx):
open_account(user=ctx.author)
chance = [1, 4]
if chance == 2:
return await ctx.send(
"Уважаемый человек, ты так трудился что тебя сняли с должности! P.s. это шутка"
)

amount = random.randrange(2000000, 6000000)
outcomes = [
f"Ты хорошо поработал **{amount}**",
f"Ты выклянчил у своего союзника **{amount}**. Круто! Но обещай больше так не делать!",
f"Ты попросил у своего союзника **{amount}**. Ну хотя бы не клянчил.",
f" **{amount}**. Пон. ",
f" **{amount}** ?! неплохо, но ты можешь лучше!"
]

await ctx.send(random.choice(outcomes))
add_bal(ctx.author, amount)

def get_rich_people(self):
db = sqlite3.connect('data/bank.sqlite')
cursor = db.cursor()
cursor.execute("SELECT * FROM main")
result = cursor.fetchall()

networths = [{"id" : member_id, "" : казино + bank} for member_id, казино, bank in result]
networths.sort(reverse=True, key=lambda x: x["networth"])

try:
return networths[0:5]
except ValueError:
return networths

@commands.command(name="рейтинг", aliases=['табл', 'таблица'])
@commands.cooldown(1, 3, commands.BucketType.user)
async def lb(self, ctx):
open_account(user=ctx.author)
rich_people = self.get_rich_people()

if len(rich_people) == 0:
return await ctx.send("Этот мир захватил буржуи... Все стали бедными :tired_face: ")

embed = discord.Embed(color=get_random_color(), timestamp=ctx.message.created_at)

first_guy, first_guy_worth = rich_people[0]["id"], rich_people[0]["networth"]
embed.add_field(
name=f"1. {ctx.guild.get_member(first_guy)} | [{first_guy}]:",
value=f"**{first_guy_worth}**",
inline=False
)

try:
second_guy, second_guy_worth = rich_people[1]["id"], rich_people[1]["networth"]
embed.add_field(
name=f"2. {ctx.guild.get_member(second_guy)} | [{second_guy}]:",
value=f"**{second_guy_worth}**",
inline=False
)
except IndexError:
pass

try:
third_guy, third_guy_worth = rich_people[2]["id"], rich_people[2]["networth"]
embed.add_field(
name=f"3. {ctx.guild.get_member(third_guy)} | [{third_guy}]:",
value=f"**{third_guy_worth}**",
inline=False
)
except IndexError:
pass

try:
fourth_guy, fourth_guy_worth = rich_people[3]["id"], rich_people[3]["networth"]
embed.add_field(
name=f"4. {ctx.guild.get_member(fourth_guy)} | [{fourth_guy}]:",
value=f"**{fourth_guy_worth}**",
inline=False
)
except IndexError:
pass

try:
fifth_guy, fifth_guy_worth = rich_people[4]["id"], rich_people[4]["networth"]
embed.add_field(
name=f"5. {ctx.guild.get_member(fifth_guy)} | [{fifth_guy}]:",
value=f"**{fifth_guy_worth}**",
inline=False
)
except IndexError:
pass

embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url)
embed.set_thumbnail(url=ctx.guild.icon_url)

await ctx.send(embed=embed)

def setup(client):
client.add_cog(Economy(client))