示例#1
0
def main():
    if (len(sys.argv) - 1) % 2 != 0 or (len(sys.argv) - 1) == 0:
        print(
            f"Usage: {sys.argv[0]} `item` `quantity`"
            + " [`item` `quantity` `item` `quantity`]"
        )
        print(f"Example: {sys.argv[0]} Apple 4 Orange 3 Watermelon 5")
    else:
        basket = Basket()
        items = {
            "Apple": Item(
                "Apple",
                0.20,
                SpecialOffer("Buy One Get One Free on Apples", 2)
            ),
            "Orange": Item(
                "Orange",
                0.50
            ),
            "Watermelon": Item(
                "Watermelon",
                0.80,
                SpecialOffer("Three For The Price Of Two on Watermelons", 3),
            ),
        }
        n = 1
        for _ in range((len(sys.argv) - 1) // 2):
            try:
                basket.add(items[sys.argv[n]], int(sys.argv[n + 1]))
            except KeyError:
                print(f"Item {sys.argv[n]} not found")
            n += 2
        basket.show()
        basket.apply_special_offers()
示例#2
0
def createitem():

    user = User.query.get(int(current_user.id))
    item = ItemForm()
    item.item_category.choices = [('Car','Car'),('Dress','Dress'),('Mobile','Mobile')]
    print('before validation')
    picture_path=''
    if item.validate_on_submit():

        print('on validation')
        item_db = Item(name=item.item_name.data, description=item.item_desc.data,
                       starting_bid=item.item_starting_bid.data, category=item.item_category.data,user_id=current_user.id)


        db.session.add(item_db)
        db.session.commit()
        picture_file = save_picture(item.item_img.data,item_db.id)
        item_db.item_image = picture_file
        picture_path = picture_file

        print('before add')
        db.session.commit()
        bid = Bid(bid_price=item.item_starting_bid.data, item_id=item_db.id,user_name=current_user.username,bid_status=True)
        db.session.add(bid)
        db.session.commit()
        print(bid)
        print(item_db.id)
        print('item added')


        # return redirect(url_for('home'))



    return render_template('createitem.html', title='Create Item',item=item,user=user,item_img=url_for('static',filename ='data/items/'+ picture_path))
示例#3
0
    def post(self):
        req = json.loads(request.data)
        item = Item()

        if 'name' not in req or 'available' not in req or 'price' not in req or 'flavors' not in req:
            return jsonify({"message": "Body is invalid"})

        if 'name' in req and 'price' in req:
            item.name = req['name']
            item.price = req['price']
        else:
            return jsonify({"message": "Body is invalid"})

        if 'available' in req:
            item.available = req['available']

        if 'description' in req:
            item.description = req['description']

        if 'flavors' in req and type(req['flavors']) == list:
            for flavor in req['flavors']:
                exists = Flavor.query.filter_by(name=flavor['name']).first()
                if not exists:
                    if 'name' in flavor:
                        insert = Flavor()
                        insert.name = flavor['name']
                        item.flavors.append(insert)
                        insert.save()
                else:
                    item.flavors.append(exists)

        item.save()
        data = self.schema.dump(item)
        return jsonify(data), 201
    async def item_create(self, ctx, *, name):
        if name == "":
            raise commands.errors.MissingRequiredArgument("name")
        if not is_tester(ctx.author):
            raise SendableException(ctx.translate("not_a_tester"))

        item, new = Item.get_or_create(name=name)

        if not new:
            await item.editor_for(ctx, "name", skippable=not new)

        await item.editor_for(ctx, "description", skippable=not new)
        await item.editor_for(ctx, "rarity", skippable=True)
        await item.editor_for(ctx, "explorable", skippable=True)

        waiter = AttachmentWaiter(ctx,
                                  prompt=ctx.translate("item_image_prompt"),
                                  skippable=not new)
        try:
            item.image_url = await waiter.wait(store=True)
        except Skipped:
            pass

        item.save()
        await ctx.send("OK")
示例#5
0
def parse_item_slots(xml_items):
    """
    Parses all entries in the specified xml node depending on the type items or slots are parsed
    :param xml_items: xml node "Items"
    :return: dictionary of item slots [SLOTNAME]:[name, item_id, item]
    """
    items = []
    slots = {}
    activeSet = get_attrib_if_exists(xml_items, 'activeItemSet')
    for entry in xml_items:
        # todo: only parse needed items for the current build
        if entry.tag.lower() == "item":
            items.append(
                Item(entry.attrib['id'], entry.text,
                     get_attrib_if_exists(entry, 'variant')))
        # todo: implement check if we need to parse the second weapon set instead of the normal one.
        if entry.tag.lower() == "slot":
            item_id = get_attrib_if_exists(entry, 'itemId')
            item = parse_item_slot(entry, items, item_id)
            if item:
                slots[entry.attrib['name']] = item

        if entry.tag.lower() == "itemset" and get_attrib_if_exists(
                entry, 'id') == activeSet:
            for slot in entry:
                item_id = get_attrib_if_exists(slot, 'itemId')
                item = parse_item_slot(slot, items, item_id)
                if item:
                    slots[slot.attrib['name']] = item
    return slots
示例#6
0
 def get_human_item(self, user, code=None):
     #TODO: optimize
     human_item = HumanItem.get_or_none(human=self.bot.get_human(user=user),
                                        item=Item.get(code=code))
     if human_item is None or human_item.amount == 0:
         raise SendableException(self.bot.translate("no_" + code))
     return human_item
    async def item_list(self, ctx):
        items = Item.select().order_by(Item.chance.desc())

        table = pretty.Table()
        table.add_row(pretty.Row(("name", "rarity"), header=True))
        for item in items:
            table.add_row(pretty.Row((item.name, item.rarity.name)))
        await table.to_paginator(ctx, 15).wait()
 async def item_usable(self, ctx):
     items = Item.select().where(Item.usable == True)
     embed = discord.Embed(title="Usable items", color=ctx.guild_color)
     for item in items:
         embed.add_field(name=item.name,
                         value=item.description,
                         inline=False)
     await ctx.send(embed=embed)
示例#9
0
    def on_milkyway_purchased(self, channel, member, amount):
        with database.connection_context():
            item = Item.get(code="milky_way")
            human = self.bot.get_human(user=member)
            human.add_item(item, amount)

        embed = discord.Embed(color=self.bot.get_dominant_color(None))
        embed.description = f"Good job in purchasing {amount} milky way(s).\nInstructions:\n`/milkyway create` or `/milkyway extend #channel`"
        asyncio.gather(channel.send(embed=embed))
示例#10
0
async def romaneios(numero_romaneio: int, qt_item: int, descricao: str):
    with store.open_session() as session:
        romaneio = list(
            session.query(object_type=Romaneio).where(
                numero=numero_romaneio))[0]
        romaneio.itens.append(Item(qt_volume=qt_item, descricao=descricao))
        session.store(romaneio)
        session.save_changes()
        return romaneio
    async def item_use(self, ctx, *, name):
        if name == "":
            raise commands.errors.MissingRequiredArgument("name")

        try:
            item = Item.get(name=name)
        except Item.DoesNotExist:
            raise SendableException("Item not found.")

        if not item.usable:
            raise SendableException(ctx.translate("item_not_usable"))

        waiter = BoolWaiter(
            ctx,
            prompt=
            f"`{item.description}`\nAre you sure you want to use this item?")
        if not await waiter.wait():
            return await ctx.send(ctx.translate("canceled"))

        human = ctx.get_human()
        human_item, created = HumanItem.get_or_create(item=item, human=human)
        if created or human_item.amount == 0:
            raise SendableException(ctx.translate("you_missing_item"))

        used = False

        if item.code == "ban_hammer":
            await ctx.author.ban(reason="Ban hammer item was used.",
                                 delete_message_days=0)
            used = True

        elif item.code in ("big_bath", "big_snack", "big_toy"):
            pigeon = Pigeon.get_or_none(human=human,
                                        condition=Pigeon.Condition.active)
            if pigeon is None:
                raise SendableException(ctx.translate("you_no_pigeon"))
            used = True
            stat = {
                "big_bath": "cleanliness",
                "big_snack": "food",
                "big_toy": "happiness"
            }[item.code]
            data = {stat: 100}
            pigeon.update_stats(data, increment=False)
            pigeon.save()
        elif item.code == "milky_way":
            return await self.bot.get_command("milkyway create")(ctx)
        elif item.code == "jester_hat":
            member = await MemberWaiter(
                ctx, prompt=ctx.translate("prank_member_prompt")).wait()
            return await self.bot.get_command("prank nickname")(ctx, member)

        if used:
            human_item.amount -= 1
            human_item.save()
            await ctx.success("Item has been successfully used.")
示例#12
0
def create_items(amount: int) -> Sequence[Item]:
    item_seq = list()
    for i in range(amount):
        item = Item(name=random.choice(ITEM_NAME_LIST) + '-' +
                    str(random.randint(100, 150)),
                    price=random.randint(10, 20))
        item_seq.append(item)
        if (i + 1) % 100 == 0:
            logger.info('---- {} items created'.format(i + 1))
    return item_seq
    async def item_give(self, ctx, member: discord.Member, *, name):
        if name == "":
            raise commands.errors.MissingRequiredArgument("name")
        try:
            item = Item.get(name=name)
        except Item.DoesNotExist:
            raise SendableException("Item not found.")

        member = member or ctx.author
        human = ctx.get_human(user=member)
        human.add_item(item, 1)
        await ctx.send("added")
示例#14
0
    def __init__(self, ctx, in_inventory=True, **kwargs):
        super().__init__(ctx, max_words=None, **kwargs)
        self.show_instructions = False
        self.case_sensitive = False

        if in_inventory:
            query = HumanItem.select()
            query = query.where(HumanItem.human == ctx.get_human())
            query = query.where(HumanItem.amount > 0)
            self.inventory = list(query)
            self.items = [x.item for x in self.inventory]
        else:
            self.items = list(Item.select())

        self.allowed_words = [x.name.lower() for x in self.items]
    async def item_explorable(self, ctx, *, name):
        if name == "":
            raise commands.errors.MissingRequiredArgument("name")

        if not is_tester(ctx.author):
            raise SendableException(ctx.translate("not_a_tester"))
        try:
            item = Item.get(name=name)
        except Item.DoesNotExist:
            raise SendableException("Item not found.")

        await item.editor_for(ctx, "rarity", skippable=True)
        await item.editor_for(ctx, "explorable", skippable=True)

        item.save()
        await ctx.send("OK")
示例#16
0
    async def prank_check(self, ctx, member, name="human"):
        if member.bot:
            raise SendableException(ctx.translate("cannot_prank_bot"))
        if member.id == ctx.author.id:
            raise SendableException(ctx.translate("cannot_prank_self"))

        ctx.prankster, _ = Prankster.get_or_create(user_id=ctx.author.id,
                                                   guild_id=ctx.guild.id)
        if not ctx.prankster.enabled:
            raise SendableException(
                ctx.translate("prankster_pranking_disabled"))

        ctx.victim, _ = Prankster.get_or_create(user_id=member.id,
                                                guild_id=ctx.guild.id)
        if not ctx.victim.enabled:
            raise SendableException(ctx.translate("victim_pranking_disabled"))
        if ctx.victim.pranked:
            raise SendableException(ctx.translate("already_pranked"))

        if ctx.command.name == "nickname":
            cls = NicknamePrank
        elif ctx.command.name == "emoji":
            cls = EmojiPrank
        elif ctx.command.name == "role":
            cls = RolePrank
        else:
            cls = None
        ctx.prank_class = cls
        ctx.human = ctx.get_human()
        ctx.has_item = False
        if cls.item_code is not None:
            ctx.human_item = HumanItem.get_or_none(
                human=ctx.human, item=Item.get(Item.code == cls.item_code))
            ctx.has_item = ctx.human_item is not None and ctx.human_item.amount > 0

        ctx.cost = cls.cost

        if not ctx.has_item:
            ctx.raise_if_not_enough_gold(ctx.cost, ctx.human)
            waiter = BoolWaiter(
                ctx,
                prompt=ctx.translate("gold_verification_check").format(
                    gold=ctx.cost))
            if not await waiter.wait():
                raise SendableException(ctx.translate("canceled"))
示例#17
0
    async def prank_revert(self, ctx, member: discord.Member = None):
        """
        3 types:
            1. Admin revert (when admin wants to revert a prank and give the pranker their gold back)
            2. Member reverts their own prank by spending gold (1k?)
            3. Someone who pranked someone reverts their prank on them
        """

        prankster, _ = Prankster.get_or_create(user_id=member.id,
                                               guild_id=ctx.guild.id)
        prank = prankster.current_prank
        if prank is not None:
            prank.end_date = prank.start_date
            prank.save()

            human = ctx.get_human(user=prank.pranked_by.user_id)
            if prank.purchase_type == NicknamePrank.PurchaseType.gold:
                human.gold += prank.cost
                human.save()
            elif prank.purchase_type == NicknamePrank.PurchaseType.item:
                human.add_item(Item.get(code=prank.item_code), 1)
            await ctx.success(ctx.translate("prank_reverted"))
    def embed(self):
        embed = self.base_embed
        pigeon = self.exploration.pigeon
        text = f"`{pigeon.name}` soared through the skies for **{self.exploration.duration_in_minutes}** minutes"
        text += f" over a distance of **{int(self.exploration.distance_in_km)}** km"
        text += f" until {pigeon.gender.get_pronoun()} finally reached **{self.exploration.destination.name()}**"

        embed.description = text

        bonus_messages = {}
        if self.Bonus.language in self.bonuses:
            language = self.language
            if language is not None:
                bonus_messages[
                    self.Bonus.
                    language] = f"A helpful {self.exploration.destination.demonym()} person also taught {pigeon.gender.get_pronoun(object = True)} some {language.name}!"
            else:
                bonus_messages[
                    self.Bonus.
                    language] = f"{pigeon.gender.get_pronoun().title()} even picked up some of the local language!"

        if self.Bonus.item in self.bonuses:
            self.item = Item.get_random()

            embed.set_thumbnail(url=self.item.image_url)
            lines = []
            lines.append(
                f"On the way {pigeon.gender.get_pronoun()} also found **{self.item.name}**"
            )
            if self.item.usable:
                lines.append(f"*{self.item.description}*")
            bonus_messages[self.Bonus.item] = "\n".join(lines)
        if self.Bonus.tenth in self.bonuses:
            bonus_messages[
                self.Bonus.
                tenth] = f"Since this is your **{self.exploration.pigeon.explorations.count()}th** exploration, you get a bonus!"
        if self.Bonus.hundredth in self.bonuses:
            bonus_messages[
                self.Bonus.
                hundredth] = f"Since this is your **{self.exploration.pigeon.explorations.count()}th** exploration, you get a bonus!"
        if self.Bonus.wing_damage in self.bonuses:
            query = PigeonRelationship.select_for(pigeon)
            relationship = query.first()
            attacker_name = "a random pigeon"
            if relationship is not None:
                other = relationship.pigeon1 if relationship.pigeon1 != pigeon else relationship.pigeon2
                attacker_name = f"`{other.name}`"
            bonus_messages[
                self.Bonus.
                wing_damage] = f"During the flight, {pigeon.name} got attacked by {attacker_name}."

        buffs = []
        for bonus, bonus_message in bonus_messages.items():
            if bonus.buff_code is not None:
                buffs.append(Buff.get(code=bonus.buff_code))
            symbol = "+" if bonus.amount > 0 else ""

            embed.add_field(
                name=f"Bonus {Pigeon.emojis['gold']} {symbol}{bonus.amount}",
                value=bonus_message,
                inline=False)

        if len(buffs) > 0:
            lines = []
            for buff in buffs:
                lines.append(f"**{buff.name}**: *{buff.description}*")
            embed.add_field(name="Buffs gained",
                            value="\n".join(lines),
                            inline=False)

        embed.add_field(name="Total Winnings",
                        value=get_winnings_value(**self.winnings),
                        inline=False)
        return embed
 async def item_view(self, ctx, *, name):
     item = Item.get(name=name)
     await ctx.send(embed=item.embed)
示例#20
0
    BasePrice.Schema().load({
        "product-type": "product_2",
        "options": {
            "size": [8.5, 9.0, 10.0],
            "pattern": ["crosses", "circles"]
        },
        "base-price": 150,
    }),
]

dummy_cart = [
    Item.Schema().load({
        "product-type": "product_1",
        "options": {
            "size": "lg",
            "color": "red"
        },
        "artist-markup": 100,
        "quantity": 2
    }),
    Item.Schema().load({
        "product-type": "product_2",
        "options": {
            "size": 9,
            "pattern": "circles"
        },
        "artist-markup": 0,
        "quantity": 1
    }),
]