diff --git a/economy with mongoDB/README.md b/economy with mongoDB/README.md
index 5c62eba..492f625 100644
--- a/economy with mongoDB/README.md
+++ b/economy with mongoDB/README.md
@@ -1,12 +1,14 @@
# πQuickstart
-# clone the repository
+# Method - 1
+
+## clone the repository
```sh
git clone https://github.com/Modern-Realm/economy-bot-discord.py
```
-# Setting up the working directory & installing packages
+## Setting up the working directory & installing packages
```sh
cd "economy-bot-discord.py/economy with mongoDB"
@@ -15,9 +17,9 @@ pip install -r requirements.txt
**Note:** make sure to install **any one** of these package`(discord.py, py-cord or nextcord)`
-# Provide the secret keys/values in `.env` file
+### Provide the secret keys/values in `.env` file
-# Running the bot
+## Running the bot
```sh
python main.py
@@ -25,7 +27,31 @@ python main.py
π Your discord bot should be online and ready to use!
-
+# Method - 2
+
+## Download the source file
+
+- [click here](https://github.com/Modern-Realm/economy-bot-discord.py/releases/download/v3.0.7/economy.with.mongoDB.zip)
+to download the `zip` file.
+- extract all the files & folders
+
+## Install required packages
+
+```shell
+pip install -r requirements.txt
+```
+
+**Note:** make sure to install **any one** of these package`(discord.py, py-cord or nextcord)`
+
+## Running the bot
+
+```shell
+python main.py
+```
+
+π Your discord bot should be online and ready to use!
+
+---
# Note: for discord.py users
diff --git a/economy with mongoDB/base.py b/economy with mongoDB/base.py
new file mode 100644
index 0000000..ca8064f
--- /dev/null
+++ b/economy with mongoDB/base.py
@@ -0,0 +1,67 @@
+import os
+import discord
+
+from discord.ext import commands
+from dotenv import load_dotenv, find_dotenv
+from pycolorise.colors import *
+
+from modules import Database
+
+__all__ = [
+ "Auth",
+ "EconomyBot"
+]
+
+load_dotenv(find_dotenv(raise_error_if_not_found=True))
+
+
+class Auth:
+ # Make sure to add all details in '.env' file
+ TOKEN = os.getenv("TOKEN")
+ COMMAND_PREFIX = os.getenv("COMMAND_PREFIX")
+
+ CLUSTER_AUTH_URL = os.getenv("CLUSTER_AUTH_URL")
+ DB_NAME = os.getenv("DB_NAME")
+
+
+class EconomyBot(commands.Bot):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.db = Database(Auth.CLUSTER_AUTH_URL, Auth.DB_NAME)
+
+ async def on_ready(self):
+ await self.change_presence(
+ status=discord.Status.online,
+ activity=discord.Game(f"{Auth.COMMAND_PREFIX}help")
+ )
+
+ # if you are using 'discord.py >=v2.0' comment(remove) below code
+ print(Purple("\nLoading Cogs:"))
+ for file in os.listdir("./cogs"):
+ if file.endswith(".py"):
+ filename = file[:-3]
+ try:
+ self.load_extension(f"cogs.{filename}")
+ print(Blue(f"- {filename} β
"))
+ except:
+ print(Blue(f"- {filename} β "))
+
+ # if you are using 'discord.py >=v2.0' uncomment(add) below code
+ # print(Purple("\nLoading Cogs:"))
+ # for file in os.listdir("./cogs"):
+ # if file.endswith(".py"):
+ # filename = file[:-3]
+ # try:
+ # await client.load_extension(f"cogs.{filename}")
+ # print(Blue(f"- {filename} β
"))
+ # except:
+ # print(Blue(f"- {filename} β "))
+
+ print()
+
+ await self.db.bank.create_table()
+ await self.db.inv.create_table()
+ print(Cyan("Created/modified tables successfully"))
+
+ print(Cyan(f"{self.user.name} is online !"))
diff --git a/economy with mongoDB/cogs/admin.py b/economy with mongoDB/cogs/admin.py
index 7bc5070..d862405 100644
--- a/economy with mongoDB/cogs/admin.py
+++ b/economy with mongoDB/cogs/admin.py
@@ -8,7 +8,7 @@
it is not recommended to include these commands.
"""
-from modules.bank_funcs import *
+from base import EconomyBot
import discord
@@ -16,8 +16,9 @@
class Admin(commands.Cog):
- def __init__(self, client: commands.Bot):
+ def __init__(self, client: EconomyBot):
self.client = client
+ self.bank = self.client.db.bank
@commands.command(aliases=["addmoney"], usage=" ")
@commands.is_owner()
@@ -36,8 +37,8 @@ async def add_money(self, ctx, member: discord.Member, amount: str, mode: str =
if amount > limit:
return await ctx.reply(f"You cannot add money more than {limit:,}")
- await open_bank(member)
- await update_bank(member, +amount, mode)
+ await self.bank.open_acc(member)
+ await self.bank.update_acc(member, +amount, mode)
await ctx.reply(f"You added {amount:,} in {member.mention}'s {mode}", mention_author=False)
@commands.command(aliases=["remoney"], usage=" ")
@@ -53,16 +54,16 @@ async def remove_money(self, ctx, member: discord.Member, amount: str, mode: str
return await ctx.reply("Please enter either wallet or bank only")
amount = int(amount)
- await open_bank(member)
+ await self.bank.open_acc(member)
- users = await get_bank_data(member)
+ users = await self.bank.get_acc(member)
user_amt = users[2 if mode == "bank" else 1]
if user_amt < amount:
return await ctx.reply(
f"You can only remove {user_amt:,} from {member.mention}'s {mode}"
)
- await update_bank(member, -amount, mode)
+ await self.bank.update_acc(member, -amount, mode)
await ctx.reply(f"You removed {amount:,} from {member.mention}'s {mode}", mention_author=False)
@commands.command(usage="")
@@ -72,11 +73,11 @@ async def reset_user(self, ctx, member: discord.Member):
if member.bot:
return await ctx.reply("Bots don't have account", mention_author=False)
- users = await get_bank_data(member)
+ users = await self.bank.get_acc(member)
if users is None:
- await open_bank(member)
+ await self.bank.open_acc(member)
else:
- await reset_bank(member)
+ await self.bank.reset_acc(member)
return await ctx.reply(f"{member.mention}'s account has been reset", mention_author=False)
diff --git a/economy with mongoDB/cogs/economy.py b/economy with mongoDB/cogs/economy.py
index 4612abb..e755793 100644
--- a/economy with mongoDB/cogs/economy.py
+++ b/economy with mongoDB/cogs/economy.py
@@ -1,4 +1,4 @@
-from modules.bank_funcs import *
+from base import EconomyBot
from numpy import random
@@ -6,18 +6,19 @@
class Economy(commands.Cog):
- def __init__(self, client: commands.Bot):
+ def __init__(self, client: EconomyBot):
self.client = client
+ self.bank = self.client.db.bank
@commands.cooldown(1, 24 * 60 * 60)
@commands.command()
@commands.guild_only()
async def daily(self, ctx):
user = ctx.author
- await open_bank(user)
+ await self.bank.open_acc(user)
rand_amt = random.randint(3000, 5000)
- await update_bank(user, +rand_amt)
+ await self.bank.update_acc(user, +rand_amt)
await ctx.reply(f"Your daily pocket money is {rand_amt:,}", mention_author=False)
@commands.cooldown(1, 7 * 24 * 60 * 60)
@@ -25,10 +26,10 @@ async def daily(self, ctx):
@commands.guild_only()
async def weekly(self, ctx):
user = ctx.author
- await open_bank(user)
+ await self.bank.open_acc(user)
rand_amt = random.randint(7000, 10000)
- await update_bank(user, +rand_amt)
+ await self.bank.update_acc(user, +rand_amt)
await ctx.reply(f"Your weekly pocket money is {rand_amt:,}", mention_author=False)
@commands.cooldown(1, 30 * 24 * 60 * 60)
@@ -36,10 +37,10 @@ async def weekly(self, ctx):
@commands.guild_only()
async def monthly(self, ctx):
user = ctx.author
- await open_bank(user)
+ await self.bank.open_acc(user)
rand_amt = random.randint(30000, 50000)
- await update_bank(user, +rand_amt)
+ await self.bank.update_acc(user, +rand_amt)
await ctx.reply(f"Your monthly pocket money is {rand_amt:,}", mention_author=False)
diff --git a/economy with mongoDB/cogs/events.py b/economy with mongoDB/cogs/events.py
index 4f3279b..b5a000d 100644
--- a/economy with mongoDB/cogs/events.py
+++ b/economy with mongoDB/cogs/events.py
@@ -1,4 +1,4 @@
-from config import Auth
+from base import Auth
import discord
diff --git a/economy with mongoDB/cogs/fun.py b/economy with mongoDB/cogs/fun.py
index f9d8db9..79217a6 100644
--- a/economy with mongoDB/cogs/fun.py
+++ b/economy with mongoDB/cogs/fun.py
@@ -1,4 +1,4 @@
-from modules.bank_funcs import *
+from base import EconomyBot
import discord
import asyncio
@@ -9,21 +9,22 @@
class Fun(commands.Cog):
- def __init__(self, client: commands.Bot):
+ def __init__(self, client: EconomyBot):
self.client = client
+ self.bank = self.client.db.bank
@commands.command(aliases=["cf", "coinflip"], usage=" ")
@commands.guild_only()
async def coin_flip(self, ctx, bet_on: str, amount: int):
user = ctx.author
- await open_bank(user)
+ await self.bank.open_acc(user)
bet_on = "heads" if "h" in bet_on.lower() else "tails"
if not 500 <= amount <= 5000:
return await ctx.reply("You can only bet amount between 500 and 5000", mention_author=False)
reward = round(amount / 2)
- users = await get_bank_data(user)
+ users = await self.bank.get_acc(user)
if users[1] < amount:
return await ctx.reply("You don't have enough money", mention_author=False)
@@ -31,21 +32,21 @@ async def coin_flip(self, ctx, bet_on: str, amount: int):
result = random.choice(coin)
if result != bet_on:
- await update_bank(user, -amount)
+ await self.bank.update_acc(user, -amount)
return await ctx.reply(f"Got {result}, you lost {amount:,}", mention_author=False)
- await update_bank(user, +reward)
+ await self.bank.update_acc(user, +reward)
return await ctx.reply(f"Got {result}, you won {amount + reward:,}", mention_author=False)
@commands.command(usage=" ")
async def dice(self, ctx, amount: int, bet_on: int = 6):
user = ctx.author
- await open_bank(user)
+ await self.bank.open_acc(user)
rdice = [1, 2, 3, 4, 5, 6]
if bet_on not in rdice:
@@ -115,17 +116,17 @@ async def dice(self, ctx, amount: int, bet_on: int = 6):
if not 1000 <= amount <= 5000:
return await ctx.reply("You can only bet amount between 1000 and 5000", mention_author=False)
- users = await get_bank_data(user)
+ users = await self.bank.get_acc(user)
if users[1] < amount:
return await ctx.reply("You don't have enough money", mention_author=False)
rand_num = random.choice(rdice)
if rand_num != bet_on:
- await update_bank(user, -amount)
+ await self.bank.update_acc(user, -amount)
return await ctx.reply(f"Got {rand_num}, you lost {amount:,}", mention_author=False)
reward = round(amount / 2)
- await update_bank(user, +reward)
+ await self.bank.update_acc(user, +reward)
await ctx.reply(f"Got {rand_num}, you won {amount + reward:,}", mention_author=False)
diff --git a/economy with mongoDB/cogs/inventory.py b/economy with mongoDB/cogs/inventory.py
index 4d8855f..b87d114 100644
--- a/economy with mongoDB/cogs/inventory.py
+++ b/economy with mongoDB/cogs/inventory.py
@@ -1,5 +1,4 @@
-from modules.bank_funcs import *
-from modules.inventory_funcs import *
+from base import EconomyBot
import discord
@@ -7,8 +6,10 @@
class Inventory(commands.Cog):
- def __init__(self, client: commands.Bot):
+ def __init__(self, client: EconomyBot):
self.client = client
+ self.bank = self.client.db.bank
+ self.inv = self.client.db.inv
@commands.command(aliases=["inv"], usage="")
@commands.guild_only()
@@ -17,15 +18,15 @@ async def inventory(self, ctx, member: discord.Member = None):
user_av = user.display_avatar or user.default_avatar
if user.bot:
return await ctx.reply("Bot's don't have account", mention_author=False)
- await open_inv(user)
+ await self.bank.open_acc(user)
em = discord.Embed(color=0x00ff00)
x = 1
- for item in shop_items:
+ for item in self.inv.shop_items:
name = item["name"]
item_id = item["id"]
- data = await update_inv(user, 0, name)
+ data = await self.inv.update_acc(user, 0, name)
if data[0] >= 1:
x += 1
em.add_field(
@@ -40,40 +41,42 @@ async def inventory(self, ctx, member: discord.Member = None):
@commands.command(usage="")
async def buy(self, ctx, *, item_name: str):
user = ctx.author
- await open_bank(user)
- if item_name.lower() not in [item["name"].lower() for item in shop_items]:
+ await self.bank.open_acc(user)
+ await self.inv.open_acc(user)
+
+ if item_name.lower() not in [item["name"].lower() for item in self.inv.shop_items]:
return await ctx.reply(f"Theirs no item named `{item_name}`", mention_author=False)
- users = await get_bank_data(user)
- for item in shop_items:
+ users = await self.bank.get_acc(user)
+ for item in self.inv.shop_items:
if item_name == item["name"].lower():
- await open_inv(user)
if users[1] < item["cost"]:
return await ctx.reply(f"You don't have enough money to buy {item['name']}",
mention_author=False)
- await update_inv(user, +1, item["name"])
- await update_bank(user, -item["cost"])
+ await self.inv.update_acc(user, +1, item["name"])
+ await self.bank.update_acc(user, -item["cost"])
return await ctx.reply(f"You bought {item_name}", mention_author=False)
@commands.command(usage="")
async def sell(self, ctx, *, item_name: str):
user = ctx.author
- await open_bank(user)
- if item_name.lower() not in [item["name"].lower() for item in shop_items]:
+ await self.bank.open_acc(user)
+ await self.inv.open_acc(user)
+
+ if item_name.lower() not in [item["name"].lower() for item in self.inv.shop_items]:
return await ctx.reply(f"Theirs no item named `{item_name}`", mention_author=False)
- for item in shop_items:
+ for item in self.inv.shop_items:
if item_name.lower() == item["name"].lower():
cost = int(round(item["cost"] / 2, 0))
- quantity = await update_inv(user, 0, item["name"])
+ quantity = await self.inv.update_acc(user, 0, item["name"])
if quantity[0] < 1:
return await ctx.reply(f"You don't have {item['name']} in your inventory",
mention_author=False)
- await open_inv(user)
- await update_inv(user, -1, item["name"])
- await update_bank(user, +cost)
+ await self.inv.update_acc(user, -1, item["name"])
+ await self.bank.update_acc(user, +cost)
return await ctx.reply(f"You sold {item_name} for {cost:,}", mention_author=False)
diff --git a/economy with mongoDB/cogs/mainbank.py b/economy with mongoDB/cogs/mainbank.py
index a1811c2..0333fb2 100644
--- a/economy with mongoDB/cogs/mainbank.py
+++ b/economy with mongoDB/cogs/mainbank.py
@@ -1,4 +1,4 @@
-from modules.bank_funcs import *
+from base import EconomyBot
import discord
@@ -7,8 +7,9 @@
class MainBank(commands.Cog):
- def __init__(self, client: commands.Bot):
+ def __init__(self, client: EconomyBot):
self.client = client
+ self.bank = self.client.db.bank
@commands.command(aliases=["bal"], usage=f"")
@commands.guild_only()
@@ -17,9 +18,9 @@ async def balance(self, ctx, member: discord.Member = None):
user_av = user.display_avatar or user.default_avatar
if user.bot:
return await ctx.reply("Bot's don't have account", mention_author=False)
- await open_bank(user)
+ await self.bank.open_acc(user)
- users = await get_bank_data(user)
+ users = await self.bank.get_acc(user)
wallet_amt = users[1]
bank_amt = users[2]
net_amt = int(wallet_amt + bank_amt)
@@ -36,14 +37,14 @@ async def balance(self, ctx, member: discord.Member = None):
@commands.guild_only()
async def withdraw(self, ctx, amount: str):
user = ctx.author
- await open_bank(user)
+ await self.bank.open_acc(user)
- users = await get_bank_data(user)
+ users = await self.bank.get_acc(user)
bank_amt = users[2]
if amount.lower() == "all" or amount.lower() == "max":
- await update_bank(user, +1 * bank_amt)
- await update_bank(user, -1 * bank_amt, "bank")
+ await self.bank.update_acc(user, +1 * bank_amt)
+ await self.bank.update_acc(user, -1 * bank_amt, "bank")
return await ctx.reply(f"You withdrew {bank_amt:,} in your wallet", mention_author=False)
amount = int(amount)
@@ -52,21 +53,21 @@ async def withdraw(self, ctx, amount: str):
if amount < 0:
return await ctx.reply("Enter a valid amount !", mention_author=False)
- await update_bank(user, +amount)
- await update_bank(user, -amount, "bank")
+ await self.bank.update_acc(user, +amount)
+ await self.bank.update_acc(user, -amount, "bank")
await ctx.reply(f"You withdrew {amount:,} from your bank", mention_author=False)
@commands.command(aliases=["dep"], usage="")
@commands.guild_only()
async def deposit(self, ctx, amount: str):
user = ctx.author
- await open_bank(user)
+ await self.bank.open_acc(user)
- users = await get_bank_data(user)
+ users = await self.bank.get_acc(user)
wallet_amt = users[1]
if amount.lower() == "all" or amount.lower() == "max":
- await update_bank(user, -wallet_amt)
- await update_bank(user, +wallet_amt, "bank")
+ await self.bank.update_acc(user, -wallet_amt)
+ await self.bank.update_acc(user, +wallet_amt, "bank")
return await ctx.reply(f"You deposited {wallet_amt:,} in your bank", mention_author=False)
amount = int(amount)
@@ -75,8 +76,8 @@ async def deposit(self, ctx, amount: str):
if amount < 0:
return await ctx.reply(f"Enter a valid amount !", mention_author=False)
- await update_bank(user, -amount)
- await update_bank(user, +amount, "bank")
+ await self.bank.update_acc(user, -amount)
+ await self.bank.update_acc(user, +amount, "bank")
await ctx.reply(f"You deposited {amount:,} in your bank", mention_author=False)
@commands.command(usage=" ")
@@ -86,24 +87,24 @@ async def send(self, ctx, member: discord.Member, amount: int):
if member.bot:
return await ctx.reply("Bot's don't have account", mention_author=False)
- await open_bank(user)
- await open_bank(member)
+ await self.bank.open_acc(user)
+ await self.bank.open_acc(member)
- users = await get_bank_data(user)
+ users = await self.bank.get_acc(user)
wallet_amt = users[1]
if amount <= 0:
return await ctx.reply("Enter a valid amount !", mention_author=False)
if amount > wallet_amt:
return await ctx.reply("You don't have enough amount", mention_author=False)
- await update_bank(user, -amount)
- await update_bank(member, +amount)
+ await self.bank.update_acc(user, -amount)
+ await self.bank.update_acc(member, +amount)
await ctx.reply(f"You sent {amount:,} to {member.mention}", mention_author=False)
@commands.command(aliases=["lb"])
@commands.guild_only()
async def leaderboard(self, ctx):
- users = await get_networth_lb()
+ users = await self.bank.get_networth_lb()
data = []
index = 1
diff --git a/economy with mongoDB/cogs/shop.py b/economy with mongoDB/cogs/shop.py
index 918f430..3611b12 100644
--- a/economy with mongoDB/cogs/shop.py
+++ b/economy with mongoDB/cogs/shop.py
@@ -1,4 +1,4 @@
-from modules.inventory_funcs import *
+from base import EconomyBot
import discord
@@ -6,21 +6,22 @@
class Shop(commands.Cog):
- def __init__(self, client: commands.Bot):
+ def __init__(self, client: EconomyBot):
self.client = client
+ self.inv = self.client.db.inv
@commands.group(invoke_without_command=True)
@commands.guild_only()
async def shop(self, ctx):
user = ctx.author
- await open_inv(user)
+ await self.inv.open_acc(user)
em = discord.Embed(
title="SHOP",
color=discord.Color(0x00ff00)
)
x = 1
- for item in shop_items:
+ for item in self.inv.shop_items:
name = item["name"]
cost = item["cost"]
item_id = item["id"]
@@ -37,7 +38,7 @@ async def shop(self, ctx):
@commands.guild_only()
async def info(self, ctx, *, item_name: str):
user = ctx.author
- for item in shop_items:
+ for item in self.inv.shop_items:
name = item["name"]
cost = item["cost"]
item_info = item["info"]
diff --git a/economy with mongoDB/config.py b/economy with mongoDB/config.py
deleted file mode 100644
index b3f0d61..0000000
--- a/economy with mongoDB/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from os import getenv
-from dotenv import load_dotenv, find_dotenv
-
-load_dotenv(find_dotenv(raise_error_if_not_found=True))
-
-
-class Auth:
- # Make sure to add all details in '.env' file
- TOKEN = getenv("TOKEN")
- COMMAND_PREFIX = getenv("COMMAND_PREFIX")
-
- CLUSTER_AUTH_URL = getenv("CLUSTER_AUTH_URL")
- DB_NAME = getenv("DB_NAME")
diff --git a/economy with mongoDB/main.py b/economy with mongoDB/main.py
index fca6aeb..140aed9 100644
--- a/economy with mongoDB/main.py
+++ b/economy with mongoDB/main.py
@@ -1,56 +1,9 @@
-from modules import bank_funcs, inventory_funcs
-from config import Auth
+from base import Auth, EconomyBot
-import os
import discord
-from pycolorise.colors import *
-from discord.ext import commands
-
intents = discord.Intents.all()
-client = commands.Bot(command_prefix=Auth.COMMAND_PREFIX, intents=intents, auto_sync_commands=True)
-
-
-@client.event
-async def on_ready():
- await client.change_presence(
- status=discord.Status.online,
- activity=discord.Game(f"{Auth.COMMAND_PREFIX}help")
- )
-
- # if you are using 'discord.py >=v2.0' comment(remove) below code
- print(Purple("\nLoading Cogs:"))
- for file in os.listdir("./cogs"):
- if file.endswith(".py"):
- filename = file[:-3]
- try:
- client.load_extension(f"cogs.{filename}")
- print(Blue(f"- {filename} β
"))
- except:
- print(Blue(f"- {filename} β "))
-
- # if you are using 'discord.py >=v2.0' uncomment(add) below code
- # print(Purple("\nLoading Cogs:"))
- # for file in os.listdir("./cogs"):
- # if file.endswith(".py"):
- # filename = file[:-3]
- # try:
- # await client.load_extension(f"cogs.{filename}")
- # print(Blue(f"- {filename} β
"))
- # except:
- # print(Blue(f"- {filename} β "))
-
- print()
- await inventory_funcs.DB.connect()
- if not inventory_funcs.DB.is_connected:
- raise RuntimeError("Database access denied")
-
- await bank_funcs.create_table()
- await inventory_funcs.create_table()
- print(Cyan("Created/modified tables successfully"))
-
- print(Cyan(f"{client.user.name} is online !"))
-
+client = EconomyBot(command_prefix=Auth.COMMAND_PREFIX, intents=intents)
if __name__ == "__main__":
# Make sure to add Bot Token in '.env' file
diff --git a/economy with mongoDB/modules/__init__.py b/economy with mongoDB/modules/__init__.py
new file mode 100644
index 0000000..65fdceb
--- /dev/null
+++ b/economy with mongoDB/modules/__init__.py
@@ -0,0 +1,15 @@
+from .ext import Database as DB
+from .bank_funcs import Bank
+from .inventory_funcs import Inventory
+
+__all__ = [
+ "Database"
+]
+
+
+class Database(DB):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.bank = Bank(self)
+ self.inv = Inventory(self)
diff --git a/economy with mongoDB/modules/bank_funcs.py b/economy with mongoDB/modules/bank_funcs.py
index 432e639..711dbe0 100644
--- a/economy with mongoDB/modules/bank_funcs.py
+++ b/economy with mongoDB/modules/bank_funcs.py
@@ -1,4 +1,4 @@
-from config import Auth
+from modules.ext import Database
import discord
@@ -8,12 +8,7 @@
from pymongo.collection import Collection
__all__ = [
- "DB",
- "open_bank",
- "get_bank_data",
- "update_bank",
- "reset_bank",
- "get_networth_lb"
+ "Bank"
]
TABLE_NAME = "bank"
@@ -27,73 +22,50 @@
cols = [key for key in document.keys()]
-class DataBase:
- def __init__(self):
- self.cluster: Optional[MongoClient[Mapping[str, Any]]] = None
- self.db: Optional[MongoDB[Mapping[str, Any]]] = None
+class Bank:
+ def __init__(self, database: Database):
+ self._conn = database
- async def connect(self):
- try:
- self.cluster = MongoClient(Auth.CLUSTER_AUTH_URL)
- self.db = self.cluster[Auth.DB_NAME]
- except errors.OperationFailure:
- self.cluster = None
- return self
+ async def create_table(self):
+ if TABLE_NAME not in self._conn.db.list_collection_names():
+ self._conn.db.create_collection(TABLE_NAME)
- @property
- def is_connected(self) -> bool:
- return self.cluster is not None
+ async def open_acc(self, user: discord.Member) -> None:
+ user_data = self._conn.cursor(TABLE_NAME).find_one({"_id": user.id})
+ if user_data is not None:
+ return
- def cursor(self, table_name: str) -> Collection[Mapping[str, Any]]:
- return self.db[table_name]
+ doc = document.copy()
+ doc.update(_id=user.id)
+ self._conn.cursor(TABLE_NAME).insert_one(doc)
+ async def get_acc(self, user: discord.Member, mode: str = None) -> Optional[Any]:
+ user_data = self._conn.cursor(TABLE_NAME).find_one({"_id": user.id})
+ if mode is None:
+ return [_ for _ in user_data.values()]
-DB = DataBase()
+ return user_data.get(mode)
+ async def update_acc(
+ self, user: discord.Member, amount: Union[float, int] = 0, mode: str = "wallet"
+ ) -> Optional[Any]:
+ self._conn.cursor(TABLE_NAME).update_one(
+ {"_id": user.id}, {"$inc": {mode: amount}}
+ )
-async def create_table():
- if TABLE_NAME not in DB.db.list_collection_names():
- DB.db.create_collection(TABLE_NAME)
+ return await self.get_acc(user, mode)
+ async def reset_acc(self, user: discord.Member) -> None:
+ self._conn.cursor(TABLE_NAME).delete_one({"_id": user.id})
+ await self.open_acc(user)
-async def open_bank(user: discord.Member) -> None:
- user_data = DB.cursor(TABLE_NAME).find_one({"_id": user.id})
- if user_data is not None:
- return
+ async def get_networth_lb(self) -> List[Any]:
+ user_data = self._conn.cursor(TABLE_NAME).aggregate([
+ {"$addFields": {"sum": {"$add": ["$wallet", "$bank"]}}},
+ {"$sort": {"sum": -1}}
+ ])
+ # sorted_data = []
+ # for val in user_data:
+ # sorted_data.append([_ for _ in val.values()])
- doc = document.copy()
- doc.update(_id=user.id)
- DB.cursor(TABLE_NAME).insert_one(doc)
-
-
-async def get_bank_data(user: discord.Member, mode: str = None) -> Optional[Any]:
- user_data = DB.cursor(TABLE_NAME).find_one({"_id": user.id})
- if mode is None:
- return [_ for _ in user_data.values()]
-
- return user_data.get(mode)
-
-
-async def update_bank(user: discord.Member, amount: Union[float, int] = 0, mode: str = "wallet") -> Optional[Any]:
- DB.cursor(TABLE_NAME).update_one(
- {"_id": user.id}, {"$inc": {mode: amount}}
- )
-
- return await get_bank_data(user, mode)
-
-
-async def reset_bank(user: discord.Member) -> None:
- DB.cursor(TABLE_NAME).delete_one({"_id": user.id})
- await open_bank(user)
-
-
-async def get_networth_lb() -> List[Any]:
- user_data = DB.cursor(TABLE_NAME).aggregate([
- {"$addFields": {"sum": {"$add": ["$wallet", "$bank"]}}},
- {"$sort": {"sum": -1}}
- ])
- sorted_data = []
- for val in user_data:
- sorted_data.append([_ for _ in val.values()])
-
- return sorted_data
+ return [[_ for _ in val.values()] for val in user_data]
diff --git a/economy with mongoDB/modules/ext.py b/economy with mongoDB/modules/ext.py
new file mode 100644
index 0000000..43f6940
--- /dev/null
+++ b/economy with mongoDB/modules/ext.py
@@ -0,0 +1,24 @@
+from typing import Mapping, Any
+from pymongo import MongoClient
+from pymongo.database import Database as MongoDB
+from pymongo.collection import Collection
+
+
+class Database:
+ def __init__(
+ self, cluster_url: str, db_name: str, min_pool_size: int = 10, max_pool_size: int = 15
+ ) -> None:
+ self.cluster_url = cluster_url
+ self.db_name = db_name
+
+ self._conn = MongoClient(self.cluster_url, minPoolSize=min_pool_size, maxPoolSize=max_pool_size)
+
+ @property
+ def db(self) -> MongoDB[Mapping[str, Any]]:
+ return self._conn[self.db_name]
+
+ def cursor(self, table_name: str) -> Collection[Mapping[str, Any]]:
+ return self.db[table_name]
+
+ def __del__(self):
+ self._conn.close()
diff --git a/economy with mongoDB/modules/inventory_funcs.py b/economy with mongoDB/modules/inventory_funcs.py
index 289dd3d..f824784 100644
--- a/economy with mongoDB/modules/inventory_funcs.py
+++ b/economy with mongoDB/modules/inventory_funcs.py
@@ -1,16 +1,11 @@
-from modules.bank_funcs import DB
+from modules.ext import Database
import discord
-from typing import Union, Any, Optional
+from typing import List, Union, Any, Optional
__all__ = [
- "DB",
- "shop_items",
- "open_inv",
- "get_inv_data",
- "update_inv",
- "change_inv"
+ "Inventory"
]
TABLE_NAME = "inventory" # Enter the table name here (tip:- use only lowercase letters)
@@ -24,41 +19,49 @@
item_names = [item["name"] for item in shop_items]
-async def create_table():
- if TABLE_NAME not in DB.db.list_collection_names():
- DB.db.create_collection(TABLE_NAME)
+class Inventory:
+ def __init__(self, database: Database):
+ self._conn = database
+ @property
+ def shop_items(self) -> List:
+ return shop_items
-async def open_inv(user: discord.Member):
- doc = {"_id": user.id}
- user_data = DB.cursor(TABLE_NAME).find_one(doc)
- if user_data is not None:
- return
+ async def create_table(self):
+ if TABLE_NAME not in self._conn.db.list_collection_names():
+ self._conn.db.create_collection(TABLE_NAME)
- for name in item_names:
- doc.setdefault(name, 0)
- DB.cursor(TABLE_NAME).insert_one(doc)
+ async def open_acc(self, user: discord.Member):
+ doc = {"_id": user.id}
+ user_data = self._conn.cursor(TABLE_NAME).find_one(doc)
+ if user_data is not None:
+ return
+ for name in item_names:
+ doc.setdefault(name, 0)
+ self._conn.cursor(TABLE_NAME).insert_one(doc)
-async def get_inv_data(user: discord.Member, mode: str = None) -> Optional[Any]:
- user_data = DB.cursor(TABLE_NAME).find_one({"_id": user.id})
- if mode is None:
- return [_ for _ in user_data.values()]
+ async def get_acc(self, user: discord.Member, mode: str = None) -> Optional[Any]:
+ user_data = self._conn.cursor(TABLE_NAME).find_one({"_id": user.id})
+ if mode is None:
+ return [_ for _ in user_data.values()]
- return user_data.get(mode)
+ return user_data.get(mode)
+ async def update_acc(
+ self, user: discord.Member, amount: Union[float, int], mode: str
+ ) -> Optional[Any]:
+ self._conn.cursor(TABLE_NAME).update_one(
+ {"_id": user.id}, {"$inc": {mode: amount}}
+ )
-async def update_inv(user: discord.Member, amount: Union[float, int], mode: str) -> Optional[Any]:
- DB.cursor(TABLE_NAME).update_one(
- {"_id": user.id}, {"$inc": {mode: amount}}
- )
+ return [await self.get_acc(user, mode)]
- return [await get_inv_data(user, mode)]
+ async def change_acc(
+ self, user: discord.Member, amount: Union[float, int, None], mode: str
+ ) -> Optional[Any]:
+ self._conn.cursor(TABLE_NAME).update_one(
+ {"_id": user.id}, {"$set": {mode: amount}}
+ )
-
-async def change_inv(user: discord.Member, amount: Union[float, int, None], mode: str) -> Optional[Any]:
- DB.cursor(TABLE_NAME).update_one(
- {"_id": user.id}, {"$set": {mode: amount}}
- )
-
- return await get_inv_data(user, mode)
+ return await self.get_acc(user, mode)