Exemple #1
0
def removeItem(seller, category, itemDict):
    if category == "waifu":
        waifu = waifu_fAux.getWaifu(itemDict["waifuID"])
        UserProfile.load(seller).waifuRemove(waifu)
        return 0
    else:
        raise ValueError("not a valid category: {}".format(category))
Exemple #2
0
def buy_f(buyer, itemID):
    if not itemID.isdigit():
        return -1
    else:
        itemID = int(itemID)

    itemDoc = dbClient.getClient().DBot.marketplace.find_one({"itemID": itemID})
    if itemDoc is None:
        return -2
    
    if itemDoc["seller"]["id"] == buyer.id:
        return -3

    # check if buyer has enough money
    buyerProfile = UserProfile.load(buyer)
    if not buyerProfile.ecoCheckBalance(itemDoc["price"]):
        return -4

    # Remove from marketplace listing and add to buyer
    print(buyer)
    marketplace_fAux.addItem(buyer, itemDoc["category"], itemDoc["item"])
    marketplace_fAux.removeFromMarketplace(itemDoc["itemID"])

    # Remove money from buyer, and add to seller
    UserProfile.load(buyer).ecoChangeBalance(-itemDoc["price"], forced=True)
    
    seller = Bot.getBot().get_user(itemDoc["seller"]["id"])
    sellerProfile = UserProfile.load(seller)
    sellerProfile.ecoChangeBalance(itemDoc["price"], forced=True)

    # Assemble embed
    embed = marketplace_fAux.makeBuyEmbed(buyer, seller, itemDoc["category"], itemDoc["item"], itemDoc["price"], itemID)
    return embed
Exemple #3
0
def addItem(user, category, itemDict):
    print(user, category, itemDict)
    if category == "waifu":
        waifu = waifu_fAux.getWaifu(itemDict["waifuID"])
        print(waifu)
        UserProfile.load(user).waifuAdd(waifu)
    else:
        raise ValueError("not a valid category: {}".format(category))
    return 0
Exemple #4
0
    def eventStop(self):
        if self.winnerUser != None:
            UserProfile.load(self.winnerUser).ecoChangeBalance(self.prize,
                                                               forced=True)

        self.status = False
        self.setTimeStart(self.minWait, self.maxWait)

        self.winnerUser = None
        self.chochePhrase = None
        self.prize = 0
Exemple #5
0
    def eventStop(self):
        print(self.users)
        if len(self.users) > 0:
            for user in self.prizeDict.keys():
                print(type(user), user, self.prizeDict[user])
                UserProfile.load(user).ecoChangeBalance(self.prizeDict[user],
                                                        forced=True)

        self.status = False
        self.setTimeStart(self.minWait, self.maxWait)

        self.users = []
        self.prizeDict = dict()
Exemple #6
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
Exemple #7
0
def summon_f(user):
    profile = UserProfile.load(user)
    code = profile.waifuSummon()

    if code == -1:
        return -1

    waifu = waifu_fAux.getRandomWaifuByRank(waifu_fAux.getSummonRank())
    profile.waifuAdd(waifu)

    embedTitle = "\U00002728 {}'s Waifu Summon \U00002728".format(user)
    embedDescription = "You summoned a {}-tier Waifu!".format(waifu["rank"])
    embed = discord.Embed(title=embedTitle, description=embedDescription)

    infoValue1 = "Name: {}".format(waifu["name"])
    infoValue2 = ", alias {}".format(random.choice(
        waifu["aliases"])) if len(waifu["aliases"]) > 0 else ""
    infoValue3 = "From: {}".format(waifu["animeName"])
    embed.add_field(name="Basic Information",
                    value=infoValue1 + infoValue2 + "\n" + infoValue3)

    statsValue1 = "Value: {}".format(waifu["value"])
    statsValue2 = "Ranking: {}/{}".format(waifu["ranking"],
                                          waifu_fAux.waifuCount())
    embed.add_field(name="Stats", value=statsValue1 + "\n" + statsValue2)

    thumbnail_url = random.choice(waifu["pictures"])
    embed.set_thumbnail(url=thumbnail_url)

    return embed
Exemple #8
0
def isSellable(seller, category, itemDict):
    if category == "waifu":
        profile = UserProfile.load(seller)
        waifu = waifu_fAux.getWaifu(itemDict["waifuID"])
        return profile.waifuCheck(waifu)
    else:
        return -1
Exemple #9
0
def fuse_f(user, waifuID1, waifuID2, waifuID3):
    profile = UserProfile.load(user)

    # check if all of the 3 waifus are owned by the user
    waifuListCopy = profile.waifuList[:]
    try:
        waifuListCopy.remove(waifuID1)
        waifuListCopy.remove(waifuID2)
        waifuListCopy.remove(waifuID3)
    except:
        return -1

    # check if all of the 3 waifus are of the same rank
    waifu1 = waifu_fAux.getWaifu(waifuID1)
    waifu2 = waifu_fAux.getWaifu(waifuID2)
    waifu3 = waifu_fAux.getWaifu(waifuID3)
    if not (waifu1["rank"] == waifu2["rank"] == waifu3["rank"]):
        return -2

    # check if at least one is SSS
    if waifu1["rank"] == "SSS" or waifu2["rank"] == "SSS" or waifu3[
            "rank"] == "SSS":
        return -3

    # if all checks passed, get the a next-rank waifu
    nextRank = waifu_const.WAIFU_RANKS[
        waifu_const.WAIFU_RANKS.index(waifu1["rank"]) + 1]

    # Remove waifus from user profile
    profile.waifuRemove(waifu1)
    profile.waifuRemove(waifu2)
    profile.waifuRemove(waifu3)

    # Get random fused waifu
    fusedWaifu = waifu_fAux.getRandomWaifuByRank(nextRank)
    profile.waifuAdd(fusedWaifu)

    # Assemble embed
    embedTitle = "\U0001F9EC {}'s Waifu Fusion! \U0001F9EC".format(user)
    embedDescription = "You got a {}-tier Waifu!".format(fusedWaifu["rank"])
    embed = discord.Embed(title=embedTitle, description=embedDescription)

    infoValue1 = "Name: {}".format(fusedWaifu["name"])
    infoValue2 = ", alias {}".format(random.choice(
        fusedWaifu["aliases"])) if len(fusedWaifu["aliases"]) > 0 else ""
    infoValue3 = "From: {}".format(fusedWaifu["animeName"])
    embed.add_field(name="Basic Information",
                    value=infoValue1 + infoValue2 + "\n" + infoValue3)

    statsValue1 = "Value: {}".format(fusedWaifu["value"])
    statsValue2 = "Ranking: {}/{}".format(fusedWaifu["ranking"],
                                          waifu_fAux.waifuCount())
    embed.add_field(name="Stats", value=statsValue1 + "\n" + statsValue2)

    thumbnail_url = random.choice(fusedWaifu["pictures"])
    embed.set_thumbnail(url=thumbnail_url)

    return embed
Exemple #10
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
Exemple #11
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
Exemple #12
0
def favorite_f(user, favArg):
    if not (favArg.lower() == "clear" or favArg.isdigit()):
        return -2

    profile = UserProfile.load(user)
    if favArg.lower() == "clear":
        profile.waifuClearFavorite()
        return 1
    if favArg.isdigit():
        newFavWaifuID = int(favArg)
        code = profile.waifuSetFavorite(newFavWaifuID)
        return code
Exemple #13
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
Exemple #14
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
Exemple #15
0
    def eventStop(self):
        if self.user != None:
            profile = UserProfile.load(self.user)
            profile.ecoChangeBalance(-self.lastBid)
            profile.waifuAdd(self.waifu)

        self.status = False
        self.setTimeStart(self.minWait, self.maxWait)

        self.waifu = None
        self.startingBid = 0
        self.buyoutPrize = 0
        self.bidStepUp = 1

        self.user = None
        self.lastBid = 0
        self.lastBidTime = None
        self.lastBidTimeChecked = None
Exemple #16
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
Exemple #17
0
def addmoney_f(ctx, user, changeAmount):
    if not isAdmin(ctx.author):
        return -1
    else:
        UserProfile.load(user).ecoChangeBalance(changeAmount, forced=True)
        return 0
Exemple #18
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