예제 #1
0
def lottery_f(user, gamesToPlay):
    if gamesToPlay > economy_const.LOTTERY_MAX_GAMES_ALLOWED:
        return -1

    profile = UserProfile.load(user)
    if profile.ecoIsLocked():
        return -2

    totalCost = economy_const.LOTTERY_COST * gamesToPlay
    if not profile.ecoCheckBalance(totalCost):
        return -3

    # When all checks pass, lock the profile
    profile.ecoLock()

    # Play lottery and assemble report embed
    lotteryReport = economy_fAux.gameLottery(gamesToPlay)
    ticketStrings = []
    for game in lotteryReport["games"]:
        ticketStr = "{}: `[{}] ({})` | Prize: {}".format(
            str(lotteryReport["games"].index(game) + 1).zfill(2),
            "-".join([str(t).zfill(2) for t in game["ticket"]]),
            str(game["hits"]).zfill(2), game["prize"])
        ticketStrings.append(ticketStr)

    totalPrize = sum([game["prize"] for game in lotteryReport["games"]])
    totalChange = totalPrize - totalCost
    if totalChange > 0:
        resultStr = "You won {}!".format(economy_fAux.pMoney(totalChange))
    elif totalChange < 0:
        resultStr = "You just lost {} haha".format(
            economy_fAux.pMoney(abs(totalChange)))
    else:
        resultStr = "You didn't win or lose anything"

    embed = discord.Embed(
        title="Lottery",
        description="Winning ticket: `[{}]`".format("-".join(
            [str(t).zfill(2) for t in lotteryReport["winningTicket"]])))
    embed.add_field(name="Tickets",
                    value="\n".join(ticketStrings),
                    inline=False)
    embed.add_field(name="Results",
                    value="Total Prize: {}\n{}".format(totalPrize, resultStr),
                    inline=False)
    if totalChange == 0:
        embed.set_footer(text="Booooooooooring")

    # Make balance changes and unlock profile
    profile.ecoChangeBalance(totalPrize - totalCost)
    profile.ecoUnlock()

    return embed
예제 #2
0
 async def addmoney(self, ctx, mentionedUser: discord.User,
                    changeAmount: int):
     code = admin_f.addmoney_f(ctx, mentionedUser, changeAmount)
     if code == -1:
         await inssuficientPermissions(ctx)
     elif code == 0:
         await ctx.send("{}, {} balance was changed by {}.".format(
             ctx.author.mention, mentionedUser.mention,
             economy_fAux.pMoney(changeAmount)))
     return 0
예제 #3
0
    async def eventPublishEnd(self):
        if self.winnerUser != None:
            embedDescription = "Congrats to {}! You won {}!".format(
                self.winnerUser.name, economy_fAux.pMoney(self.prize))
            embed = discord.Embed(title="Hola yutuberos como tan toos..",
                                  description=embedDescription)
        else:
            embed = discord.Embed(title="Hola yutuberos como tan toos..",
                                  description="No one guessed it.")

        await self.channel.send("", embed=embed)
예제 #4
0
def collect_f(user):
    profile = UserProfile.load(user)
    code = profile.ecoCollect()
    if code == -1:
        return -1
    elif code == 0:
        profile.ecoChangeBalance(economy_const.COLLECTION_MONEY, forced=True)
        embedTitle = "Welfare Collected!"
        embedDescription = "You just collected your daily {}".format(
            economy_fAux.pMoney(economy_const.COLLECTION_MONEY))
        embed = discord.Embed(title=embedTitle, description=embedDescription)
        return embed
예제 #5
0
def bid_f(user, bidAmount):
    eventManager = EventManager.getEventManager()
    waifuAHEvent = eventManager.getEvent("waifuAH")

    if not waifuAHEvent.isRunning():
        return -1

    profile = UserProfile.load(user)
    if not profile.ecoCheckBalance(bidAmount):
        return -2

    if bidAmount <= waifuAHEvent.lastBid:
        return -3

    if abs(bidAmount - waifuAHEvent.lastBid) < waifuAHEvent.bidStepUp:
        return -4

    # If there is an event, check preliminary bidding info
    t = utcNow()
    extendedTime = False
    if (waifuAHEvent.timeEnd -
            t).total_seconds() < waifuAHEvent.timeThresholdToExtend:
        extendedTime = True

    # Eco unlock previous bidder and eco lock current one
    if waifuAHEvent.user is not None:
        UserProfile.load(waifuAHEvent.user).ecoUnlock()
    profile.ecoLock()

    # Set this user as current bidder in event
    waifuAHEvent.user = user
    waifuAHEvent.lastBid = bidAmount
    waifuAHEvent.lastBidTime = t

    # Assemble embed and return
    embed = discord.Embed(title="Bid Registered",
                          description="{} made the latest bid!".format(
                              user.name))
    embed.add_field(name="Bid Amount",
                    value="{}".format(economy_fAux.pMoney(bidAmount)))

    if extendedTime:
        newEndTime = utcToTZ(utcNow() + datetime.timedelta(
            seconds=waifuAHEvent.bidTimeExtension))
        tStr = "Auction will stop at {}.".format(
            newEndTime.strftime("%H:%M:%S"))
        embed.add_field(name="Time Extended!", value=tStr)

    return embed
예제 #6
0
 async def bid(self, ctx, bidAmount: int = 0):
     code = waifu_f.bid_f(ctx.author, bidAmount)
     if code == -1:
         await ctx.send("{}, this event is not active right now.".format(
             ctx.author.mention))
     elif code == -2:
         await ctx.send(
             "{}, you have inssuficient funds to make this bid.".format(
                 ctx.author.mention))
     elif code == -3:
         await ctx.send(
             "{}, the minimum bid must be higher than {}.".format(
                 ctx.author.mention,
                 economy_fAux.pMoney(self.waifuAuctionHouseEvent.lastBid)))
     elif code == -4:
         await ctx.send(
             "{}, the minimum bid must be at least {} higher than the previous one."
             .format(
                 ctx.author.mention,
                 economy_fAux.pMoney(self.waifuAuctionHouseEvent.bidStepUp))
         )
     else:
         embed = code
         await ctx.send("", embed=embed)
예제 #7
0
def balance_f(ctx, userMentioned):
    if userMentioned != None:
        if isAdmin(ctx.author):
            targetUser = userMentioned
        else:
            return -1
    else:
        targetUser = ctx.author

    profile = UserProfile.load(targetUser)

    embedTitle = "{}'s Balance".format(profile.user.name)
    embedDescription = economy_fAux.pMoney(profile.ecoBalance)
    embed = discord.Embed(title=embedTitle, description=embedDescription)
    return embed
예제 #8
0
    async def eventPublishEnd(self):
        embedTitle = "Money Claim!"
        if self.users == []:
            embedDescription = "No one claimed it \U0001F4B8"
        else:
            prizeStrs = []
            for user in self.prizeDict.keys():
                prizeStr = "{}: {}".format(
                    user.name, economy_fAux.pMoney(self.prizeDict[user]))
                prizeStrs.append(prizeStr)

            embedDescription = "Congratulations to the winners!\n" + "\n".join(
                prizeStrs)

        embed = discord.Embed(title=embedTitle, description=embedDescription)
        await self.channel.send("", embed=embed)
예제 #9
0
    async def eventProcess(self):
        if self.lastBidTime != self.lastBidTimeChecked:
            if (self.timeEnd -
                    utcNow()).total_seconds() < self.timeThresholdToExtend:
                self.setTimeEnd(self.bidTimeExtension)
                self.lastBidTimeChecked = self.lastBidTime

        if self.lastBid > 0:
            newStepUp = max(1, int((self.lastBid / self.waifu["value"]))**2)
            if newStepUp > self.bidStepUp:
                self.bidStepUp = newStepUp
                embed = discord.Embed(
                    title="Waifu AH Bid STEP UP!",
                    description="New minimum bid Step-Up: {}".format(
                        economy_fAux.pMoney(self.bidStepUp)))
                await self.channel.send("", embed=embed)
예제 #10
0
    async def eventPublishEnd(self):
        embedTitle = "Waifu AuctionHouse Event!"
        if self.user == None:
            embed = discord.Embed(
                title=embedTitle,
                description="No one bidded for her \U0001F494")
        else:
            embed = discord.Embed(
                title=embedTitle,
                description="{} got {}! Congrats \U0001F496".format(
                    self.user.name, self.waifu["name"]))
            embed.add_field(
                name="Bidding",
                value="{} ({}% of Waifu Value)".format(
                    economy_fAux.pMoney(self.lastBid),
                    int(round(self.lastBid / self.waifu["value"] * 100, 1))))

        embed.set_thumbnail(url=random.choice(self.waifu["pictures"]))
        await self.channel.send("", embed=embed)
예제 #11
0
def makeBuyEmbedItemDescription(buyer, seller, category, itemDict, price):
    embedDescription0 = "{} just purchased an item from {} for {}!".format(
        buyer.name, 
        seller.name,
        economy_fAux.pMoney(price))
    
    if category == "waifu":
        waifu = waifu_fAux.getWaifu(itemDict["waifuID"])
        embedDescription1_part1 = "{}{}".format(marketplace_const.ITEM_VALUENAME, waifu["name"])
        embedDescription1_part2 = "{}Source: {}".format(marketplace_const.ITEM_VALUESPACE, waifu["animeName"])
        embedDescription1_part3 = "{}Rank: {}".format(marketplace_const.ITEM_VALUESPACE, waifu["rank"])
        embedDescription1_part4 = "{}Value: {}".format(marketplace_const.ITEM_VALUESPACE, waifu["value"])
        embedDescription1List = [embedDescription1_part1, embedDescription1_part2, embedDescription1_part3, embedDescription1_part4]
        embedDescription1 = "\n".join(embedDescription1List)
    else:
        raise ValueError("Not a valid category: {}".format(category))

    embedDescriptionList = [embedDescription0, "", embedDescription1]
    embedDescription = "\n".join(embedDescriptionList)
    return embedDescription
예제 #12
0
def makeSellEmbedItemDescription(seller, category, itemDict, price):
    embedDescription0 = "Seller: {}".format(seller.name)
    embedDescription1 = "Category: {}".format(category)

    if category == "waifu":
        waifu = waifu_fAux.getWaifu(itemDict["waifuID"])
        embedDescription2_part1 = "{}{}".format(marketplace_const.ITEM_VALUENAME, waifu["name"])
        embedDescription2_part2 = "{}Source: {}".format(marketplace_const.ITEM_VALUESPACE, waifu["animeName"])
        embedDescription2_part3 = "{}Rank: {}".format(marketplace_const.ITEM_VALUESPACE, waifu["rank"])
        embedDescription2_part4 = "{}Value: {}".format(marketplace_const.ITEM_VALUESPACE, waifu["value"])
        embedDescription2List = [embedDescription2_part1, embedDescription2_part2, embedDescription2_part3, embedDescription2_part4]
        embedDescription2 = "\n".join(embedDescription2List)
    else:
        return ValueError("Not valid category: {}".format(category))
    
    embedDescriptionValue3 = "Price: {}".format(economy_fAux.pMoney(price))
    
    embedValueList = [embedDescription0, embedDescription1, embedDescription2, embedDescriptionValue3]
    embedDescription = "\n".join(embedValueList)
    return embedDescription
예제 #13
0
def ranking_f():
    embed = discord.Embed(title="Economy Ranking",
                          description="Top 5 based on total Balance.")

    mongoClient = dbClient.getClient()
    userDocs = list(
        mongoClient.DBot.users.find({}).sort("ecoDict.balance",
                                             pymongo.DESCENDING))

    selectedDocs = userDocs[:5]
    for userDoc in selectedDocs:
        profile = UserProfile.load(Bot.getBot().get_user(
            userDoc["user"]["id"]))
        fieldName = "{}/{}: {}".format(
            selectedDocs.index(userDoc) + 1, len(selectedDocs),
            profile.user.name)
        fieldValue = "Balance: {}".format(
            economy_fAux.pMoney(profile.ecoBalance))
        embed.add_field(name=fieldName, value=fieldValue, inline=False)

    return embed
예제 #14
0
def pay_f(originUser, destinationUser, amount):
    if amount <= 0:
        return -1

    originProfile = UserProfile.load(originUser)
    if originProfile.ecoIsLocked():
        return -2

    destinationProfile = UserProfile.load(destinationUser)
    if destinationProfile.ecoIsLocked():
        return -3

    if not originProfile.ecoCheckBalance(amount):
        return -4

    originProfile.ecoChangeBalance(-amount)
    destinationProfile.ecoChangeBalance(amount)

    embedTitle = "Successful transaction"
    embedDescription = "{} just sent {} to {}.".format(
        originUser.name, economy_fAux.pMoney(amount), destinationUser.name)
    embed = discord.Embed(title=embedTitle, description=embedDescription)
    return embed
예제 #15
0
def list_f(ctx, args):
    # parse args
    # parse page number
    numbers = [int(arg) for arg in args if arg.isdigit()]
    if len(numbers) > 1:
        return -1
    page = numbers[0] if len(numbers) == 1 else 1

    # parse ranks
    ranksInArgs = [
        arg for arg in args if (arg.upper() in waifu_const.WAIFU_RANKS)
    ]
    ranksQuery = ranksInArgs if len(
        ranksInArgs) > 0 else waifu_const.WAIFU_RANKS

    # parse target user
    mentions = ctx.message.mentions
    if len(mentions) != 0:
        if not isAdmin(ctx.author):
            return -2
        if len(mentions) > 1:
            return -3

        targetUser = mentions[0]
    else:
        targetUser = ctx.author

    # Parse duplicate mode
    duplicateMode = False
    if ("-d" in args) or ("-D" in args) or ("duplicates" in args):
        duplicateMode = True

    # Get waifu profile
    profile = UserProfile.load(ctx.author)

    if len(profile.waifuList) == 0:
        if targetUser == ctx.author:
            return -4
        else:
            return -5

    # Query waifus from DB
    if duplicateMode:
        duplicateIDs = list(profile.waifuGetDuplicateWaifuDict().keys())
        query = {
            "$and": [{
                "MAL_data.charID": {
                    "$in": duplicateIDs
                }
            }, {
                "rank": {
                    "$in": ranksQuery
                }
            }]
        }
    else:
        query = {
            "$and": [{
                "MAL_data.charID": {
                    "$in": list(set(profile.waifuList))
                }
            }, {
                "rank": {
                    "$in": ranksQuery
                }
            }]
        }

    waifuList = list(dbClient.getClient().DBot.waifus.find(query).sort(
        "value", pymongo.DESCENDING))

    if len(waifuList) == 0:
        return -6

    if profile.waifuFavorite is not None:
        waifuFav = waifu_fAux.getWaifu(profile.waifuFavorite)
        embedDescription = "Favorite Waifu: {}{}\nFrom: {}".format(
            waifuFav["name"],
            "" if waifuFav["aliases"] == [] else ", alias {}".format(
                random.choice(waifuFav["aliases"])), waifuFav["animeName"])
        thumbnail_url = random.choice(waifuFav["pictures"])
    else:
        embedDescription = discord.Embed.Empty
        thumbnail_url = random.choice(waifu_const.NO_FAV_WAIFU_URLS)

    embed = discord.Embed(title="{}'s Harem".format(profile.user.name),
                          description=embedDescription)
    waifuStart = waifu_const.WAIFU_LIST_WAIFUS_PER_PAGE * (page - 1)
    waifuEnd = waifuStart + waifu_const.WAIFU_LIST_WAIFUS_PER_PAGE
    for waifu in waifuList[waifuStart:waifuEnd]:
        fieldName = "{}/{} \U0000300C{}\U0000300D: {} [{}]".format(
            waifuList.index(waifu) + 1, len(waifuList), waifu["rank"],
            waifu["name"], waifu["MAL_data"]["charID"])

        fieldValue1 = "Source: {}".format(waifu["animeName"])
        fieldValue2 = "Ranking: {}/{}\nValue: {}".format(
            waifu["ranking"], waifu_fAux.waifuCount(), waifu["value"])
        fieldValues = [fieldValue1, fieldValue2]

        if duplicateMode:
            fieldValue4 = "Count: {}".format(
                profile.waifuList.count(waifu["MAL_data"]["charID"]))
            fieldValues.append(fieldValue4)
        elif profile.waifuList.count(waifu["MAL_data"]["charID"]) > 1:
            fieldValue4 = "Count: {}".format(
                profile.waifuList.count(waifu["MAL_data"]["charID"]))
            fieldValues.append(fieldValue4)

        embed.add_field(name=fieldName,
                        value="\n".join(fieldValues),
                        inline=False)

    embed.add_field(name="Total Waifu Value",
                    value="{}".format(
                        economy_fAux.pMoney(profile.waifuGetTotalValue())),
                    inline=False)

    embed.set_thumbnail(url=thumbnail_url)
    footerText1 = "Waifu Harem page: {} of {}.".format(
        page,
        math.ceil(len(waifuList) / waifu_const.WAIFU_LIST_WAIFUS_PER_PAGE))
    footerText2 = "Search other pages using `>waifu list <page>`"
    embed.set_footer(text=footerText1 + "\n" + footerText2)

    return embed