Ejemplo n.º 1
0
 async def do_work():
     await ctx.channel.trigger_typing()
     sender = ctx.message.author
     message_logger(
         "COMMAND",
         ".edit_leaderboard command requested by " + sender.display_name)
     filename = args[0] + ".audica"
     leaderboard_id = args[1]
     database = customs_database()
     database.load()
     song = database.get_song_with_filename(filename)
     song_filename = song["filename"].replace(".audica", "")
     if song == False:
         m = await ctx.send(
             content="Could not find the song_id in the database.")
     else:
         try:
             hash = leaderboard_id.replace(song_filename + "_", "")
         except:
             hash = leaderboard_id
         if len(hash) != 32:
             m = await ctx.send(content="Invalid leaderboard hash.")
         else:
             if len(leaderboard_id) == 32:
                 leaderboard_id = song_filename + "_" + hash
             database.edit_leaderboard_id(song_filename, leaderboard_id)
             database.save()
             m = await ctx.send(
                 content="Song with ID \"" + song_filename +
                 "\" was successfully edited with the leaderboard hash \"" +
                 hash + "\".")
     client.loop.create_task(cooldown_reaction(m,
                                               edit_leaderboard_cooldown))
Ejemplo n.º 2
0
 async def process_scores(song, scores):
     old_scores = scores[0]
     new_scores = scores[1]
     if old_scores == []:
         return
     else:
         temp_old_scores = []
         temp_new_scores = []
         for score in old_scores:
             temp = score
             temp["timestamp"] = 0
             temp_old_scores.append(temp)
         for score in new_scores:
             temp = score
             temp["timestamp"] = 0
             temp_new_scores.append(temp)
         count = 0
         if temp_old_scores != temp_new_scores:
             message_logger("CUSTOMS LEADERBOARDS", "[SONG \"" + song[0] + "\"] Found new scores.")
             for channel in client.get_all_channels():
                 if str(channel) == "leaderboards":
                     if str(channel.guild) in servers_to_operate:
                         if temp_new_scores == []:
                             await channel.send(content="Scores were wiped for " + song + " and this leaderboard is currently empty.")
                         else:
                             embed = make_top20_autoupdate_embed(song[0], temp_old_scores, temp_new_scores, custom=True, api=api)
                             await channel.send(embed=embed)
         else:
             message_logger("CUSTOMS LEADERBOARDS", "[SONG \"" + song[0] + "\"] No new scores.")
Ejemplo n.º 3
0
async def on_ready():
    message_logger("COMMANDS BOT", "Connected to Discord.")
    message_logger("COMMANDS BOT", "Ready to execute commands.")
    for channel in client.get_all_channels():
        if str(channel.guild) in servers_to_operate:
            if str(channel) == "audica-friend-codes":
                async for message in (channel.history(limit=10000)):
                    if "<audica_friend_code " in message.content:
                        result = await add_friend_code(message)
                        if result == True:
                            await message.add_reaction(approved_emoji)
                            await asyncio.sleep(0.25)
            elif str(channel) == "finished-songs":
                async for message in (channel.history(limit=10000)):
                    if len(message.attachments) > 0:
                        processed_messages = []
                        try:
                            f = open("finished-songs-processed-messages.txt",
                                     "r")
                            for line in f:
                                processed_messages.append(
                                    line.replace("\n", ""))
                            f.close()
                        except:
                            print(
                                "finished-songs-processed-messages.txt does not exist"
                            )
                        if str(message.id) not in processed_messages:
                            await process_custom_song(message)
                            processed_messages.append(str(message.id))
                        f = open("finished-songs-processed-messages.txt", "w")
                        for line in processed_messages:
                            f.write(line + "\n")
                        f.close()
Ejemplo n.º 4
0
async def songidlist(ctx):
    if str(ctx.guild) in servers_to_operate:
        sender = ctx.message.author
        message_logger(
            "COMMAND",
            ".songidlist command requested by " + sender.display_name)
        m = await ctx.send(embed=make_songid_embed(sender))
        client.loop.create_task(
            cooldown_reaction(m, songidlist_command_cooldown))
Ejemplo n.º 5
0
 async def do_work():
     await ctx.channel.trigger_typing()
     sender = ctx.message.author
     message_logger("COMMAND",
                    ".myscores command requested by " + sender.display_name)
     if ctx.message.content == ".myscores":
         codes = friend_codes()
         codes.load()
         code = codes.get_code(ctx.author.id)
         if code == None:
             message_logger("COMMAND",
                            "Help message sent, error with arguments")
             for channel in ctx.guild.channels:
                 if str(channel) == "audica-friend-codes":
                     m = await ctx.send(
                         content=
                         "Friend code not found. To link your friend code post it in "
                         + channel.mention + ".")
                     client.loop.create_task(
                         cooldown_reaction(m, myscores_command_cooldown))
         else:
             request = api.post_request(api.global_songs, [code])
             pages = []
             page = []
             all_songs = []
             count = 0
             ammount = 0
             total_score = 0
             for i in request["leaderboard"]:
                 if i["data"] != []:
                     if i["leaderboard_name"] != "all_time_leaders":
                         if i["leaderboard_name"] != "all_time_totals":
                             ammount = ammount + 1
             for p in request["leaderboard"]:
                 if p["leaderboard_name"] != "all_time_leaders":
                     if p["leaderboard_name"] != "all_time_totals":
                         if p["data"] != []:
                             page.append(p)
                             count = count + 1
                             print(count)
                             total_score = total_score + p["data"][0][
                                 "score"]
                             if count == 20 or count == 40 or count == ammount:
                                 pages.append(page)
                                 page = []
             for page in pages:
                 for data in page:
                     all_songs.append(data)
             m = None
             for page in pages:
                 m = await ctx.send(embed=make_myscores_embed(
                     page, sender, api, all_songs, total_score))
                 await asyncio.sleep(0.1)
             client.loop.create_task(
                 cooldown_reaction(m, myscores_command_cooldown))
Ejemplo n.º 6
0
async def delete_song(ctx, *args):
    user_id = ctx.author.id
    sender = ctx.message.author
    database = customs_database()
    database.load()
    found = False
    message_logger("COMMAND",
                   ".delete_song command requested by " + sender.display_name)
    for song in database.song_list:
        if song["filename"] == args[0] or song["song_id"] == args[0]:
            found = True
            if user_id == song["uploader"] or await client.is_owner(ctx.author
                                                                    ):
                database.delete(song["song_id"])
                database.save()
                os.remove(audica_custom_songs_folder + os.sep +
                          song["filename"])
                await ctx.send(content="`" + song["song_id"] +
                               "` successfully deleted.")
                message_logger("COMMAND", song["song_id"] + "deleted.")
            else:
                await ctx.send(
                    content="You do not have permission to delete `" +
                    song["song_id"] + "`.")
                message_logger("COMMAND",
                               "Does not have permission to delete.")
            break
    if found == False:
        await ctx.send(
            content="Did not find a song with `" + args[0] +
            "` as either song_id or filename. Please specify the exact filename or song_id of the song to delete."
        )
        message_logger("COMMAND", "Song not found.")
Ejemplo n.º 7
0
 async def do_work():
     await ctx.channel.trigger_typing()
     sender = ctx.message.author
     message_logger(
         "COMMAND",
         ".leaderboards command requested by " + sender.display_name)
     if ctx.message.content == ".leaderboards":
         m = await ctx.send(embed=make_leaderboards_help_embed(sender))
         message_logger("COMMAND", "Help message sent, no arguments given")
         client.loop.create_task(
             cooldown_reaction(m, leaderboards_command_cooldown))
     else:
         try:
             parameters = parse_leaderboards_args(args)
             if parameters == False:
                 m = await ctx.send(
                     embed=make_leaderboards_help_embed(sender))
                 message_logger("COMMAND",
                                "Help message sent, error with arguments")
                 client.loop.create_task(
                     cooldown_reaction(m, leaderboards_command_cooldown))
                 return
             songid = parameters["songid"]
             platform = parameters["platform"]
             difficulty = parameters["difficulty"]
             user = parameters["user"]
             harmonix = parameters["harmonix"]
             results = api.search_database_for_song(songid,
                                                    user=user,
                                                    top20=False,
                                                    platform=platform,
                                                    difficulty=difficulty,
                                                    harmonix=harmonix)
             m = await ctx.send(embed=make_leaderboards_embed(
                 results, sender, songid, difficulty, api=api))
             message_logger(
                 "COMMAND",
                 "Search successful. songid=" + songid + ", user="******", platform=" + platform + ", difficulty=" + difficulty +
                 ", harmonix=" + str(harmonix))
             client.loop.create_task(
                 cooldown_reaction(m, leaderboards_command_cooldown))
         except Exception as e:
             print(e)
             m = await ctx.send(embed=make_leaderboards_help_embed(sender))
             message_logger("COMMAND",
                            "Help message sent, error with arguments")
             client.loop.create_task(
                 cooldown_reaction(m, leaderboards_command_cooldown))
Ejemplo n.º 8
0
 async def do_work():
     await ctx.channel.trigger_typing()
     sender = ctx.message.author
     message_logger("COMMAND",
                    ".compare command requested by " + sender.display_name)
     users = user_list()
     codes = friend_codes()
     users.load()
     codes.load()
     user = codes.get_code(sender.id)
     if user == None:
         message_logger("COMMAND",
                        "Help message sent, error with arguments")
         for channel in ctx.guild.channels:
             if str(channel) == "audica-friend-codes":
                 m = await ctx.send(
                     content=
                     "Friend code not found. To link your friend code post it in "
                     + channel.mention + ".")
     else:
         try:
             request = api.post_request(api.global_songs, [user])
             pages = []
             page = []
             all_songs = []
             count = 0
             ammount = 0
             for i in request["leaderboard"]:
                 if i["data"] != []:
                     ammount = ammount + 1
             for p in request["leaderboard"]:
                 if p["data"] != []:
                     page.append(p)
                     count = count + 1
                     if count == 20 or count == 40 or count == ammount:
                         pages.append(page)
                         page = []
             m = None
             for page in pages:
                 #print(page)
                 m = await ctx.send(
                     embed=make_compare_mps_embed(page, user, sender, api))
         except Exception as e:
             print(e)
             m = await ctx.send(content="Unexpected error with the command."
                                )
     client.loop.create_task(cooldown_reaction(m, compare_command_cooldown))
Ejemplo n.º 9
0
 async def do_work():
     await ctx.channel.trigger_typing()
     sender = ctx.message.author
     message_logger(
         "COMMAND", ".missing_leaderboards command requested by " +
         sender.display_name)
     database = customs_database()
     database.load()
     songs = []
     for song in database.song_list:
         if song["leaderboard_id"] == "":
             songs.append(song["filename"].replace(".audica", ""))
     message_string = "Filename of songs with missing leaderboard ID:\n\n"
     for song in songs:
         message_string = message_string + song + "\n"
     m = await ctx.send(content=message_string)
     client.loop.create_task(cooldown_reaction(m,
                                               edit_leaderboard_cooldown))
Ejemplo n.º 10
0
async def audica_twitch_streams_loop():
    global running
    running = True
    all_channels = client.get_all_channels()
    try:
        ttv_api = twitch_api()
        new_streams = ttv_api.update_live_streams()
        all_streams = ttv_api.live_streams
        if new_streams != []:
            for channel in all_channels:
                if str(channel) == "audica-streams":
                    if str(channel.guild) in servers_to_operate:
                        for stream in new_streams:
                            user_data = ttv_api.get_user(stream["user_id"])
                            await channel.send(embed=make_twitch_embed(
                                stream, user_data["data"][0]))
        for channel in all_channels:
            if str(channel) == "audica-streams":
                async for message in (channel.history(limit=10)):
                    #print(message)
                    if message.author.id == client.user.id:
                        try:
                            streamer_name = message.embeds[0].author.name
                            streamer_found = False
                            for stream in all_streams:
                                if "Twitch" == str(
                                        message.embeds[0].title.split(" ")[1]):
                                    user_data = ttv_api.get_user(
                                        stream["user_id"])
                                    if streamer_name == user_data["data"][0][
                                            "login"]:
                                        streamer_found = True
                            if "Twitch" == str(
                                    message.embeds[0].title.split(" ")[1]):
                                if streamer_found == False:
                                    await message.add_reaction(offline_emoji)
                        except:
                            pass
        log_string = "New live streams: "
        for stream in new_streams:
            log_string = log_string + "\"" + stream["user_name"] + "\" "
        if new_streams != []:
            message_logger("TWITCH LOOP", log_string)
        else:
            message_logger("TWITCH LOOP", "No new Audica streams.")
        await asyncio.sleep(150)
    except Exception as e:
        message_logger(
            "TWITCH LOOP",
            "Loop crashed, printing error on next line and restarting in 30 seconds..."
        )
        message_logger("TWITCH LOOP", str(e))
        await asyncio.sleep(150)
    asyncio.ensure_future(audica_twitch_streams_loop())
Ejemplo n.º 11
0
async def cache_song_leaderboard(song, current_page=1):
        
    stop_running = False

    if not os.path.exists(api.leaderboards_cache_folder + os.sep + song):
        os.makedirs(api.leaderboards_cache_folder + os.sep + song)
        
    starting_page = current_page
    total_pages = current_page

    while(stop_running == False):
        req = api.request_song_leaderboard(song, page=str(current_page))
        if req == False:
            print("Error requesting page " + str(current_page) + " of " + str(total_pages) + " for the song " + song)
        else:
            reqjson = json.loads(req)
            total_pages = reqjson["leaderboard"]["total_pages"]
            if req == "page does not exist":
                stop_running = True
            else:
                f = open(api.leaderboards_cache_folder + os.sep + song + os.sep + str(current_page) + ".json", "w")
                f.write(req)
                f.close()
                if total_pages == 0:
                    current_page = 0
                    api.update_state(song, current_page, total_pages, start_time=True, custom=True)
                if current_page == 1:
                    api.update_state(song, current_page, total_pages, start_time=True, custom=True)
                    if total_pages == current_page:
                        api.update_state(song, current_page, total_pages, finish_time=True, custom=True)
                elif total_pages == current_page:
                    api.update_state(song, current_page, total_pages, finish_time=True, custom=True)
                else:
                    api.update_state(song, current_page, total_pages, custom=True)
            if current_page == total_pages:
                stop_running = True
                message_logger("CUSTOMS LEADERBOARDS", "[SONG \"" + song[:-33] + "\"] Page "+ str(current_page) + " of " + str(total_pages) + " saved. " + \
                                str(api.requests_left) + " of " + str(api.requests_per_hour) + " requests left.")
                message_logger("CUSTOMS LEADERBOARDS", "[SONG \"" + song[:-33] + "\"] Song cache saving and user data update is starting.")
                wait_time = api.find_optimal_wait_time(minimum_time=api.seconds_per_requests_customs)
                await asyncio.sleep(wait_time)
                return api.save_song_cache_to_database(song, custom=True)
            elif current_page == 0:
                stop_running = True
                message_logger("CUSTOMS LEADERBOARDS", "[SONG \"" + song[:-33] + "\"] This leaderboard has 0 pages.")
        if stop_running == False:
            message_logger("CUSTOMS LEADERBOARDS", "[SONG \"" + song[:-33] + "\"] Page "+ str(current_page) + " of " + str(total_pages) + " saved. " + \
                           str(api.requests_left) + " of " + str(api.requests_per_hour) + " requests left.")
        if api.loop_running == False:
            stop_running = True
        current_page = current_page + 1
        wait_time = api.find_optimal_wait_time(minimum_time=api.seconds_per_requests_customs)
        await asyncio.sleep(wait_time)
Ejemplo n.º 12
0
def audica_leaderboards_update_loop():
    try:
        while True:
            try:
                message_logger(
                    "LEADERBOARDS API",
                    "Automatic update of the full leaderboards is starting...")
                api.update_loop()
            except Exception as e:
                message_logger(
                    "LEADERBOARDS API",
                    "Error, printing the error on the next line and waiting 30 seconds..."
                )
                message_logger("LEADERBOARDS API", str(e))
                time.sleep(30)
    except:
        message_logger(
            "LEADERBOARDS API",
            "Error, loop crashed unexpectedly, will restart the loop in 30 seconds..."
        )
        message_logger("LEADERBOARDS API", str(e))
        time.sleep(30)
Ejemplo n.º 13
0
    def log_request(self, type):
        log_file = self.leaderboards_cache_folder + os.sep + "requests.log"
        temp_list = []
        try:
            if os.path.isfile(log_file):
                #f = open(log_file, "r")
                #fjson = json.load(f)
                #f.close()
                #for item in fjson:
                for item in self.log:
                    time_difference = time.time() - item["time"]
                    if time_difference < 3600:
                        temp_list.append(item)
        except:
            message_logger("LEADERBOARDS API",
                           "Request log corrupted, starting a new one...")
        log = {}
        log["type"] = type
        log["time"] = time.time()
        temp_list.append(log)

        self.log = temp_list
Ejemplo n.º 14
0
async def scan_all_finished_songs():
    message_logger("FUNCTION",
                   "Scanning all Audica custom songs from #finished-songs")
    messages = []
    async for message in (channel.history(limit=10000)):
        #timestamp = message.created_at
        #attachments = message.attachments
        #content = message.content
        #author = message.author
        if len(message.attachments) > 0:
            for attachment in message.attachments:
                if str(attachment.url)[-7:] == ".audica":
                    filename = str(attachment.url).split(os.sep)[-1]
                    message_logger("DOWNLOAD",
                                   "Downloading " + filename + "...")
                    await attachment.save(audica_folder + os.sep + filename)
                    message_logger("DOWNLOAD", "Download finished!")
                    messages.append(message)
                    break
    #print(messages)
    message_logger("FUNCTION", "Finished scanning Audica custom songs")
Ejemplo n.º 15
0
async def process_custom_song(message):
    database = customs_database()
    database.load()
    for attachment in message.attachments:
        if str(attachment.url)[-7:] == ".audica":
            filename = str(attachment.url).split(os.sep)[-1]
            file_path = audica_custom_songs_folder + os.sep + filename
            try:
                found = False
                for song in database.song_list:
                    if song["filename"] == filename:
                        found = True
                if found == False:
                    if os.path.isfile(file_path) == False:
                        message_logger("CUSTOMS DATABASE",
                                       "Downloading " + filename + "...")
                        await attachment.save(file_path)
                        message_logger("CUSTOMS DATABASE",
                                       "Download finished!")
                        song = custom_song(file_path)
                        song.filename = filename
                        song.uploader = message.author.id
                        song.download_url = str(attachment.url)
                        song.upload_time = str(message.created_at)
                        m = message.content
                        if "\n" in m:
                            for line in m.split("\n"):
                                if "video:" in line.lower():
                                    song.video_url = line.split(
                                        "o:")[-1].replace(" ", "")
                                if song.desc_file.author == "" and "mapper:" in line.lower(
                                ):
                                    song.desc_file.author = line.split(
                                        ":")[-1].replace(" ", "")
                                if "leaderboard:" in line.lower():
                                    song.leaderboard_id = line.split(
                                        ":")[-1].replace(" ", "")
                        else:
                            if "video:" in m.lower():
                                song.video_url = m.split("o:")[-1].replace(
                                    " ", "")
                            if song.desc_file.author == "" and "mapper:" in m.lower(
                            ):
                                song.desc_file.author = m.split(
                                    ":")[-1].replace(" ", "")
                            if "leaderboard:" in m.lower():
                                song.leaderboard_id = m.split(":")[-1].replace(
                                    " ", "")
                        if database.add(song.get_song_data()) == False:
                            await message.author.send(
                                content="A file named \"" + filename +
                                "\" already exists in the database. The song was not added to the database."
                            )
                            os.remove(file_path)
                            await message.add_reaction(rejected_emoji)
                        database.save()
                        message_logger(
                            "CUSTOMS DATABASE",
                            "Added \"" + song.desc_file.artist + " - " +
                            song.desc_file.title + "\" authored by \"" +
                            song.desc_file.author + "\"")
                        await message.add_reaction(approved_emoji)
                    else:
                        await message.author.send(
                            content="A file named \"" + filename +
                            "\" already exists in the database. The song was not added to the database."
                        )
                        await message.add_reaction(rejected_emoji)
                else:
                    await message.author.send(
                        content="A file named \"" + filename +
                        "\" already exists in the database. The song was not added to the database."
                    )
                    await message.add_reaction(rejected_emoji)
            except Exception as e:
                os.remove(file_path)
                await message.author.send(
                    content="There was a problem processing the file \"" +
                    filename + "\".")
                await message.add_reaction(rejected_emoji)
                print(e)
        else:
            await message.author.send(
                content=
                "This channel is exclusively reserved to post audica files of finished songs."
            )
            await message.add_reaction(rejected_emoji)
Ejemplo n.º 16
0
async def on_ready():
    global running
    message_logger("TWITCH LOOP", "Connected to Discord.")
    if running == False:
        message_logger("TWITCH LOOP", "Starting the loop...")
        asyncio.ensure_future(audica_twitch_streams_loop())
Ejemplo n.º 17
0
async def on_ready():
    global running
    message_logger("TOP20 UPDATE BOT", "Connected to Discord.")
    if running == False:
        message_logger("TOP20 UPDATE BOT", "Starting update loop...")
        await audica_top20_update_loop()
Ejemplo n.º 18
0
async def audica_top20_update_loop():
    global running
    running = True
    message_logger("TOP20 UPDATE LOOP", "Loop started.")
    try:

        def save_json(filename, rjson):
            f = open(filename, "w")
            json.dump(rjson, f, sort_keys=True, indent=4)
            f.close()

        try:
            for song in api.ost:
                if song != "all_time_leaders" and song != "all_time_totals":
                    request = api.request_song_leaderboard(song,
                                                           platform="global",
                                                           difficulty="all",
                                                           page="1",
                                                           page_size="20")
                    rjson = json.loads(request)
                    filename = api.leaderboards_cache_folder + os.sep + song + "top20.json"
                    if os.path.isfile(filename):
                        f = open(filename, "r")
                        fjson = json.load(f)
                        f.close()
                        old_scores = fjson
                        new_scores = []
                        for item in rjson["leaderboard"]["data"]:
                            item = item[0]
                            new_scores.append(item)
                        if old_scores != new_scores:
                            message_logger(
                                "TOP20 UPDATE LOOP",
                                "[SONG \"" + song + "\"] Found new scores.")
                            channel_to_post = ""
                            if song in api.global_songs:
                                channel_to_post = channel_to_operate
                            else:
                                channel_to_post = channel_extra_songs
                            for channel in client.get_all_channels():
                                if str(channel) == channel_to_post:
                                    if str(channel.guild
                                           ) in servers_to_operate:
                                        if new_scores == []:
                                            await channel.send(
                                                content="Scores were wiped for "
                                                + song +
                                                " and this leaderboard is currently empty."
                                            )
                                        else:
                                            await channel.send(
                                                embed=
                                                make_top20_autoupdate_embed(
                                                    song, old_scores,
                                                    new_scores))
                            save_json(filename, new_scores)
                        else:
                            message_logger(
                                "TOP20 UPDATE LOOP",
                                "[SONG \"" + song + "\"] No new scores.")
                    else:
                        message_logger(
                            "TOP20 UPDATE LOOP", "[SONG \"" + song +
                            "\"] Leaderboards not found, saving current data..."
                        )
                        data = []
                        for item in rjson["leaderboard"]["data"]:
                            item = item[0]
                            data.append(item)
                        save_json(filename, data)
                    await asyncio.sleep(
                        api.find_optimal_wait_time(
                            minimum_time=(300.0 / len(api.ost) + 1) - 1))
        except Exception as e:
            print("problem top20-1")
            print(e)
            await asyncio.sleep(
                api.find_optimal_wait_time(
                    minimum_time=(300.0 / len(api.ost) + 1) - 1))
        try:
            request = api.request_song_leaderboard("all_time_leaders",
                                                   page_size="20")
            #request = api.request_all_time_leaders()
            rjson = json.loads(request)
            filename = api.leaderboards_cache_folder + os.sep + "globaltop20.json"
            song = "global"
            if os.path.isfile(filename):
                f = open(filename, "r")
                fjson = json.load(f)
                f.close()
                old_scores = fjson
                new_scores = []
                for item in rjson["leaderboard"]["data"]:
                    item = item[0]
                    new_scores.append(item)
                if old_scores != new_scores:
                    message_logger("TOP20 UPDATE LOOP",
                                   "[SONG \"" + song + "\"] Found new scores.")
                    for channel in client.get_all_channels():
                        if str(channel) == channel_to_operate:
                            if str(channel.guild) in servers_to_operate:
                                if new_scores == []:
                                    await channel.send(
                                        content="Scores were wiped for " +
                                        song +
                                        " and this leaderboard is currently empty."
                                    )
                                else:
                                    await channel.send(
                                        embed=make_top20_autoupdate_embed(
                                            song, old_scores, new_scores))
                    save_json(filename, new_scores)
                else:
                    message_logger("TOP20 UPDATE LOOP",
                                   "[SONG \"" + song + "\"] No new scores.")
            else:
                message_logger(
                    "TOP20 UPDATE LOOP", "[SONG \"" + song +
                    "\"] Leaderboards not found, saving current data...")
                data = []
                for item in rjson["leaderboard"]["data"]:
                    item = item[0]
                    data.append(item)
                save_json(filename, data)
            await asyncio.sleep(
                api.find_optimal_wait_time(minimum_time=(300.0 / len(api.ost)))
            )
        except Exception as e:
            print("problem top20-2")
            print(e)
            await asyncio.sleep(
                api.find_optimal_wait_time(minimum_time=(300.0 / len(api.ost)))
            )
        message_logger("TOP20 UPDATE LOOP",
                       "Loop finished, going back to first song...")
    except Exception as e:
        message_logger("TOP20 UPDATE LOOP",
                       "Loop crashed, should restart in 30 seconds...")
        print(e)
        await asyncio.sleep(30)
    top20_update_running = False
    client.loop.create_task(audica_top20_update_loop())
Ejemplo n.º 19
0
 def save_song_cache_to_database(self, song, custom=False):
     if custom == True:
         song_file = self.leaderboards_database_folder + os.sep + "CUSTOMS" + os.sep + song + ".json"
     else:
         song_file = self.leaderboards_database_folder + os.sep + song + ".json"
     cache_folder = self.leaderboards_cache_folder + os.sep + song
     cache_files = [
         f for f in os.listdir(cache_folder)
         if os.path.isfile(os.path.join(cache_folder, f))
     ]
     temp = []
     songjson = []
     oldjson = []
     if custom == True:
         try:
             f = open(song_file, "r")
             temp = json.load(f)
             f.close()
             for item in temp:
                 oldjson.append(self.sort_scores(item))
         except:
             pass
     if custom == False:
         users = user_list()
         users.load()
     new_users = 0
     changed_users = 0
     for file in cache_files:
         file_name = cache_folder + os.sep + file
         f = open(file_name, "r")
         fjson = json.load(f)
         f.close()
         for entry in fjson["leaderboard"]["data"]:
             for e in entry:
                 e["timestamp"] = os.stat(file_name).st_mtime
                 songjson.append(self.sort_scores(e))
                 platform_id = e["platform_id"]
                 if custom == False:
                     database_name = users.get_name(platform_id)
                     if database_name == None:
                         users.add(e["user"], e["platform_id"],
                                   e["developer"])
                         new_users = new_users + 1
                     else:
                         if database_name != e["user"]:
                             users.change_name(e["user"], e["platform_id"],
                                               e["developer"])
                             changed_users = changed_users + 1
                 else:
                     temp = self.users_to_check
                     for item in temp:
                         found = False
                         if item["platform_id"] == platform_id:
                             found = True
                         if found == False:
                             self.users_to_check.append(users_to_check)
     songjsonsorted = sorted(songjson, key=lambda k: k["rank"])
     with open(song_file, "w") as f:
         json.dump(songjsonsorted, f, sort_keys=True, indent=4)
     shutil.rmtree(cache_folder)
     if custom == False:
         message_logger(
             "LEADERBOARDS API",
             "[SONG \"" + song + "\"] Leaderboard database saved!")
     else:
         message_logger(
             "CUSTOMS LEADERBOARDS",
             "[SONG \"" + song[:-33] + "\"] Leaderboard database saved!")
     if custom == False:
         for e in self.users_to_check:
             database_name = users.get_name(e["platform_id"])
             if database_name == None:
                 users.add(e["user"], e["platform_id"], e["developer"])
                 new_users = new_users + 1
             else:
                 if database_name != e["user"]:
                     users.change_name(e["user"], e["platform_id"],
                                       e["developer"])
                     changed_users = changed_users + 1
         self.users_to_check = []
         users_string = "[SONG \"" + song + "\"]"
         users.save()
         if new_users > 0:
             users_string = users_string + " " + str(
                 new_users) + " new users has been added to the user list."
         if changed_users > 0:
             users_string = users_string + " " + str(
                 changed_users) + " users has changed their name."
         users_string = users_string + " There are " + str(
             len(users.users["users"])) + " users."
     if custom == True:
         return oldjson, songjsonsorted
     else:
         message_logger("LEADERBOARDS API", users_string)
Ejemplo n.º 20
0
 async def do_work():
     await ctx.channel.trigger_typing()
     sender = ctx.message.author
     message_logger("COMMAND",
                    ".compare command requested by " + sender.display_name)
     users = user_list()
     codes = friend_codes()
     users.load()
     codes.load()
     user1 = codes.get_code(sender.id)
     user2 = None
     if user1 == None:
         message_logger("COMMAND",
                        "Help message sent, error with arguments")
         for channel in ctx.guild.channels:
             if str(channel) == "audica-friend-codes":
                 m = await ctx.send(
                     content=
                     "Friend code not found. To link your friend code post it in "
                     + channel.mention + ".")
     else:
         if "<audica_friend_code" in args[0]:
             if " " in args[0]:
                 user2 = args[0].replace("<audica_friend_code ",
                                         "").replace(">", "")
             else:
                 user2 = args[1].replace(">", "")
         elif "steam" in args[0] or "viveport" in args[
                 0] or "oculus" in args[0]:
             user2 = args[0]
         else:
             for user in users.users["users"]:
                 if args[0] == user["name"]:
                     user2 = user["platform_id"]
                     break
             if user2 == None:
                 for user in users.users["users"]:
                     if args[0].lower() == user["name"].lower():
                         user2 = user["platform_id"]
                         break
             if user2 == None:
                 for user in users.users["users"]:
                     if args[0] in user["name"]:
                         user2 = user["platform_id"]
                         break
             if user2 == None:
                 for user in users.users["users"]:
                     if args[0].lower() in user["name"].lower():
                         user2 = user["platform_id"]
                         break
         if user2 == None:
             m = await ctx.send(
                 content=
                 "User to compare with not found. This command needs either a part or the totality of the in-game name, the friend code or the platform id of the player to compare with."
             )
         else:
             try:
                 request = api.post_request(api.global_songs,
                                            [user1, user2])
                 pages = []
                 page = []
                 all_songs = []
                 count = 0
                 ammount = 0
                 for i in request["leaderboard"]:
                     if i["data"] != []:
                         ammount = ammount + 1
                 for p in request["leaderboard"]:
                     if p["data"] != []:
                         page.append(p)
                         count = count + 1
                         if count == 20 or count == 40 or count == ammount:
                             pages.append(page)
                             page = []
                 m = None
                 for page in pages:
                     #print(page)
                     m = await ctx.send(embed=make_compare_embed(
                         page, user1, user2, users.get_name(user1),
                         users.get_name(user2), sender, api))
             except:
                 m = await ctx.send(
                     content="Unexpected error with the command.")
     client.loop.create_task(cooldown_reaction(m, compare_command_cooldown))
Ejemplo n.º 21
0
async def process_play_history_or_log(message):
    for attachment in message.attachments:
        id_list = []
        ids_edited = []
        ids_unknown = []
        if "play_history.json" in str(attachment.url):
            filename = str(attachment.url).split(os.sep)[-1]
            message_logger("CUSTOMS DATABASE",
                           "Downloading " + filename + "...")
            await attachment.save(filename)
            message_logger("CUSTOMS DATABASE", "Download finished!")
            f = open(filename, "r")
            fjson = json.load(f)
            f.close()
            os.remove(filename)
            for item in fjson["songs"]:
                id = item["songID"]
                newest_play = 0
                for history in item["history"]:
                    if history["date"] >= 637085800000000000:
                        if history["date"] > newest_play:
                            newest_play = history["date"]
                id_list.append([id, newest_play])
            id_list_copy = id_list
            new_id_list = []
            for item in id_list:
                newest_play = 0
                id = ""
                for i in id_list_copy:
                    if item[0][:-33] == i[0][:-33]:
                        t = int(str(i[1] - 621357696000000000)[:-7])
                        if t > newest_play:
                            newest_play = t
                            id = i[0]
                new_data = [id, newest_play]
                if new_data not in new_id_list:
                    if new_data[0][:-33] != "":
                        new_id_list.append(new_data)
            id_list = new_id_list
        elif "output_log.txt" in str(attachment.url):
            filename = str(attachment.url).split(os.sep)[-1]
            message_logger("CUSTOMS DATABASE",
                           "Downloading " + filename + "...")
            await attachment.save(filename)
            message_logger("CUSTOMS DATABASE", "Download finished!")
            lines = []
            f = open(filename, "r")
            for line in f:
                lines.append(line)
            f.close()
            os.remove(filename)
            for line in lines:
                if "Requesting leaderboard for " in line:
                    id = line.replace("Requesting leaderboard for ",
                                      "").replace("\n", "")
                    if id[:-33] != "":
                        id_found = False
                        for i in id_list:
                            if id == i[0]:
                                id_found = True
                                break
                        if id_found == False:
                            id_list.append([id, time.time()])
        if id_list != []:
            unknown_ids = []
            database = customs_database()
            database.load()
            unknown_database = unknown_leaderboard_ids()
            unknown_database.load()
            for id in id_list:
                song_found = False
                for song in database.song_list:
                    song_id = song["filename"].replace(".audica", "")
                    leaderboard_id = song["leaderboard_id"]
                    if song_id == id[0][:-33]:
                        song_found = True
                        if leaderboard_id == "":
                            database.edit_leaderboard_id(
                                song["song_id"], id[0])
                            ids_edited.append(id[0])
                        break
                if song_found == False:
                    id_found = False
                    for item in unknown_database.leaderboard_ids:
                        if item["leaderboard_id"] == id[0]:
                            id_found = True
                            break
                    if id_found == False:
                        unknown_database.add(id[0], id[1])
                        ids_unknown.append(id[0])
            database.save()
            unknown_database.save()
        message_string = ""
        if ids_edited != []:
            message_string = "Songs that needed an ID from the file provided:\n\n"
            for item in ids_edited:
                message_string = message_string + item + "\n"
            message_string = message_string + "\n"
        if ids_unknown != []:
            message_string = message_string + "IDs that are unknown (songs not in database) that were saved for future use:\n\n"
            for item in ids_unknown:
                message_string = message_string + item + "\n"
        if message_string != "":
            await message.channel.send(content=message_string)
        else:
            if "play_history.json" in str(attachment.url):
                await message.channel.send(
                    content="This file does not contain new IDs.")
            if "output_log.txt" in str(attachment.url):
                await message.channel.send(
                    content="This file does not contain new IDs.")
Ejemplo n.º 22
0
 async def do_work():
     if str(ctx.message.content) == ".top20":
         await ctx.channel.trigger_typing()
         sender = ctx.message.author
         message_logger(
             "COMMAND",
             ".top20 command requested by " + sender.display_name)
         try:
             song = "global"
             f = open(api.leaderboards_cache_folder + os.sep + song +
                      "top20.json")
             fjson = json.load(f)
             f.close()
             m = await ctx.send(
                 embed=make_leaderboards_embed(fjson,
                                               sender,
                                               song,
                                               "all",
                                               top20=True,
                                               Global=True,
                                               ost=api.global_songs))
             message_logger("COMMAND", "Search successful. songid=" + song)
             client.loop.create_task(
                 cooldown_reaction(m, leaderboards_command_cooldown))
         except Exception as e:
             print(e)
             message_logger("COMMAND",
                            "Help message sent, error with arguments")
             #client.loop.create_task(cooldown_reaction(m, leaderboards_command_cooldown))
     else:
         await ctx.channel.trigger_typing()
         sender = ctx.message.author
         message_logger(
             "COMMAND",
             ".top20 command requested by " + sender.display_name)
         try:
             song = str(ctx.message.content).split(" ", 1)[1]
             files = [
                 f for f in glob.glob(api.leaderboards_cache_folder +
                                      os.sep + "**/*.json",
                                      recursive=True)
             ]
             found = False
             for f in files:
                 if song.lower() == f.lower().split(os.sep)[-1:][0][:-10]:
                     found = True
                     song = f.split(os.sep)[-1:][0][:-10]
                     break
             if found == False:
                 for f in files:
                     if song.lower() in f.lower():
                         song = f.split(os.sep)[-1:][0][:-10]
                         break
             f = open(api.leaderboards_cache_folder + os.sep + song +
                      "top20.json")
             fjson = json.load(f)
             f.close()
             m = await ctx.send(embed=make_leaderboards_embed(
                 fjson, sender, song, "all", top20=True))
             message_logger("COMMAND", "Search successful. songid=" + song)
             client.loop.create_task(
                 cooldown_reaction(m, leaderboards_command_cooldown))
         except Exception as e:
             print(e)
             message_logger("COMMAND",
                            "Help message sent, error with arguments")
Ejemplo n.º 23
0
async def on_ready():
    global running
    message_logger("CUSTOMS LEADERBOARDS", "Connected to Discord.")
    if running == False:
        message_logger("CUSTOMS LEADERBOARDS", "Starting the loop...")
        asyncio.ensure_future(customs_leaderboards_update())