Пример #1
0
def fishOffHandler():
    dir = './data/bucket'
    now = datetime.datetime.now()
    lastMonth = now - datetime.timedelta(days=now.day)
    monthStr = lastMonth.strftime("%b")
    yearStr = lastMonth.strftime("%Y")
    #nowdebug = 1
    #if nowdebug == 1:
    if now.day == 1:
        print(f'Today is the first of the month!')

        path = "./data/bucket/"
        highscoreDict = {}
        x = os.listdir(path)
        if len(x) == 0:
            return
        for i in x:
            filePath = path + i
            with open(filePath, "r") as f:
                data = json.load(f)
                sort_bucket = sorted(data.items(),
                                     key=lambda x: x[1],
                                     reverse=True)
                sortdict = dict(sort_bucket)
                topFish = next(iter(sortdict))
                topFishWeight = sortdict[topFish]
                nameFix = i[:-5]
                highscoreDict[nameFix + ' - ' + topFish] = topFishWeight
                sort_score = sorted(highscoreDict.items(),
                                    key=lambda x: x[1],
                                    reverse=True)
                sort_score_dict = dict(sort_score)
                #Code to return the winner for future winnerlist.
                y = next(iter(sort_score_dict))
                z = str(sort_score_dict[y])

        winnertext = monthStr + " " + yearStr + " " + y + " " + z

        Key = monthStr + yearStr
        filePath2 = "./data/fishoffwinners.json"
        with open(filePath2, "r") as f2:
            data2 = json.load(f2)
            if Key in data2:
                print(f'{Key} entry already exists...ignoring')
            else:
                print(f'A fishoff winner been crowned {winnertext}')
                userIdSplit = y.split()[0]
                handleMoney(userIdSplit, 100)
                print(f'{y} is given 100 money'
                      )  #debugging to find the problem for next season.
                data2[Key] = winnertext
                writeJSON(filePath2, data2)
                for f in os.listdir(dir):
                    os.remove(os.path.join(dir, f))
                    print(f'Deleting {f}')
                return (winnertext)
    else:
        print(
            f'Today is NOT the first of the month, its {now.day}...keep fishing'
        )
Пример #2
0
def addFish(discordId, fish, weight, classInt):
    discordIdStr = str(discordId)
    jsonFile = discordIdStr + '.json'
    filePath = "./data/bucket/" + jsonFile
    #print(f'Loading file...{filePath}')
    if os.path.isfile(filePath) == True:
        #print(f'File found!')
        with open(filePath, "r") as f:
            data = json.load(f)
            if fish in data:
                #print(f"That fish type is in the bucket already.")
                if data[fish] < weight:
                    x = (
                        f'NEW RECORD {fish}! This new one was {weight} the one in your bucket was only {data[fish]}'
                    )
                    oldPb = data[fish]
                    data[fish] = weight
                    writeJSON(filePath, data)
                    #new rogue
                    value = handleMoney(discordIdStr, 0, fish, classInt, oldPb)
                    return (oldPb, value)
                else:
                    x = (
                        f'This {fish} was only {weight}, you already have one at {data[fish]}'
                    )
                    currentPb = data[fish]
                    value = handleMoney(discordIdStr, 0, fish, classInt,
                                        weight)
                    return (currentPb, value)
            else:
                x = (f"New fish type! great addition to your bucket!")
                data[fish] = weight
                writeJSON(filePath, data)
                return (0.0, 0)
    else:
        x = ""
        #print(f"JSON not found! Creating...")
        data = {fish: weight}
        writeJSON(filePath, data)
    #old system
    #return(x)
    return (0.0, 0)
Пример #3
0
    async def on_message(self, message):
        txt = message.content
        #Make sure the message is from a normal person.
        if message.author.bot:
            return
        #message mentions woodhouse with or with caps?
        if message.content.__contains__(
                "Woodhouse") or message.content.__contains__("woodhouse"):
            t = get_timestamp_str()
            u = message.author
            u_str = str(u)[:-5]
            #TODO move this get_speech call to where its needed to improve response time
            i = get_speech(self)
            p = bool(random.getrandbits(1))
            if p == True:
                await message.channel.send(i)
                print(
                    '{} {} mentioned woodhouse by name , response was -----> {}'
                    .format(t, u, i))
            else:
                o = bool(random.getrandbits(1))
                if o == True:
                    i2 = random.choice(response_flare)
                    c_response = u_str + ", " + i2
                    await message.channel.send(c_response)
                    print(
                        '{} {} mentioned woodhouse by name , response was -----> {}'
                        .format(t, u, c_response))
                else:
                    b_response = i + ", " + u_str
                    await message.channel.send(b_response)
                    print(
                        '{} {} mentioned woodhouse by name , response was -----> {}'
                        .format(t, u, b_response))

        if message.content.startswith('$url'):
            i = pick_url()
            t = get_timestamp_str()
            u = message.author
            print('{}Manual triggered URL request by {} -----> {}'.format(
                t, u, i))
            await message.channel.send(i)

        if message.content.startswith('$holiday'):
            i = get_holiday()
            t = get_timestamp_str()
            u = message.author
            print('{}Manual triggered Holiday request by {} -----> {}'.format(
                t, u, i))
            await message.channel.send(i)

        m = re.search(r'(?:\s|^)(\-?\d+)( ?celcius| ?fahrenheit|c|f)\b',
                      txt,
                      flags=re.IGNORECASE)
        if m:
            t = get_timestamp_str()
            u = message.author
            i = int(m[1])
            unit = m[2]
            if unit.lower().startswith('c'):
                c = round(9.0 / 5.0 * i + 32)
                resp = [
                    'Muuuurica!', '', 'Sir, ',
                    'I know what that is in freedom units'
                ]
                r = random.choice(resp)
                msg = f'{r} {i}c is {c}f'
                print(f'{t} Converted C to F for {u}')
                await message.channel.send(msg)
            if unit.lower().startswith('f'):
                c = round((i - 32) * 5.0 / 9.0)
                resp = [
                    'Sir im delighted to tell you that', '', 'Sir, ',
                    'Oh oh oh! i know that',
                    'My superior intelligence tell me that'
                ]
                r = random.choice(resp)
                msg = f'{r} {i}f is {c}c'
                print(f'{t} Converted F to C for {u}')
                await message.channel.send(msg)

        if message.content.startswith('$highscore'):
            x = highscore()
            t = get_timestamp_str()
            u = message.author
            print('{}{}Requested highscore list....'.format(t, u))
            await message.channel.send(x)

        if message.content.startswith('$shutup'):
            global shutup
            if shutup == 0:
                shutup = 1
                t = get_timestamp_str()
                u = message.author
                print('{}{} Told woodhouse to shutup...'.format(t, u))
                l = [
                    'Yes, sir.', 'righto', 'Its gonna be a itchy day...',
                    'will do!', 'Very good, sir.'
                ]
                x = random.choice(l)
                await message.channel.send(x)
            else:
                t = get_timestamp_str()
                u = message.author
                print(
                    '{}{} Told woodhouse to shutup...but he was already doing it.'
                    .format(t, u))
                k = str(u)
                y = k[:-5]
                x = '{} im terribly sorry but i cant shut up more then i already am...'.format(
                    y)
                await message.channel.send(x)

        if message.content.startswith('$speak'):
            #x = get_speech(self)
            x = ranswer()  #Testing markovify
            t = get_timestamp_str()
            u = message.author
            print('{}Manual trigger issued by {} chosen reply was -----> {}'.
                  format(t, u, x))
            await message.channel.send(x)

        if message.content.startswith('$test'):
            count = 0
            seek = 10
            channel = self.get_channel(194028816333537280)
            async for message in channel.history(limit=seek):
                if message.author == self.user:
                    count += 1
            print('{}/{} of the last messages was Woodhouses...'.format(
                count, seek))

        if message.content.startswith('$dex'):
            dexUser = message.author
            t = get_timestamp_str()
            print('{}Listing {}s pokédex...'.format(t, dexUser))
            uiDex = str(dexUser)
            filePathDex = './data/' + uiDex
            fE = open(filePathDex, 'a')
            fE.close()

            with open(filePathDex) as f2:
                # list of mons stripping newlines and removing empty lines
                mons = [mon.strip() for mon in f2.readlines() if mon.strip()]
                count = len(mons)
                badge_num = -1
                if count >= THRESHOLDS[0]:
                    badge_num = 0
                    while count >= THRESHOLDS[badge_num + 1]:
                        badge_num += 1
                # badge_text = '' if badge_num < 0 else f'{badge_num + 1}/8 BADGES'
                # status = f'{dexUser}\'s POKÉDEX  {count}/894 CAUGHT  {badge_text}'
                # last_five = '\n'.join(mons[-5:])
                # if count == 0: last_five = '  GO CATCH SOME POKÉMON FIRST'
                trainer = str(dexUser).replace('#', '%23')
                url = f'http://thedarkzone.se/arachne/pokedex?trainer={trainer}'
                # msg = f'```{status}\n{last_five}```\n{url}'

                # TODO embed user's arachne avatar?
                embed = discord.Embed()
                embed.title = f'{dexUser}\'s POKÉDEX'
                embed.url = url
                last_five = '\n'.join(['> ' + mon for mon in mons[-5:]])
                if count == 0:
                    last_five = 'Go catch some pokémon first!'
                embed.add_field(name='CAUGHT',
                                value=f'{count}/894',
                                inline=True)
                if badge_num >= 0:
                    embed.add_field(name='BADGES',
                                    value=f'{badge_num + 1}/8',
                                    inline=True)
                embed.add_field(name='Last 5 Pokémon',
                                value=last_five,
                                inline=False)

                if badge_num >= 0:
                    await message.channel.send(
                        embed=embed,
                        file=discord.File(BADGE_PATH_PROGRESS[badge_num]))
                else:
                    await message.channel.send(embed=embed)

        if message.content.startswith('$catch'):
            global pokemonAlive
            global pokePick
            discordId = message.author
            discordName = message.author.name  #test
            t = get_timestamp_str()
            print('{}{} is attempting pokemon catch...'.format(t, discordId))
            uid = str(discordId)
            if pokemonAlive == 1:
                #catchAttempt = bool(random.getrandbits(1))
                if random.randint(1, 10) < 9:
                    pokemonAlive = 0
                    filePath = './data/' + uid
                    f = open(filePath, 'a')
                    # fE = open(filePath, 'w+')
                    # fE.close()
                    record = pokePick.title()
                    recordEntry = [record]

                    with open(filePath) as fDex2:
                        contentDex = fDex2.readlines()
                        listC2 = [a for a in contentDex if a != '\n']
                        listC3 = [i.strip() for i in listC2]
                        #print(listC3)
                        listC4 = ('\n'.join(map(str, listC3)))

                        if record not in listC4:
                            count = len(
                                listC4.split('\n')
                            ) + 1  # Use this to figure out if a player has reached a badge
                            #f = open(filePath, 'a')
                            writer = csv.writer(f)
                            writer.writerow(recordEntry)
                            f.close()
                            msg = f'yaml\n{discordId} CAUGHT {pokePick}!'
                            badge_pic = None
                            if count in THRESHOLDS:
                                badge_num = THRESHOLDS.index(count)
                                badge_pic = BADGE_PATH_SINGLE[badge_num]
                                msg += f'\n {discordId} EARNED A NEW BADGE!'
                                await message.channel.send(
                                    f'```{msg}```',
                                    file=discord.File(badge_pic))
                            else:
                                await message.channel.send(f'```{msg}```')
                            t = get_timestamp_str()
                            print('{}{} caught {}'.format(
                                t, discordId, pokePick))
                            #Catch history entry
                            try:
                                postCatch = Post(body='{} CAUGHT {}!'.format(
                                    discordName, pokePick),
                                                 pokemon=pokePick,
                                                 user_id=discordId.id)
                                db.session.add(postCatch)
                                db.session.commit()
                            except Exception as e:
                                print(
                                    '{}ERROR Could not put pokemon into catch history!'
                                    .format(t))
                                print(e)
                        else:
                            await message.channel.send(
                                """```yaml\n{} CAUGHT {}...but already had it!```"""
                                .format(discordId, pokePick))
                            #print("We had that one...")

                else:
                    await message.channel.send(
                        """```yaml\n{} BROKE OUT FOR {}!```""".format(
                            pokePick, discordId))

        if message.content.startswith('$mmo'):
            mmoMessage = message.content.replace('$mmo ', '')
            if len(mmoMessage.split()) != 2:
                print('Wrong string input')
                return
            mmoName, mmoClass = mmoMessage.split(' ', 1)
            mmoScore = playMMO(mmoName, mmoClass)
            t = get_timestamp_str()
            u = message.author
            print('{}{} played the mmo...'.format(t, u))
            await message.channel.send(mmoScore)


#Fish catching game woo
        if message.content.startswith('$cast'):
            discordId = message.author
            t = get_timestamp_str()
            print('{}{} is casting a line...'.format(t, discordId))
            uid = str(discordId)
            failFlare = [
                "broke the line and fish got away...", "fell in the water.",
                "caught nothing...", "reels in the empty line...",
                "broke the fishing pole",
                "lost the fish and spilled their beer",
                "with all their force throwing their entire fishing rod, hook, line and sinker.",
                "after a long tough fight the fish got away"
            ]
            #This whole mess is to combat a File not found and just placing in the number 13 to get started
            now = datetime.datetime.now()
            try:
                f = open('./data/fishTime/' + uid, 'r')
            except FileNotFoundError:
                f = open('./data/fishTime/' + uid, "w")
                f.write("13")
                f.close()
                f = open('./data/fishTime/' + uid, "r")
            #test check for day
            timeCheck = int(f.readline())
            #fname = pathlib.Path('./data/fishTime/'+uid)
            #mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
            f.close()
            #Check if person has fished in the current hour
            if timeCheck != now.hour:
                #random xp modifier
                lvl = getLevel(discordId)
                diff = 0.025 * lvl
                if diff > 2:
                    diff = 2  #already 100% successrate
                    print("User is at max fishing sucessrate")
                roll = random.uniform(
                    3 + diff, 10)  #at level 80 you have 100% successrate
                #if random.randint(1,10) < 3: #oldroll
                if roll < 5:
                    await message.channel.send(
                        """```yaml\n{} Casts their line but {}!```""".format(
                            discordId, random.choice(failFlare)))
                    f = open('./data/fishTime/' + uid, "w")
                    f.write(str(now.hour))
                    f.close()
                    #write fail into stats
                    with open("./data/fishstats.json", "r") as f:
                        data = json.load(f)
                    if uid not in data["users"]:
                        data["users"][uid] = {}
                        data["users"][uid]["numbers"] = 0
                        data["users"][uid]["fails"] = 0
                    data["users"][uid]["fails"] += 1
                    writeJSON("./data/fishstats.json", data)
                    f.close()
                    if os.path.isfile(
                            f"./data/fishprofiles/{uid}.json") == True:
                        x = handleMoney(discordId, -3)
                else:
                    x = cast_line(discordId, currentSchool)
                    await message.channel.send(embed=x)
            else:
                await message.channel.send(
                    """```yaml\nYou are not allowed to fish again this soon {}!```"""
                    .format(discordId))

        if message.content.startswith('$fishoff'):
            t = get_timestamp_str()
            u = message.author
            print('{}{} is listing the fishoff highscores'.format(t, u))
            x, winner = fishOff()
            await message.channel.send(
                """```yaml\n\n     FISH OFF MONTHLY HIGHSCORE\n{}```""".format(
                    x))

        if message.content.startswith('$bucket'):
            t = get_timestamp_str()
            u = message.author
            print('{}{} is listing their bucket'.format(t, u))
            x = bucket(u)
            await message.channel.send("""```yaml\n\n{}```""".format(x))

        if message.content.startswith('$fishscore'):
            t = get_timestamp_str()
            u = message.author
            print('{}{} is listing the all time fishoff winners'.format(t, u))
            x = fishscore()
            await message.channel.send("""```yaml\n\n{}```""".format(x))

        if message.content.startswith('$fishstats'):
            t = get_timestamp_str()
            u = message.author
            print('{}{} is listing the fishstats'.format(t, u))
            x = listFishStats()
            await message.channel.send("""```yaml\n\n{}```""".format(x))

        if message.content.startswith('$where'):
            t = get_timestamp_str()
            u = message.author
            print('{}{} is asking where i am'.format(t, u))
            url = "http://checkip.dyndns.org"
            request = requests.get(url)
            clean = request.text.split(': ', 1)[1]
            my_ip = clean.split('</body></html>', 1)[0]
            my_host = socket.gethostname()
            x = (f'Oh maybe i have a new ip?\n{my_host}\n{my_ip}')
            await message.channel.send("""```yaml\n\n{}```""".format(x))

        if message.content.startswith('$buy'):
            t = get_timestamp_str()
            u = message.author
            x = buyCast(u)  #returns True if user can afford it, False if not.
            if x == True:
                print('{}{} bought an extra cast'.format(t, u))
                xZ = f'{u} bought an extra cast for 50 Bells!'
                await message.channel.send("""```yaml\n\n{}```""".format(xZ))
            else:
                xZ = f'{u} you cant afford a extra cast right now(or you already have a cast this hour)'
                await message.channel.send("""```yaml\n\n{}```""".format(xZ))
Пример #4
0
def cast_line(discordId, school):
    #define variables n stuff
    uid = str(discordId)
    fileDir = "./data/fishdata/"
    fishFiles = [
        "class1.json", "class2.json", "class3.json", "class4.json",
        "class5.json", "class6.json", "class7.json"
    ]
    #pick random fish with weighted chances
    chosenClass = random.choices(fishFiles, weights=school)
    #print(f'[DEBUG]Current school is {school}')
    filePath = fileDir + chosenClass[0]
    #access json should never error but anyways?
    try:
        with open(filePath, "r") as f:
            data = json.load(f)
            #print(f'LOADED {filePath}!')
    except FileNotFoundError:
        return (f'ERROR {filePath} NOT FOUND SOMETHING IS WRONG HERE...')
    #Ugly data converting back and forth cause i dont know syntax
    z = random.choice(list(data))
    j = data[z]['joke']
    wL = data[z]['weightLow']
    wH = data[z]['weightHigh']
    c = chosenClass[0][:-5]
    #Shiny check/add
    if random.randint(1, 160) == 160:
        shiny = True
        if c == "class7":
            wH = wH * 2
        else:
            wL = wL * 2
            wH = wH * random.randint(2, 5)
        handleMoney(uid, 50)
    else:
        shiny = False
    #Triangular weighted random weight test.
    mid = (wL + wH) / 2
    w = round(random.triangular(wL, wH, mid), 2)
    #Make the only fish once and hour mark.
    now = datetime.datetime.now()
    f = open('./data/fishTime/' + uid, "w")
    f.write(str(now.hour))
    f.close()
    #check WR stuff
    wr, holder = get_wr(z)  # get the current wr if any
    #changed check_wr to this if statement
    if holder == "None":  # assuming if no wr we get back weight is 0.0 and holder is "None"
        write_wr(
            uid, z, w
        )  #added this rogue, cause it dont write the first ever record i think.
        wr, holder = 0.0, ""
    elif w > wr:  # if new fish is wr, write it to file
        write_wr(uid, z, w)
    cI = int(c[5:])
    #addfish to buckets if needed
    if shiny == True:
        q, value = addFish(discordId, z + "*", w,
                           cI)  #add the asterix to shiny fish to offset.
    else:
        q, value = addFish(discordId, z, w,
                           cI)  #check bucket and add if needed
    #return for rogue embed
    #record stats(wip)
    fishStats(uid, z, w, cI, shiny)
    Xvalue, xp, dinged = profileHandler(uid, z, cI,
                                        w)  # manage profile system(WIP)
    x = fishing_embed(uid,
                      z,
                      j,
                      cI,
                      w,
                      value,
                      xp,
                      shiny,
                      ding=dinged,
                      old_pb=q,
                      old_wr=wr,
                      dethroned=holder)  #return for rogue embedd
    return (x)