from discord.ext.commands import Bot, Cog from discord_slash import cog_ext, SlashContext from discord_slash.utils.manage_commands import create_option, create_choice from base import config from models.user import User from models.level import Level from models.item import Item from models.inventory import Inventory from peewee import DoesNotExist import random import yaml class Shop(Cog): def __init__(self, bot: Bot): self.bot = bot with open("config.yaml", "r") as yamlfile: config = yaml.load(yamlfile, Loader=yaml.CLoader) print("Read config successful") self.config = config print(config["discord_server_id"]) @cog_ext.cog_slash( name="shop", description="Browse the shop.", guild_ids=[config["discord_server_id"]], ) async def shop(self, ctx: SlashContext): items = Item.select().limit(100) shop_text = "" for item in items: shop_text += f"#{item.id} {item.name}: {item.price} {config['currency']} \n" await ctx.send(content=shop_text) @cog_ext.cog_slash( name="buy", description="Buy from the shop", guild_ids=[config["discord_server_id"]], options=[ create_option( name="item", description="Item to buy", option_type=3, required=True, ), ], ) async def buy(self, ctx: SlashContext, item: str): user = User.get(User.discord_id == ctx.author_id) try: if is_number(item): buying_item = Item.get(Item.id == item) else: buying_item = Item.get(Item.name == item) except DoesNotExist: await ctx.send(content=f"Item {item} not found. Try using the item number") else: if user.currency >= buying_item.price: try: inventory = Inventory.get(user=user, item=buying_item) except DoesNotExist: inventory = Inventory(user=user, item=buying_item, stock=0) inventory.stock += 1 user.currency -= buying_item.price inventory.save() user.save() await ctx.send( content=f"{user.display_name} bought the item: {buying_item.name} for {buying_item.price} {config['currency']}" ) else: await ctx.send( content=f"{buying_item.name} costs {buying_item.price} {config['currency']}. You can't afford that {user.display_name}!" ) def is_number(s): try: int(s) return True except ValueError: return False def setup(bot): bot.add_cog(Shop(bot)) print("Loaded Shop")