Untitled
unknown
plain_text
a year ago
36 kB
10
Indexable
import typing
import discord
import random
import asyncio
from discord import app_commands
from discord.ext import commands
import sqlite3
import os
import re
from datetime import datetime, timedelta
import math
from math import ceil
from typing import List, Union
from discord.ui import Button, View
import difflib
class InventoryPaginator(discord.ui.View):
def __init__(self, ctx, inventory, shop_items, items, member):
super().__init__(timeout=60)
self.ctx = ctx
self.inventory = inventory
self.items = items
self.shop_items = shop_items
self.current_page = 0
self.items_per_page = 5
self.pages = math.ceil(len(inventory) / self.items_per_page)
self.moneyemoji = "<a:MoneyGIFNexus:1274650931992072205>"
self.member = member
# Sort inventory by total value
self.sorted_inventory = self.sort_inventory_by_value()
self.pages = math.ceil(len(self.sorted_inventory) / self.items_per_page)
def sort_inventory_by_value(self):
def get_item_total_value(item_tuple):
item_name, quantity = item_tuple
item_info = self.shop_items.get(item_name, self.items.get(item_name, {}))
price = item_info.get('price', 0)
return price * quantity
return sorted(self.inventory.items(), key=get_item_total_value, reverse=True)
def check_author(self, interaction: discord.Interaction):
if interaction.user != self.ctx.author:
return False
return True
def update_button_states(self):
self.first_page_button.disabled = self.current_page == 0
self.previous_button.disabled = self.current_page == 0
self.next_button.disabled = self.current_page == self.pages - 1
self.last_page_button.disabled = self.current_page == self.pages - 1
print(f"InventoryPaginator - Current page: {self.current_page}, Total pages: {self.pages}")
print(f"Button states: First: {self.first_page_button.disabled}, Prev: {self.previous_button.disabled}, Next: {self.next_button.disabled}, Last: {self.last_page_button.disabled}")
@discord.ui.button(emoji='<:DLArrow:1274651134283350016>', style=discord.ButtonStyle.grey)
async def first_page_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
self.current_page = 0
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
@discord.ui.button(emoji='<:SLArrow:1274651192076800041>', style=discord.ButtonStyle.grey)
async def previous_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
if self.current_page > 0:
self.current_page -= 1
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
@discord.ui.button(emoji='<:SRArrow:1274651171776233523>', style=discord.ButtonStyle.grey)
async def next_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
if self.current_page < self.pages - 1:
self.current_page += 1
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
@discord.ui.button(emoji='<:DRArrow:1274651105061634090>', style=discord.ButtonStyle.grey)
async def last_page_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
self.current_page = self.pages - 1
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
def create_embed(self):
start = self.current_page * self.items_per_page
end = start + self.items_per_page
items = self.sorted_inventory[start:end]
embed = discord.Embed(title=f"{self.member.display_name}'s Inventory", color=discord.Color.blue())
for item, quantity in items:
item_info = self.shop_items.get(item, self.items.get(item, {}))
emoji = item_info.get('emoji', '')
price = item_info.get('price', 0)
total_value = price * quantity
embed.add_field(name=f"{emoji} {item.capitalize()}", value=f"**Quantity:** `{quantity}`\n**Total Value:** {self.moneyemoji} `{total_value:,}`", inline=False)
#embed.set_thumbnail(url=self.ctx.member.avatar.url)
embed.set_thumbnail(url=self.member.avatar.url)
embed.set_footer(text=f"Page {self.current_page + 1} of {self.pages}")
return embed
async def run(self):
self.update_button_states()
message = await self.ctx.send(embed=self.create_embed(), view=self)
self.message = message
class ShopPaginator(discord.ui.View):
def __init__(self, ctx, shop_items):
super().__init__(timeout=60)
self.ctx = ctx
self.shop_items = shop_items
self.current_page = 0
self.items_per_page = 4
self.pages = math.ceil(len(shop_items) / self.items_per_page)
self.moneyemoji = "<a:MoneyGIFNexus:1274650931992072205>"
def check_author(self, interaction: discord.Interaction):
if interaction.user != self.ctx.author:
return False
return True
def update_button_states(self):
self.first_page_button.disabled = self.current_page == 0
self.previous_button.disabled = self.current_page == 0
self.next_button.disabled = self.current_page == self.pages - 1
self.last_page_button.disabled = self.current_page == self.pages - 1
print(f"ShopPaginator - Current page: {self.current_page}, Total pages: {self.pages}")
print(f"Button states: First: {self.first_page_button.disabled}, Prev: {self.previous_button.disabled}, Next: {self.next_button.disabled}, Last: {self.last_page_button.disabled}")
@discord.ui.button(emoji='<:DLArrow:1274651134283350016>', style=discord.ButtonStyle.grey)
async def first_page_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
self.current_page = 0
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
@discord.ui.button(emoji='<:SLArrow:1274651192076800041>', style=discord.ButtonStyle.grey)
async def previous_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
if self.current_page > 0:
self.current_page -= 1
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
@discord.ui.button(emoji='<:SRArrow:1274651171776233523>', style=discord.ButtonStyle.grey)
async def next_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
if self.current_page < self.pages - 1:
self.current_page += 1
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
@discord.ui.button(emoji='<:DRArrow:1274651105061634090>', style=discord.ButtonStyle.grey)
async def last_page_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.check_author(interaction):
await interaction.response.send_message("This is not for you.", ephemeral=True)
return
self.current_page = self.pages - 1
self.update_button_states()
await interaction.response.edit_message(embed=self.create_embed(), view=self)
def create_embed(self):
start = self.current_page * self.items_per_page
end = start + self.items_per_page
items = list(self.shop_items.items())[start:end]
embed = discord.Embed(title="Shop", description="Welcome to the shop! Here are the items available for purchases.", color=0x00ff00)
for item, info in items:
embed.add_field(
name=f"{info['emoji']} {item.capitalize()}",
value=f"{info['description']}\n - Price: {self.moneyemoji} {self.format_money(info['price'])}",
inline=False)
embed.set_footer(text=f"Page {self.current_page + 1} of {self.pages}")
return embed
def format_money(self, amount):
return "{:,}".format(amount)
async def run(self):
self.update_button_states()
message = await self.ctx.send(embed=self.create_embed(), view=self)
self.message = message
class Economy(commands.Cog):
def __init__(self, client):
self.client = client
self.db_path = os.path.join('Cogs', 'economy.db')
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
self.create_tables()
self.active_commands = {}
self.cooldowns = {}
self.moneyemoji = "<a:MoneyGIFNexus:1274650931992072205>"
self.shop_items = {
"Apple": {'price': 2000, 'description': '''> They say "An apple a day keeps the Doctor away." `Tech's` favourite fruit.''', 'emoji': '๐', 'rarity': 'Common'},
'Watch': {'price': 50000, 'description': '''> It was the watch that `Tech` got when he turned 15. A Gyro Watch.''', 'emoji': 'โ', 'rarity': 'Rare'},
'Mobile': {'price': 80000, 'description': '''> This is the Mobile in which `AK` learned how to play CODM. A really powerful Phone.''', 'emoji': '๐ฑ', 'rarity': 'Rare'},
'Laptop': {'price': 100000, 'description': '''> This is the very first Laptop that `Tech` got when he learned CS. It was the laptop in which Nexus's prototype was made.''', 'emoji': '๐ป', 'rarity': 'Epic'},
"Bank Slip": {'price': 200000, 'description': '> Use this item to increase your bank limit by `70k-170k`.', 'emoji': '๐งพ', 'rarity': 'Rare'},
'Medal': {'price': 500000, 'description': '''> A Medal Gifted to `Zack` by `Tech`, for his contributions in Nexus's Development.''', 'emoji': '๐
', 'rarity': 'Epic'},
'Trophy': {'price': 20000000, 'description': '> This was the Trophy which `Tech` had won in an Abacus competition when he was 10 yrs old.', 'emoji': '๐', 'rarity': 'Legendary'},
'Crown': {'price': 80000000, 'description': '> The Crown of Power. If you got this than you have some true Power.', 'emoji': '๐', 'rarity': 'Legendary'},
"AK's Credit Card": {'price': 150000000, 'description': "> AK's Credit Card, which you nerds can use to get random amount of money. Good Luck", 'emoji': '๐ณ', 'rarity': 'Godly'},
"Tech's Banana": {'price': 500000000, 'emoji': '๐', 'description': "> A Banana, Use it to DM Tech.", 'rarity': 'Godly'}
}
self.items = {
"Tech's butterfly": {
'price': 40000000,
'emoji': '๐ฆ',
'description': "> Legend has it that it is `Tech's Butterfly` which he lost when he was a kid. If you got this, then you've earned his respect.",
'rarity': 'Epic'
},
"Tech's cake": {
'price': 7000000,
'emoji': '๐ฐ',
'description': "> This is `Tech's Birthday Cake`. He ate all of it when he was 13. If you got this, then you're lucky to have it because no one has it.",
'rarity': 'Epic'
},
"Tech's Camera": {
'price': 10000000,
'emoji': '๐ท',
'description': "> This is `Tech's Camera`. It has some good and funny memories captured.",
'rarity': 'Rare'
},
"AK's Credit Card": {
'price': 150000000,
'emoji': '๐ณ',
'description': "> This is `AK's Credit Card`. Using this item will give you some coins ranging from **100m-300m**.",
'rarity': 'Legendary'
},
"Apple": {
'price': 2000,
'emoji': '๐',
'description': "> This is an apple. Can not be consumed.",
'rarity': 'Common'
},
"Tech's Banana": {
'price': 500000000,
'emoji': '๐',
'description': "> This is `Tech's Banana`. Using this will send him a DM saying that you have used this item.You can can also add a custom message.",
'rarity': 'Godly'
},
"Stack Of Cash": {
'price': 30000000,
'emoji': '๐ต',
'description': "> This is the cash which `Tech` had made from hardwork but was stolen by a thief. If you got this, keep it safe.",
'rarity': 'Epic'
},
"AK's Gemstone": {
'price': 20000000,
'emoji': '๐',
'description': "> It is the `AK's Gemstone`. It was really precious to him. It is a very sacred and a rare stone, if you ever manage to get it, you must protect it at all costs.",
'rarity': 'Epic'
},
"Zack's Sunglasses": {
'price': 20000000,
'emoji': '๐',
'description': "> These are `Zack's Sunglasses`. He's just too cool. He was a big contributor in the development of Nexus.",
'rarity': 'Epic'
},
"Party Poppers": {
'price': 10000,
'emoji': '๐',
'description': "> These are `Party Poppers`. An item to celebrate Nexus's birthday.",
'rarity': 'Rare'
},
"AK's Boots": {
'price': 2000000,
'emoji': '๐ฅพ',
'description': "> These are `AK's Boots`. These were the boots AK had bought from his first earnings.",
'rarity': 'Common'
}
}
async def item_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
all_items = {**self.shop_items, **self.items}
return [
app_commands.Choice(name=f"{name}", value=name)
for name, data in all_items.items()
if current.lower() in name.lower()
][:25] # Discord limits to 25 choices
async def shop_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
all_items = {**self.shop_items}
return [
app_commands.Choice(name=f"{name}", value=name)
for name, data in all_items.items()
if current.lower() in name.lower()
][:25] # Discord limits to 25 choices
def handle_death(self, user_id):
wallet_balance = self.get_wallet_balance(user_id)
loss_amount = random.randint(int(wallet_balance * 0.2), int(wallet_balance * 0.5))
self.update_balance(user_id, -loss_amount)
inventory = self.get_inventory(user_id)
eligible_items = [item for item, quantity in inventory.items()
if self.items.get(item, {}).get('rarity', '') not in ['Legendary', 'Godly']]
lost_items = {}
if eligible_items:
lost_item = random.choice(eligible_items)
max_loss = min(inventory[lost_item], 3)
lost_quantity = random.randint(1, max_loss)
self.update_inventory(user_id, lost_item, -lost_quantity)
lost_items[lost_item] = lost_quantity
return loss_amount, lost_items
def get_item_emoji(self, item):
# Define a dictionary mapping items to emojis
item_emojis = {
"apple": "๐",
"banana": "๐",
"watch": "โ",
"laptop": "๐ป",
"medal": "๐
",
"trophy": "๐",
"crown": "๐",
"card": "๐ณ",
"mobile": "๐ฑ",
# Add more items and their corresponding emojis as needed
}
# Return the emoji for the given item, or a default emoji if not found
return item_emojis.get(item.lower())
def get_closest_item(self, input_item):
items = list(self.shop_items.keys())
closest_match = difflib.get_close_matches(input_item.lower(), items, n=1, cutoff=0.6)
return closest_match[0] if closest_match else None
def resolve_item_name(self, item_name):
if item_name.lower() in self.shop_items:
return item_name.lower()
aliases = self.get_item_aliases()
for real_name, alias_list in aliases.items():
if item_name.lower() in alias_list:
return real_name
return None
def create_tables(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
wallet INTEGER DEFAULT 0,
bank INTEGER DEFAULT 0,
bank_limit INTEGER DEFAULT 100000
)
''')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS inventory (
user_id INTEGER,
item_name TEXT,
quantity INTEGER,
PRIMARY KEY (user_id, item_name),
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# Update existing records
self.cursor.execute("UPDATE users SET bank_limit = 100000 WHERE bank_limit = 10000")
# Check if bank_limit column exists, if not, add it
self.cursor.execute("PRAGMA table_info(users)")
columns = [column[1] for column in self.cursor.fetchall()]
if 'bank_limit' not in columns:
self.cursor.execute("ALTER TABLE users ADD COLUMN bank_limit INTEGER DEFAULT 100000")
self.conn.commit()
def get_wallet_balance(self, user_id):
self.cursor.execute("SELECT wallet FROM users WHERE user_id = ?", (user_id,))
result = self.cursor.fetchone()
return result[0] if result else 0
def get_bank_balance(self, user_id):
self.cursor.execute("SELECT bank FROM users WHERE user_id = ?", (user_id,))
result = self.cursor.fetchone()
return result[0] if result else 0
def get_cooldown_time(self, user_id, command_type):
if user_id in self.cooldowns.get(command_type, {}):
return self.cooldowns[command_type][user_id] - datetime.now()
return None
def open_account(self, member):
user_id = member.id
self.cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
if self.cursor.fetchone():
return False
else:
self.cursor.execute("INSERT INTO users (user_id, wallet, bank) VALUES (?, 0, 0)", (user_id,))
self.conn.commit()
return True
def get_user(self, user_id):
self.cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
user = self.cursor.fetchone()
return user
def update_inventory(self, user_id, item_name, quantity_change):
self.cursor.execute("""
INSERT INTO inventory (user_id, item_name, quantity)
VALUES (?, ?, ?)
ON CONFLICT(user_id, item_name)
DO UPDATE SET quantity = quantity + ?
""", (user_id, item_name, quantity_change, quantity_change))
self.conn.commit()
def get_inventory(self, user_id):
self.cursor.execute("""
SELECT item_name, quantity
FROM inventory
WHERE user_id = ? AND quantity > 0
""", (user_id,))
inventory_items = self.cursor.fetchall()
# Convert the list of tuples to a dictionary
inventory = {item: quantity for item, quantity in inventory_items}
return inventory
def add_item_to_inventory(self, user_id, item_name, quantity):
self.cursor.execute('''
INSERT INTO inventory (user_id, item_name, quantity)
VALUES (?, ?, ?)
ON CONFLICT(user_id, item_name) DO UPDATE SET
quantity = quantity + ?
''', (user_id, item_name, quantity, quantity))
self.conn.commit()
def get_random_item(self):
rarity_chances = {
'Common': 0.30,
'Rare': 0.20,
'Epic': 0.10,
'Legendary': 0.5,
'Godly': 0.5
}
# Decide if an item should be dropped
if random.random() > 0.2: # 20% chance to get an item
return None
# Select rarity based on probabilities
rarity = random.choices(list(rarity_chances.keys()),
weights=list(rarity_chances.values()))[0]
# Filter items by selected rarity
eligible_items = [item for item, data in self.items.items() if data['rarity'] == rarity]
if eligible_items:
return random.choice(eligible_items)
return None
def format_money(self, amount):
return "{:,}".format(amount)
def parse_amount(self, amount_str):
multipliers = {'k': 1000, 'm': 1000000, 'b': 1000000000}
match = re.match(r"(\d+)([kmb])?$", amount_str)
if match:
number, multiplier = match.groups()
number = int(number)
if multiplier:
number *= multipliers[multiplier.lower()]
return number
return 0
def update_balance(self, user_id, change, account_type='wallet'):
self.cursor.execute(f"SELECT {account_type} FROM users WHERE user_id = ?", (user_id,))
current_balance = self.cursor.fetchone()[0]
new_balance = current_balance + change # Remove the max() function # Ensure the new balance is at least 1
self.cursor.execute(f'''
UPDATE users
SET {account_type} = ?
WHERE user_id = ?
''', (new_balance, user_id))
self.conn.commit()
return new_balance
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@commands.hybrid_command(name='reset_inventory', description="Reset a user's inventory (Owner only).")
@commands.is_owner()
async def reset_inventory(self, ctx, member: discord.Member):
user_id = member.id
# Delete all inventory entries for the user
self.cursor.execute("DELETE FROM inventory WHERE user_id = ?", (user_id,))
# Commit the changes
self.conn.commit()
# Send a confirmation message
await ctx.send(f"{member.mention}'s inventory has been reset.")
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@commands.hybrid_command(name='set_balance', description="Set a user's wallet and bank balance.", aliases=['sb'])
@commands.is_owner()
@app_commands.describe(member="The user whose balance you want to change.", wallet="The wallet amount that you want to change.", bank="The bank balance you want to change.")
async def set_balance(self, ctx, member: Union[discord.Member, discord.User], wallet: int, bank: int):
user_id = member.id
if (wallet < 0) or (bank < 0):
await ctx.send(f"{ctx.author.mention}, The values for {wallet} and {bank} can not be less than One.")
return False
wallet = max(0, wallet) # Ensure minimum balance of 0
bank = max(0, bank) # Ensure minimum balance of 0
self.cursor.execute("INSERT OR REPLACE INTO users (user_id, wallet, bank) VALUES (?, ?, ?)", (user_id, wallet, bank))
self.conn.commit()
await ctx.send(f"{member.mention}'s wallet has been set to {wallet:,} and bank balance to {bank:,}.")
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@commands.hybrid_command(name='balance', aliases=['bal'], description="See someone's or your balance.")
@app_commands.describe(member="The member who's balance you want to see.")
async def balance(self, ctx, member: discord.Member = None):
member = member or ctx.author
user_id = member.id
self.cursor.execute("SELECT wallet, bank, bank_limit FROM users WHERE user_id = ?", (user_id,))
result = self.cursor.fetchone()
if result:
wallet_balance, bank_balance, bank_limit = result
else:
wallet_balance, bank_balance, bank_limit = 0, 0, 100000
self.cursor.execute("SELECT item_name, quantity FROM inventory WHERE user_id = ?", (user_id,))
inventory = dict(self.cursor.fetchall())
inventory_net = sum(self.shop_items[item]['price'] * quantity
for item, quantity in inventory.items()
if item in self.shop_items)
total_net = inventory_net + wallet_balance + bank_balance
embed = discord.Embed(
title=f"{member.name}'s Balance",
description=f'**Wallet Balance:** {self.moneyemoji} {wallet_balance:,}\n**Bank Balance:** {self.moneyemoji} {bank_balance:,} / {bank_limit:,}\n \n**Inventory Net:** {self.moneyemoji} {inventory_net:,}\n \n**Total Net:** {self.moneyemoji} {total_net:,}',
colour=discord.Colour.gold()
)
embed.set_thumbnail(url=member.avatar.url)
await ctx.send(embed=embed)
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@commands.hybrid_command(name='inventory', description="Check your inventory or others.", aliases=['inv'])
@app_commands.describe(member="The user whose inventory you want to view.")
async def inventory(self, ctx, member: discord.Member = None):
member = member or ctx.author
user_id = member.id
inventory = self.get_inventory(user_id)
if not inventory:
await ctx.send(f"{member.mention}'s inventory is empty.")
return
paginator = InventoryPaginator(ctx, inventory, self.shop_items, self.items, member) # Pass member here
await paginator.run()
@commands.hybrid_command(name='item', description="Get information about any item.")
@app_commands.autocomplete(item=item_autocomplete)
@app_commands.describe(item="The Item to view.")
async def item(self, ctx, *, item):
all_items = {**self.shop_items, **self.items}
item = item.strip().lower()
item_data = next((data for name, data in all_items.items() if item in name.lower()), None)
if item_data is None:
await ctx.send("Item not found.")
return
item = next(name for name, data in all_items.items() if item in name.lower())
price = f"{item_data['price']:,}"
rarity = item_data['rarity']
rarity_colors = {
'Common': discord.Color.from_rgb(173, 216, 230), # Pale blue
'Rare': discord.Color.from_rgb(135, 206, 235), # Sky blue
'Epic': discord.Color.from_rgb(255, 105, 180), # Hot Pink
'Legendary': discord.Color.from_rgb(255, 215, 0), # Golden
'Godly': discord.Color.from_rgb(0, 0, 0) # Black
}
color = rarity_colors.get(rarity, discord.Color.default())
embed = discord.Embed(title=f"{item_data['emoji']} {item}",
description=item_data.get('fact', item_data['description']),
color=color)
embed.add_field(name="Market Price", value=f"{self.moneyemoji} {price}")
embed.add_field(name="Rarity", value=rarity)
embed.set_footer(text=f"{rarity} Item")
await ctx.send(embed=embed)
@commands.hybrid_command(name='use', description="Use any item from your inventory.")
@app_commands.choices(item=[
app_commands.Choice(name="AK's Credit Card", value="card"),
app_commands.Choice(name="Tech's Banana", value="banana"),
app_commands.Choice(name="Bank Slip", value="slip")
])
@app_commands.describe(item="The item that you want to use.", quantity="The quantity of the item to use.")
async def use(self, ctx, item: str, quantity: int = 1):
user_id = ctx.author.id
item_names = {
"card": "AK's Credit Card",
"banana": "Tech's Banana",
"slip": "Bank Slip"
}
item_name = item_names.get(item)
if not item_name:
await ctx.send("Invalid item. Please choose 'card', 'banana', or 'slip'.")
return
# Check if the user has the item in their inventory
self.cursor.execute("SELECT quantity FROM inventory WHERE user_id = ? AND item_name = ?", (user_id, item_name))
result = self.cursor.fetchone()
if result and result[0] >= quantity:
item_emoji = self.shop_items.get(item_name, {}).get('emoji', '') # Get the emoji for the item
confirm_embed = discord.Embed(
title="Use Item Confirmation",
description=f"Are you sure you want to use `{quantity:,}` {item_emoji}**{item_name}(s)**?",
colour=discord.Colour.blurple())
view = discord.ui.View(timeout=30)
async def button_callback(interaction: discord.Interaction, action: str):
if interaction.user != ctx.author:
return await interaction.response.send_message("This is not for you!", ephemeral=True)
for child in view.children:
child.disabled = True
await interaction.response.edit_message(view=view)
if action == 'yes':
confirm_embed.colour = discord.Colour.green()
await interaction.message.edit(embed=confirm_embed)
if item == "slip":
increase = random.randint(70000, 170000) * quantity
self.cursor.execute("UPDATE users SET bank_limit = bank_limit + ? WHERE user_id = ?", (increase, user_id))
self.conn.commit()
self.cursor.execute("SELECT bank_limit FROM users WHERE user_id = ?", (user_id,))
new_limit = self.cursor.fetchone()[0]
success_embed = discord.Embed(
title="Bank Slip Used",
description=f"Your bank limit has increased by {self.moneyemoji} `{self.format_money(increase)}`.\nYour new bank limit is {self.moneyemoji} `{self.format_money(new_limit)}`.",
color=discord.Color.green()
)
new_slip_quantity = result[0] - quantity
#success_embed.set_footer(f"{new_slip_quantity} Bank Slip Remaining")
await ctx.send(embed=success_embed)
elif item == "banana":
tech_user_id = 889153842204278854
tech_user = await self.client.fetch_user(tech_user_id)
try:
bananaembed = discord.Embed(title="Banana Used!", description=f"{ctx.author.mention} has used {quantity} Tech's Banana(s) on you!", colour=discord.Colour.gold())
new_banana_quantity = result[0] - quantity
await tech_user.send(embed=bananaembed)
await ctx.send(f"You have used Tech's Banana(s), {new_banana_quantity} Tech's Banana(s) Remaining")
except discord.Forbidden:
await ctx.send("I cannot send a DM to the user.")
elif item == "card":
processing_embed = discord.Embed(
title="Using AK's Credit Card",
description=f"{self.items['AK\'s Credit Card']['emoji']} _Processing..._",
color=discord.Color.brand_green())
message = await ctx.send(embed=processing_embed)
await asyncio.sleep(4)
money_to_add = random.randint(100000000, 250000000) * quantity
self.update_balance(user_id, money_to_add, "wallet")
new_quantity = result[0] - quantity
success_embed = discord.Embed(
description=f"{ctx.author.mention} you used `{quantity} AK's Credit Card` and got **{self.moneyemoji} {money_to_add:,}**. Now you have `{new_quantity}` remaining in your inventory.",
color=discord.Color.brand_green())
await message.edit(embed=success_embed)
# Update the inventory
self.cursor.execute("UPDATE inventory SET quantity = quantity - ? WHERE user_id = ? AND item_name = ?", (quantity, user_id, item_name))
self.conn.commit()
else:
confirm_embed.colour = discord.Colour.red()
await interaction.message.edit(embed=confirm_embed)
cancel_embed = discord.Embed(title="Use Cancelled!", description=f"Item use successfully cancelled.", color=discord.Color.red())
await ctx.send(ctx.author.mention, embed=cancel_embed)
view.stop() # Stop listening for interactions
yes_button = discord.ui.Button(label="Yes", style=discord.ButtonStyle.green)
no_button = discord.ui.Button(label="No", style=discord.ButtonStyle.red)
yes_button.callback = lambda i: button_callback(i, 'yes')
no_button.callback = lambda i: button_callback(i, 'no')
view.add_item(yes_button)
view.add_item(no_button)
async def on_timeout():
for child in view.children:
child.disabled = True
await ctx.interaction.edit_original_response(view=view)
timeout_embed = discord.Embed(title="Use Cancelled!", description=f"Item use cancelled due to timeout.", color=discord.Color.red())
await ctx.send(ctx.author.mention, embed=timeout_embed)
view.on_timeout = on_timeout
await ctx.send(embed=confirm_embed, view=view)
# Wait for the view to finish (either by button press or timeout)
await view.wait()
else:
await ctx.send(f"You do not have enough {item_name}(s) in your inventory.")
async def setup(client: commands.Bot):
await client.add_cog(Economy(client))
Editor is loading...
Leave a Comment