Ejemplo n.º 1
0
def test_ensure_files_owned_by_user(mode_mock, owner_mock):
    files = ['.no_file']
    mode = '622'
    user = config.get_user()
    utils.ensure_files_owned_by_user(user, files, mode)
    mode_mock.assert_called_with(files, mode)
    owner_mock.assert_called_with(files, user)
Ejemplo n.º 2
0
def main(*args, **kwargs):

    ######################################################################
    #                        MLS DATA LOAD                               #
    #   -----------------------------------------------------------      #
    #       Program will load info from downloaded MLS data  into DB     #
    #    -----------------------------------------------------------     #

    #        * Pull info using mech_it.mls_data()                        #
    #        * Load information into Postgress database                  #
    #              db_utils.load_db(csv_file)                            #
    ######################################################################

    #Pull config information from config.py
    config_info = {
        'l_url': config.get_l_url(),
        'q_url': config.get_q_url(),
        'cs_url': config.get_cs_url(),
        'user': config.get_user(),
        'password': config.get_password(),
        'folder_out': config.get_folder_out(),
    }

    #Get mls data using mech_it
    mech_it.get_mls_data(config_info)
    ''' ToDo -- add filename pull '''

    #Load data into database
    db_utils.load_db(filename)
Ejemplo n.º 3
0
def test_restore_works(copy_dir_mock, owned_mock):
    shared_file_lists.restore()
    copy_dir_mock.assert_called_with(config.get_shared_file_lists_backup_dir(),
                                     config.get_shared_file_lists_dir(),
                                     with_sudo=True)
    owned_mock.assert_called_with(config.get_shared_file_lists_dir(),
                                  config.get_user())
Ejemplo n.º 4
0
def test_restore(copy_dir_mock, ensure_mock):
    dest = get_ssh_user_dir()
    ssh_files.restore()
    copy_dir_mock.assert_called_with(get_ssh_backup_dir(),
                                     dest,
                                     with_sudo=True)
    ensure_mock.assert_called_with(dest, get_user())
Ejemplo n.º 5
0
def test_restore(copy_files_mock, dotfiles_mock, ensure_mock):
    files = ['.no_file']
    dest = get_home_dir()
    dotfiles_mock.return_value = files
    dotfiles.restore()
    copy_files_mock.assert_called_with(files, dest)
    ensure_mock.assert_called_with(get_user(), files)
Ejemplo n.º 6
0
def test_change_owner_for_files(shell_mock):
    files = ['.no_file']
    user = config.get_user()
    utils.change_owner_for_files(files, user)
    shell_mock.assert_called_with(
        ['sudo', 'chown', user] + files
    )
Ejemplo n.º 7
0
def test_restore_internet_accounts(copy_mock, owned_mock):
    internet_accounts.restore_internet_accounts()
    copy_mock.assert_called_with(config.get_internet_accounts_backup_dir(),
                                 config.get_internet_accounts_dir(),
                                 with_sudo=True)
    owned_mock.assert_called_with(config.get_internet_accounts_dir(),
                                  config.get_user())
Ejemplo n.º 8
0
def restore():
    print 'Restoring dotfiles...'
    source = get_dotfiles_backup_dir()
    dest = get_home_dir()
    files = get_dot_files(source)
    copy_files(files, dest)
    files = get_dot_files(dest)
    ensure_files_owned_by_user(get_user(), files)
Ejemplo n.º 9
0
    async def plate(self, ctx):
        user = config.get_user(ctx.author.id)

        ending = ""
        cutoff = False

        regular = {}
        burned = {}

        for o in user['ovens']:
            if o is not None:
                s = (o['done'] - datetime.datetime.utcnow()).total_seconds()
                if 'burn' in o.keys():
                    b = (o['burn'] -
                         datetime.datetime.utcnow()).total_seconds()
                else:
                    b = 1
                if s <= 0 and b > 0:
                    if len(user['inventory']) >= user.get(
                            'inventory_capacity', 25):
                        cutoff = True
                        break
                    new_bread = config.create_bread(config.breads[o['index']])
                    user['inventory'].append(new_bread)
                    regular[o['index']] = regular.get(o['index'], 0) + 1
                    user['ovens'][user['ovens'].index(o)] = None
                elif s <= 0 and b <= 0:
                    if len(user['inventory']) >= user.get(
                            'inventory_capacity', 25):
                        cutoff = True
                        break
                    new_bread = config.create_bread(config.breads[12])
                    user['inventory'].append(new_bread)
                    burned[o['index']] = burned.get(o['index'], 0) + 1
                    user['ovens'][user['ovens'].index(o)] = None

        for index, amount in regular.items():
            ending += f"+ `{amount}x` {config.breads[index]['emoji']} **{config.breads[index]['name']}**\n"
        for index, amount in burned.items():
            ending += f"+ `{amount}x` {config.breads[12]['emoji']} **Burned {config.breads[index]['name']}** (Charcoal)\n"

        config.USERS.update_one(
            {'id': user['id']},
            {'$set': {
                'inventory': user['inventory'],
                'ovens': user['ovens']
            }})

        if ending == "":
            ending = "No bread was plated."

        embed = discord.Embed(color=config.MAINCOLOR,
                              title="Plated Bread",
                              description=ending)
        if cutoff:
            embed.description += "\n*Some ovens were not emptied because your bread storage is full. Please sell some bread.*"
        await ctx.reply_safe(embed=embed)
Ejemplo n.º 10
0
def restore():
    source = get_ssh_backup_dir()
    if not exists(source):
        log.info('No .ssh dir found... skipping.')
        return
    log.info('Restoring .ssh dir...')
    dest = get_ssh_user_dir()
    copy_dir(source, dest, with_sudo=True)
    ensure_dir_owned_by_user(dest, get_user())
Ejemplo n.º 11
0
 def check(reaction, user):
     if user.id == self.bot.user.id:
         return False
     if reaction.message.id == msg.id and str(
             reaction.emoji) == "<:BreatHunter:815484321573896212>":
         u = config.get_user(user.id)
         if len(u['inventory']) < u.get('inventory_capacity', 25):
             return True
         return False
     return False
Ejemplo n.º 12
0
def login():
    #Get config info
    url = config.get_url()
    username = config.get_user()
    password = config.get_password()

	driver.get(url)
	username = driver.find_element_by_id('LoginCtrl_txtLoginUsername')
	username.send_keys(username)
	password = driver.find_element_by_id('LoginCtrl_txtPassword')
	password.send_keys(password)
	login = driver.find_element_by_id('LoginCtrl_btnLogin').click()
Ejemplo n.º 13
0
    async def send_drop_message(self, message):
        await asyncio.sleep(5)
        drop = config.create_drop()
        embed = discord.Embed(color=config.special_drop[drop['special']],
                              title=drop['name'])
        embed.set_footer(
            text=
            "React first to claim the free bread!\n\nDisable commands/drops with pan blacklist"
        )
        embed.set_author(name="Bread Drop")
        embed.set_thumbnail(url=drop['image'])

        msg = await message.channel.send(embed=embed)
        await msg.add_reaction("<:BreatHunter:815484321573896212>")

        def check(reaction, user):
            if user.id == self.bot.user.id:
                return False
            if reaction.message.id == msg.id and str(
                    reaction.emoji) == "<:BreatHunter:815484321573896212>":
                u = config.get_user(user.id)
                if len(u['inventory']) < u.get('inventory_capacity', 25):
                    return True
                return False
            return False

        try:
            reaction, member = await self.bot.wait_for('reaction_add',
                                                       check=check,
                                                       timeout=120)
        except asyncio.TimeoutError:
            await msg.delete()
            return

        try:
            await msg.clear_reactions()
        except:
            pass

        winner = config.get_user(member.id)
        print(f"DROP_CLAIM: #{message.channel.name} ({member})")
        config.USERS.update_one(
            {'id': member.id},
            {'$push': {
                'inventory': config.create_bread(drop)
            }})
        embed.set_footer(
            text=
            "This bread has already been claimed.\n\nDisable commands/drops with pan blacklist"
        )
        embed.description = f"{member.mention} has claimed the **{drop['name']}**!"
        embed.color = 0x2f3136
        await msg.edit(embed=embed)
Ejemplo n.º 14
0
    async def buy(self, ctx, index: str = None):
        user = config.get_user(ctx.author.id)

        try:
            index = int(index)
        except:
            index = None

        if index is None:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `You must tell me the badge index you would like to purchase: e.g. 'pan badge buy 0'`"
            )
            return

        chosen = None
        for x in config.current_collectables:
            if x['index'] == index:
                chosen = x

        if chosen is None:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `I don't see that badge on sale.`"
            )
            return

        if user['money'] < chosen['price']:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `You don't have enough BreadCoin for this badge.`"
            )
            return

        if index in user['badges']:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `You already have this badge.`"
            )
            return

        config.USERS.update_one({'id': user['id']}, {
            '$inc': {
                'money': -chosen['price']
            },
            '$push': {
                'badges': index
            }
        })

        chosen_badge = config.badges[index]

        await ctx.reply_safe(
            f"Congratulations! You have purchased the {chosen_badge['emoji']} **{chosen_badge['name']}** Badge!"
        )
Ejemplo n.º 15
0
    async def remind(self, ctx, *, args: str = None):
        user = config.get_user(ctx.author.id)

        if args is None:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `Please tell me the timer length and note: e.g. 'pan remind 1h 2m 4s take out the bread'`"
            )
            return

        splitted = args.split(" ")
        time = {"h": 0, "m": 0, "s": 0, "d": 0}
        message = []
        for word in splitted:
            if word[len(word) - 1].lower() in ['h', 'm', 's', 'd']:
                try:
                    time[word[len(word) - 1].lower()] += int(word[:len(word) -
                                                                  1])
                except:
                    message.append(word)
            else:
                message.append(word)
        length = datetime.timedelta(days=time['d'],
                                    hours=time['h'],
                                    minutes=time['m'],
                                    seconds=time['s'])
        if length.total_seconds() < 1:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `Please tell me the timer length and note: e.g. 'pan remind 1h 2m 4s take out the bread'`"
            )
            return
        remind_time = datetime.datetime.utcnow() + length
        message = " ".join(message)

        if message in [" ", "", None]:
            message = "something"

        embed = discord.Embed(color=config.MAINCOLOR, timestamp=remind_time)
        embed.set_footer(text=f"I will remind you about {message} at >")

        config.TIMERS.insert_one({
            'owner': ctx.author.id,
            'link': ctx.message.jump_url,
            'time': remind_time,
            'created': datetime.datetime.utcnow(),
            'message': message,
            'id': ctx.message.id,
            'sent': False,
            'expired': False
        })

        await ctx.reply_safe(embed=embed)
Ejemplo n.º 16
0
    def __init__(self):
        try:
            print(config.get_user(), config.get_password())
            self.conn = psycopg2.connect('dbname=test user={} password={}'.
                                         format(config.get_user(), config.get_password()))
            self.conn.autocommit = True
        except:
            print('I am unable to connect to the database.')
            print("Index won't be creating")
            return

        cur = self.conn.cursor()
        cur.execute("""SELECT table_name FROM information_schema.tables
               WHERE table_schema = 'public'""")
        tables = cur.fetchall()

        if (self.TABLE_NAME,) not in tables:
            try:
                cur.execute(self.command_create_table)
            except Exception as err:
                print('Could not create a table {}.'.format(self.TABLE_NAME))
                print("PageFileAttribute index won't be creating")
                print(err)
                return
Ejemplo n.º 17
0
def checkauth(passargs):
    getpriv = config.get_priv()
    backuser = config.get_user()
    logging.info("Checking privs...")
    logging.info("We have user => {}".format(backuser))
    while True:
        if getpriv == True:
            gethash(passargs, backuser)
            break
        else:
            getpriv = config.get_priv()
            tmp = time.time() - start
            if tmp > passargs.timeout:
                logging.error("Time Out. exiting...")
                break
Ejemplo n.º 18
0
 async def inventory(self, ctx):
     user = config.get_user(ctx.author.id)
     desc = ""
     if len(user['inventory']) < 1:
         desc = "You have no bread. Try managing your bakery with `pan bakery`."
         embed = discord.Embed(title="Bread Inventory",
                               color=config.MAINCOLOR,
                               description=desc)
         embed.set_footer(text=f"Showing 0/0")
         await ctx.reply_safe(embed=embed)
     else:
         pages = menus.MenuPages(source=InventoryMenu(
             user['inventory'], max=user.get('inventory_capacity', 25)),
                                 clear_reactions_after=True)
         await pages.start(ctx)
Ejemplo n.º 19
0
    async def stats(self, ctx, member: discord.Member = None):
        if member is None:
            member = ctx.author

        user = config.get_user(member.id)
        embed = discord.Embed(title="Baker Info", color=config.MAINCOLOR)
        embed.set_thumbnail(url=member.avatar_url)
        if isinstance(member,
                      discord.Member) and member.guild != 814958240009420830:
            guild = self.bot.get_guild(814958240009420830)
            try:
                mem = await guild.fetch_member(member.id)
            except:
                mem = None
        elif isinstance(member, discord.User):
            guild = self.bot.get_guild(814958240009420830)
            try:
                mem = await guild.fetch_member(member.id)
            except:
                mem = None
        else:
            mem = member
        if mem is not None:
            if 814964592076652554 in [x.id for x in mem.roles]:
                if 7 not in user['badges']:
                    user['badges'].append(7)

        if len(user.get('badges', [])) > 0:
            embed.description = " ".join(config.badges[x]['emoji']
                                         for x in user.get('badges', []))

        fav = {'name': "None", 'amount': 0}
        total = 0
        for x, y in user['baked'].items():
            total += y
            if y > fav['amount']:
                fav = {'name': config.breads[int(x)]['name'], 'amount': y}

        embed.add_field(
            name="Baking Stats",
            value=
            f"Favorite Bread: **{fav['name']}** ({fav['amount']} bakes)\nBreads Baked: **{total}**\nBreadCoin: **{user['money']}** <:BreadCoin:815842873937100800>\nOvens: **{user['oven_count']}**\nInventory Capacity: **{user.get('inventory_capacity', 25)}**"
        )

        await ctx.send(embed=embed)
Ejemplo n.º 20
0
 async def addmoney(self,
                    ctx,
                    user: discord.User = None,
                    amount: int = None):
     if ctx.author.id in config.OWNERIDS:
         if user is None:
             await ctx.send("must supply user.")
         elif amount is None:
             await ctx.send("must supply amount.")
         else:
             u = config.get_user(user.id)
             config.USERS.update_one({'id': u['id']},
                                     {'$inc': {
                                         'money': amount
                                     }})
             await ctx.send(
                 f"BreadCoins updated for {user}. User now has {u['money'] + amount} BreadCoins."
             )
Ejemplo n.º 21
0
    async def bakery(self, ctx):
        user = config.get_user(ctx.author.id)

        baking = len(user['ovens'])
        for o in user['ovens']:
            if o is None:
                baking -= 1

        for _ in range(user.get('oven_count', 2)):
            try:
                x = user['ovens'][_]
            except IndexError:
                user['ovens'].append(None)

        pages = menus.MenuPages(source=BakeryMenu(user['ovens'],
                                                  user['oven_count'], baking,
                                                  user),
                                clear_reactions_after=True)
        await pages.start(ctx)
Ejemplo n.º 22
0
    async def bal(self, ctx, member: discord.Member = None):
        if member is None:
            member = ctx.author

        user = config.get_user(member.id)

        assets = 0
        for item in user['inventory']:
            r = config.breads[item['index']]
            item_price = market.ItemPrice(r['price'], r['volitility'],
                                          item['index'])
            today_price = round(
                item_price.get_price(market.get_day_of_year_active()))
            assets += today_price

        embed = discord.Embed(
            title="Baker Balance",
            description=
            f"**Pocket**: `{user['money']}` <:BreadCoin:815842873937100800>\n**Bread Worth**: `{assets}` <:BreadCoin:815842873937100800> [<:BreadWarning:815842874226245643>]({ctx.message.jump_url} \"This value is based on the market and will change.\")\n**Total Assets**: `{user['money'] + assets}` <:BreadCoin:815842873937100800>",
            color=config.MAINCOLOR)

        await ctx.reply_safe(embed=embed)
Ejemplo n.º 23
0
    async def build(self, ctx):
        user = config.get_user(ctx.author.id)

        # if user['oven_count'] >= 24:
        #     await ctx.reply_safe("<:melonpan:815857424996630548> `You have built the maximum amount of ovens!`")
        #     return

        cost = user['oven_count'] * config.oven_cost

        if user['money'] < cost:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `You don't have enough BreadCoin to build a new oven.`"
            )
            return

        config.USERS.update_one({'id': user['id']},
                                {'$inc': {
                                    'money': -cost,
                                    'oven_count': 1
                                }})
        await ctx.reply_safe(
            "<:melonpan:815857424996630548> You have built a new oven! View it with `pan bakery`."
        )
Ejemplo n.º 24
0
    def onMessage(self, room, user, message):
        if user == self.user: return
        if not message.body.strip(): return

        msgdata = message.body.strip()
        if user.name not in config.users:
            PREFIX = config.default_user["prefix"]
        else:
            PREFIX = config.get_user(user.name)["prefix"]

        if msgdata.startswith(PREFIX):
            msgdata = msgdata[len(PREFIX):].lstrip()
        elif msgdata.lower().startswith("@" + self.name.lower()):
            msgdata = msgdata[len(self.name) + 1:].lstrip()
        else:
            return

        # partition always returns a 3 items tuple
        cmd, _, msgdata = msgdata.partition(" ")
        args = msgdata.split()
        cmd = cmd.lower()

        if cmd not in config.cmds:
            return

        try:
            exec(config.cmds[cmd], locals())
        except BaseException as e:
            fsize = str(self.user.fontSize).rjust(2, "0")
            fcolor = self.user.fontColor
            etype = e.__class__.__name__
            eargs = html.escape(str(e))
            msg = '<b>{}</b>: <f x{}{}="8"><i>{}</i>'
            msg = msg.format(etype, fsize, fcolor, eargs)
            traceback.print_exc()
            room.message(msg, html=True)
Ejemplo n.º 25
0
    async def expand(self, ctx):
        user = config.get_user(ctx.author.id)

        # if user.get('inventory_capacity', 25) >= 100:
        #     await ctx.reply_safe("<:melonpan:815857424996630548> `You have expanded your storage capacity to the max!`")
        #     return

        cost = int(
            (user.get('inventory_capacity', 25) / config.expand_amount) *
            config.expand_cost)

        if user['money'] < cost:
            await ctx.reply_safe(
                "<:melonpan:815857424996630548> `You don't have enough BreadCoin to expand your storage capacity.`"
            )
            return

        if 'inventory_capacity' in user.keys():
            config.USERS.update_one({'id': user['id']}, {
                '$inc': {
                    'money': -cost,
                    'inventory_capacity': config.expand_amount
                }
            })
        else:
            config.USERS.update_one({'id': user['id']}, {
                '$inc': {
                    'money': -cost
                },
                '$set': {
                    'inventory_capacity': 25 + config.expand_amount
                }
            })
        await ctx.reply_safe(
            f"<:melonpan:815857424996630548> You have expanded your inventory capacity by `{config.expand_amount}` slots. You can now store `{user.get('inventory_capacity', 25) + config.expand_amount}` items."
        )
Ejemplo n.º 26
0
import config

if user.name[0] not in ("#", "!"):
    cuser = config.get_user(user.name)
    if not args:
        msg = config.get_lang(cuser["lang"],
                              "current_prefix").format(cuser["prefix"])
    else:
        new_prefix = args[0]
        if len(new_prefix) > 5:
            msg = config.get_lang(cuser["lang"],
                                  "prefix_too_long").format(new_prefix)
        elif new_prefix[0] == "_":
            msg = config.get_lang(cuser["lang"],
                                  "invalid_prefix").format(new_prefix)
        else:
            cuser["prefix"] = new_prefix
            msg = config.get_lang(cuser["lang"],
                                  "new_prefix").format(new_prefix)
else:
    msg = config.get_lang("en", "not_for_anons")
room.message(msg)
Ejemplo n.º 27
0
def restore():
    log.info('Restoring shared file lists...')
    dest = config.get_shared_file_lists_dir()
    source = config.get_shared_file_lists_backup_dir()
    copy_dir(source, dest, with_sudo=True)
    ensure_dir_owned_by_user(dest, config.get_user())
Ejemplo n.º 28
0
    async def sellall(self, ctx, *, item: str = None):
        user = config.get_user(ctx.author.id)

        if item is None:
            today = datetime.datetime.now().timetuple().tm_yday
            random.seed(today)
            display = random.sample(config.breads, k=9)
            selling = []
            total = 0
            desc = "```************\nSOLD RECEIPT\n************\nDescription"
            for on_sale in display:
                if not on_sale['sellable']:
                    continue
                item_price = market.ItemPrice(on_sale['price'],
                                              on_sale['volitility'],
                                              config.breads.index(on_sale))
                today_price = round(
                    item_price.get_price(market.get_day_of_year_active()))

                this_selling = []
                for their_item in user['inventory']:
                    if their_item['index'] == config.breads.index(on_sale):
                        this_selling.append(their_item)
                        selling.append(their_item)
                total += len(this_selling) * today_price
                if len(this_selling) > 0:
                    desc += f"\n- {len(this_selling)}x {on_sale['name']}"

            for selling_item in selling:
                user['inventory'].remove(selling_item)

            if len(selling) > 0:
                config.USERS.update_one({'id': ctx.author.id}, {
                    '$set': {
                        'inventory': user['inventory']
                    },
                    '$inc': {
                        'money': total
                    }
                })

                desc += f"\n\n============\nTOTAL AMOUNT: {total} BreadCoin\nTAX: 0 BreadCoin\n============\nTHANK YOU!```"

                await ctx.reply_safe(
                    embed=discord.Embed(title="Bread Market Exchange Receipt",
                                        color=discord.Color(0xebeae8),
                                        description=desc,
                                        timestamp=datetime.datetime.utcnow()))
            else:
                await ctx.reply_safe(
                    "<:melonpan:815857424996630548> `There was nothing sellable in your inventory.`"
                )
        else:
            today = datetime.datetime.now().timetuple().tm_yday
            random.seed(today)
            display = random.sample(config.breads, k=9)
            selected = None
            for r in display:
                if item.lower() in r['name'].lower():
                    selected = r
                    break
                try:
                    index = int(item)
                    if index == config.breads.index(r):
                        selected = r
                        break
                except:
                    pass
            if selected is None:
                await ctx.send(
                    "<:melonpan:815857424996630548> `That bread doesn't look like it's on the market today...`"
                )
            elif not selected['sellable']:
                await ctx.send(
                    "<:melonpan:815857424996630548> `That cannot be sold.`")
            else:
                item_price = market.ItemPrice(selected['price'],
                                              selected['volitility'],
                                              config.breads.index(selected))
                today_price = round(
                    item_price.get_price(market.get_day_of_year_active()))

                selling = []
                for their_item in user['inventory']:
                    if their_item['index'] == config.breads.index(selected):
                        selling.append(their_item)
                total = len(selling) * today_price

                for selling_item in selling:
                    user['inventory'].remove(selling_item)

                config.USERS.update_one({'id': ctx.author.id}, {
                    '$set': {
                        'inventory': user['inventory']
                    },
                    '$inc': {
                        'money': total
                    }
                })

                desc = f"```************\nSOLD RECEIPT\n************\nDescription\n- {len(selling)}x {selected['name']}\n\n============\nTOTAL AMOUNT: {total} BreadCoin\nTAX: 0 BreadCoin\n============\nTHANK YOU!```"

                await ctx.reply_safe(
                    embed=discord.Embed(title="Bread Market Exchange Receipt",
                                        color=discord.Color(0xebeae8),
                                        description=desc,
                                        timestamp=datetime.datetime.utcnow()))
Ejemplo n.º 29
0
    async def buy(self, ctx, amount: str = None, *, item: str = None):
        user = config.get_user(ctx.author.id)

        if amount is None:
            amount = "1"
        if item is None:
            await ctx.send(
                "<:melonpan:815857424996630548> `You must tell me an item you wish to buy: e.g. 'pan buy 4 baguette'`"
            )
            return

        today = datetime.datetime.now().timetuple().tm_yday
        random.seed(today)
        display = random.sample(config.breads, k=9)
        selected = None
        for r in display:
            if item.lower() in r['name'].lower():
                selected = r
                break
            try:
                index = int(item)
                if index == config.breads.index(r):
                    selected = r
                    break
            except:
                pass
        if selected is None:
            await ctx.send(
                "<:melonpan:815857424996630548> `That bread doesn't look like it's on sale today...`"
            )
        elif not selected['buyable']:
            await ctx.send(
                "<:melonpan:815857424996630548> `That cannot be purchased.`")
        else:
            try:
                amount = abs(int(amount))
            except:
                await ctx.send(
                    "<:melonpan:815857424996630548> `Amount must be a number: e.g. 'pan buy 4 baguette'`"
                )
                return

            item_price = market.ItemPrice(selected['price'],
                                          selected['volitility'],
                                          config.breads.index(selected))
            today_price = round(
                item_price.get_price(market.get_day_of_year_active()))

            if user['money'] < today_price * amount:
                await ctx.send(
                    "<:melonpan:815857424996630548> `It doesn't look like you have enough for this item.`"
                )
            elif len(user['inventory']) + amount > user.get(
                    'inventory_capacity', 25):
                await ctx.send(
                    "<:melonpan:815857424996630548> `It doesn't look like you have enough space in your bag.`"
                )
            else:
                new_relics = []
                for _ in range(amount):
                    new_relics.append({
                        'index': config.breads.index(selected),
                        'quality': random.randint(1, 5)
                    })

                config.USERS.update_one({'id': ctx.author.id}, {
                    '$push': {
                        'inventory': {
                            '$each': new_relics
                        }
                    },
                    '$inc': {
                        'money': -today_price * amount
                    }
                })

                total = amount * today_price

                desc = f"```************\nCASH RECEIPT\n************\nDescription\n- {amount}x {selected['name']}\n\n============\nTOTAL AMOUNT: {total} BreadCoin\nTAX: 0 BreadCoin\n============\nTHANK YOU!```"

                await ctx.reply_safe(
                    embed=discord.Embed(title="Bread Market Exchange Receipt",
                                        color=discord.Color(0xebeae8),
                                        description=desc,
                                        timestamp=datetime.datetime.utcnow()))
Ejemplo n.º 30
0
    async def sell(self, ctx, amount: str = None, *, item: str = None):
        user = config.get_user(ctx.author.id)

        if amount is None:
            amount = "1"
        if item is None:
            await ctx.send(
                "<:melonpan:815857424996630548> `You must tell me an item you wish to sell: e.g. 'pan sell 4 baguette'`"
            )
            return

        today = datetime.datetime.now().timetuple().tm_yday
        random.seed(today)
        display = random.sample(config.breads, k=9)
        selected = None
        for r in display:
            if item.lower() in r['name'].lower():
                selected = r
                break
            try:
                index = int(item)
                if index == config.breads.index(r):
                    selected = r
                    break
            except:
                pass
        if selected is None:
            await ctx.send(
                "<:melonpan:815857424996630548> `That bread doesn't look like it's on the market today...`"
            )
        elif not selected['sellable']:
            await ctx.send(
                "<:melonpan:815857424996630548> `That cannot be sold.`")
        else:
            try:
                amount = abs(int(amount))
            except:
                await ctx.send(
                    "<:melonpan:815857424996630548> `Amount must be a number: e.g. 'pan sell 4 baguette'`"
                )
                return

            item_price = market.ItemPrice(selected['price'],
                                          selected['volitility'],
                                          config.breads.index(selected))
            today_price = round(
                item_price.get_price(market.get_day_of_year_active()))

            selling = []
            for their_item in user['inventory']:
                if their_item['index'] == config.breads.index(selected):
                    selling.append(their_item)
                if len(selling) >= amount:
                    break
            if len(selling) < amount:
                await ctx.send(
                    f"<:melonpan:815857424996630548> `It looks like you only have {len(selling)} of that bread in your bag.`"
                )
            else:
                total = amount * today_price

                for selling_item in selling:
                    user['inventory'].remove(selling_item)

                config.USERS.update_one({'id': ctx.author.id}, {
                    '$set': {
                        'inventory': user['inventory']
                    },
                    '$inc': {
                        'money': total
                    }
                })

                desc = f"```************\nSOLD RECEIPT\n************\nDescription\n- {amount}x {selected['name']}\n\n============\nTOTAL AMOUNT: {total} BreadCoin\nTAX: 0 BreadCoin\n============\nTHANK YOU!```"

                await ctx.reply_safe(
                    embed=discord.Embed(title="Bread Market Exchange Receipt",
                                        color=discord.Color(0xebeae8),
                                        description=desc,
                                        timestamp=datetime.datetime.utcnow()))