diff options
author | Joe Robinson <joe@lc8n.com> | 2021-11-28 18:42:55 +0000 |
---|---|---|
committer | Joe Robinson <joe@lc8n.com> | 2021-11-28 18:42:55 +0000 |
commit | dfade65d2859188de22be990f4cbc1f0c7602735 (patch) | |
tree | 50b93b669ce46b48ab164edc63321a44995b8d81 /commands | |
parent | 0c4b6e6e8c69709e638cc28d1ba338c5388f342c (diff) |
Add commands
Diffstat (limited to 'commands')
-rw-r--r-- | commands/shop.py | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/commands/shop.py b/commands/shop.py new file mode 100644 index 0000000..5c9bb9f --- /dev/null +++ b/commands/shop.py @@ -0,0 +1,88 @@ +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") |