示例#1
0
文件: funct.py 项目: yuuuuue/Saya
async def recent(message):
    code = await check_id(message.author.id)
    if not code:
        await message.channel.send(
            "> Erreur: Aucun code Arcaea n'est lié a ce compte Discord (*!register*)"
        )
        return

    api_ = AsyncApi(user_code=code)
    data = await api_.songs()
    songlist = data[0]
    prfl = data[1]
    recent = prfl["recent_score"][0]

    if recent["difficulty"] == 3:
        cover_url = cover + "3_" + recent["song_id"] + ".jpg"
    else:
        cover_url = cover + recent["song_id"] + ".jpg"
    msg_emb = discord.Embed(title="Last play",
                            type="rich",
                            color=discord.Color.dark_teal())
    msg_emb.set_thumbnail(url=cover_url)
    msg_emb.set_author(name=f'{prfl["name"]}', icon_url=get_partner_icon(prfl))
    msg_emb.add_field(
        name=
        f'**{songlist[recent["song_id"]]["en"]}\n<{diff[recent["difficulty"]]} '
        f'{get_diff(recent["constant"])}\>**',
        value=
        f'> **{format_score(recent["score"])}** [{clr[recent["best_clear_type"]]}] '
        f'(Rating: {round(recent["rating"], 3)})\n'
        f'> Pure: {recent["perfect_count"]} ({recent["shiny_perfect_count"]}) \n'
        f'> Far: {recent["near_count"]} |  Lost: {recent["miss_count"]}\n'
        f'> Date: {format_time(recent["time_played"]).split(" - ")[0]}')
    await message.channel.send(embed=msg_emb)
示例#2
0
文件: funct.py 项目: yuuuuue/Saya
async def profile(message):
    code = await check_id(message.author.id)
    if not code:
        await message.channel.send(
            "> Erreur: Aucun code Arcaea n'est lié a ce compte Discord (*!register*)"
        )
        return

    api_ = AsyncApi(user_code=code)
    data = await api_.scores()
    prfl = data[1]

    rating = "{0:04d}".format(prfl["rating"])[:2] + "." + "{0:04d}".format(
        prfl["rating"])[2:] + " PTT"

    if rating == "-0.01 PTT":
        rating = "*Hidden*"

    msg_emb = discord.Embed(title="Profile",
                            type="rich",
                            color=discord.Color.dark_teal())
    msg_emb.set_thumbnail(url=get_partner_icon(prfl))
    msg_emb.add_field(
        name=f'**{prfl["name"]}\'s profile**',
        value=f'> Rating: **{rating}**\n'
        f'> Favchar: **{partners_names[prfl["character"]]}**\n'
        f'> Last play: **{format_time(prfl["recent_score"][0]["time_played"])}**\n'
        f'> Join date: **{format_time(prfl["join_date"])}**\n'
        f'> Code: **{format_code(code)}**')
    await message.channel.send(embed=msg_emb)
示例#3
0
文件: funct.py 项目: yuuuuue/Saya
async def progression(message):
    code = await check_id(message.author.id)
    if not code:
        await message.channel.send(
            "> Erreur: Aucun code Arcaea n'est lié a ce compte Discord (*!register*)"
        )
        return

    api_ = AsyncApi(user_code=code)
    data = await api_.scores()
    prfl = data[1]
    recs = prfl['rating_records']

    dates = [datetime.strptime(rec[0], '%y%m%d').date() for rec in recs]
    ptts = [float(rec[1]) / 100 for rec in recs]

    plt.rc('axes', edgecolor='white')
    fig, ax = plt.subplots()
    fig.patch.set_facecolor('#36393F')
    ax.set_facecolor('#36393F')
    ax.set_xlabel("Time")
    ax.set_ylabel("PTT")
    ax.set_title(f"{message.author.name}'s PTT progression")
    ax.plot_date(dates, ptts, fmt='-', color='#439EBA')
    fig.autofmt_xdate()
    b = io.BytesIO()
    plt.savefig(b, format='png')
    plt.close()
    b.seek(0)
    file = discord.File(b, f"progression.png")
    await message.channel.send(file=file)
示例#4
0
def test_async():
    api_ = AsyncApi('000000001')

    async def _():
        data = await api_.userinfo()
        print("user info :", data)
    asyncio.get_event_loop().run_until_complete(_())
示例#5
0
文件: funct.py 项目: yuuuuue/Saya
async def best(message):
    code = await check_id(message.author.id)
    nb_scores = 30
    if not code:
        await message.channel.send(
            "> Erreur: Aucun code Arcaea n'est lié a ce compte Discord (*!register*)"
        )
        return

    if len(message.content.split(" ")) > 1:
        if message.content.split(" ")[1].isdigit():
            if 1 <= int(message.content.split(" ")[1]) <= 30:
                nb_scores = int(message.content.split(" ")[1])

    api_ = AsyncApi(user_code=code)
    data = await api_.scores()
    songlist = data[0]
    prfl = data[1]
    ls_top = []

    for elm in data[2:]:
        ls_top.append(elm)

    ls_top = sorted(ls_top, key=itemgetter("rating"), reverse=True)[0:30]

    msg_emb = discord.Embed(title=f'Top {nb_scores}',
                            type="rich",
                            color=discord.Color.dark_teal())
    msg_emb.set_author(name=f'{prfl["name"]}', icon_url=get_partner_icon(prfl))

    if nb_scores == 1:
        if ls_top[0]["difficulty"] == 3:
            cover_url = cover + "3_" + ls_top[0]["song_id"] + ".jpg"
        else:
            cover_url = cover + ls_top[0]["song_id"] + ".jpg"
        msg_emb.set_thumbnail(url=cover_url)

    if nb_scores > len(ls_top):
        nb_scores = len(ls_top)

    for i in range(nb_scores):
        if i == round(nb_scores / 2) and nb_scores > 20:
            await message.channel.send(embed=msg_emb)
            msg_emb = discord.Embed(title="Top 30",
                                    type="rich",
                                    color=discord.Color.dark_teal())
            msg_emb.set_author(name=f'{prfl["name"]}',
                               icon_url=get_partner_icon(prfl))
        msg_emb.add_field(
            name=
            f'**{songlist[ls_top[i]["song_id"]]["en"]}\n<{diff[ls_top[i]["difficulty"]]} '
            f'{get_diff(ls_top[i]["constant"])}\>**',
            value=
            f'> **{format_score(ls_top[i]["score"])}** [{clr[ls_top[i]["best_clear_type"]]}] '
            f'(Rating: {round(ls_top[i]["rating"], 3)})\n'
            f'> Pure: {ls_top[i]["perfect_count"]} ({ls_top[i]["shiny_perfect_count"]}) \n'
            f'> Far: {ls_top[i]["near_count"]} | Lost: {ls_top[i]["miss_count"]}\n'
            f'> Date: {format_time(ls_top[i]["time_played"]).split(" - ")[0]}')
    await message.channel.send(embed=msg_emb)
示例#6
0
文件: funct.py 项目: yuuuuue/Saya
async def ptt_recommendation(message):
    code = await check_id(message.author.id)
    if not code:
        await message.channel.send(
            "> Erreur: Aucun code Arcaea n'est lié a ce compte Discord (*!register*)"
        )
        return

    nb_scores = 5
    if len(message.content.split(" ")) > 1:
        if message.content.split(" ")[1].isdigit():
            if 1 <= int(message.content.split(" ")[1]) <= 20:
                nb_scores = int(message.content.split(" ")[1])

    api_ = AsyncApi(user_code=code)
    data = await api_.scores()
    songlist = data[0]
    prfl = data[1]
    scores = []
    for elm in data[2:]:
        scores.append(elm)

    ptt_rec = get_ptt_recommendation_scores(scores, prfl, nb_scores)

    msg_emb = discord.Embed(title="Recommendation",
                            type="rich",
                            color=discord.Color.dark_teal())
    msg_emb.set_author(name=f'{prfl["name"]}', icon_url=get_partner_icon(prfl))
    msg_emb.set_footer(text="*(Credit: Okami)*")
    for elm in ptt_rec:
        msg_emb.add_field(
            name=
            f'**{songlist[elm["song_id"]]["en"]}\n<{diff[elm["difficulty"]]} '
            f'{get_diff(elm["constant"])}\>**',
            value=
            f'> **{format_score(elm["score"])}** [{clr[elm["best_clear_type"]]}] '
            f'(Rating: {round(elm["rating"], 3)})\n'
            f'> Pure: {elm["perfect_count"]} ({elm["shiny_perfect_count"]}) \n'
            f'> Far: {elm["near_count"]} | Lost: {elm["miss_count"]}\n'
            f'> Date: {format_time(elm["time_played"]).split(" - ")[0]}')
    await message.channel.send(embed=msg_emb)
示例#7
0
async def event(message):
    with open("test.csv", "r", encoding="UTF-8") as f:
        cf = csv.reader(f, delimiter=';')
        dat = []
        for elm in cf:
            dat.append(elm)

    code = await check_id(message.author.id)
    if not code:
        await message.channel.send(
            "> Erreur: Aucun code Arcaea n'est lié a ce compte Discord (*!register*)"
        )
        return

    api_ = AsyncApi(user_code=code)
    data = await api_.songs()
    songlist = data[0]
    prfl = data[1]
    recent = prfl["recent_score"][0]

    mode = dat[0][1]
    song = songlist[recent["song_id"]]["en"]
    dif = diff[recent["difficulty"]]

    if mode == "score":
        res = recent["score"]

    elif mode == "pures":
        res = recent["perfect_count"]

    elif mode == "ppures":
        res = recent["shiny_perfect_count"]

    else:
        await message.channel.send("> ERREUR: Aucun event en cours")
        return

    e_songs = []
    e_players = [elm[1] for elm in dat[2:]]
    for elm in dat[1][3:]:
        if elm.split("|")[0] not in e_songs:
            e_songs.append(elm)

    if f"{song}|{dif}" in e_songs:
        e_ind = e_songs.index(f"{song}|{dif}") + 3
        p_line = e_players.index(str(message.author.id)) + 2
        if dat[p_line][e_ind] != "X":
            if int(dat[p_line][e_ind]) < res:
                dat[p_line][e_ind] = res

                with open('test.csv', 'w', newline='', encoding="UTF-8") as f:
                    cf = csv.writer(f, delimiter=';')
                    for elm in dat:
                        cf.writerow(elm)

                await message.channel.send(
                    f"> INFO: Envoi du score reussi\n"
                    f"> Score de {song} <{dif}> modifié en {res}")

            else:
                await message.channel.send(
                    "> ERREUR: Le score est inferieur au resultat précédent")
                return
        else:
            await message.channel.send(
                "> ERREUR: La difficulté de cette track ne fait pas partie de l'event en cours"
            )
            return
    else:
        await message.channel.send(
            "> ERREUR: La track ne fait pas partie de l'event en cours")
        return
示例#8
0
文件: arc.py 项目: fossabot/Coding
import asyncio
from Arcapi import AsyncApi

# Initialize an API with user code
api_ = AsyncApi(user_code='455704826')

# You can assign the constant range here, or just leave it in a default
asyncio.get_event_loop().run_until_complete(api_.userinfo(start=8, end=12))
示例#9
0
文件: funct.py 项目: yuuuuue/Saya
async def session_generator(message):
    code = await check_id(message.author.id)
    if not code:
        await message.channel.send(
            "> Erreur: Aucun code Arcaea n'est lié a ce compte Discord (*!register*)"
        )
        return

    # Parse parameters
    params = message.content.split(" ")
    if len(params) <= 1 or len(params) % 2 == 0:
        await message.channel.send(
            "> Erreur: Paramètres incorrects, aucune session ne peut être générée (*Exemple : !session 8 4 9 2 9+ 1*)"
        )
        return
    i = 1
    diffs = []
    nb_songs = []
    while i < len(params):
        if not params[i + 1].isdigit():
            await message.channel.send(
                "> Erreur: Le nombre de songs d'une difficulté ne doit contenir que des chiffres (*Exemple : !session 8 4 9 2 9+ 1*)"
            )
            return
        diffs.append(params[i])
        nb_songs.append(int(params[i + 1]))
        i += 2

    api_ = AsyncApi(user_code=code)
    data = await api_.scores()
    songlist = data[0]
    prfl = data[1]
    scores = []
    for elm in data[2:]:
        scores.append(elm)

    # Get PTT Recommendations so they can be used in the algorithm
    ptt_rec = get_ptt_recommendation_scores(scores, prfl, 20)

    session_songs = []
    for i in range(len(diffs)):
        songs_list = sorted(filter(
            lambda score: get_diff(score["constant"]) == diffs[i], scores),
                            key=itemgetter("time_played"),
                            reverse=True)
        if len(songs_list) < nb_songs[i]:
            await message.channel.send(
                f'> Erreur: Impossible de générer {nb_songs[i]} songs de difficulté {diffs[i]} ({len(songs_list)} disponibles)'
            )
            return
        songs_pool = []
        for j in range(len(songs_list)):
            song = songs_list[j]
            is_rec = len(
                list(
                    filter(
                        lambda rec_score: rec_score["song_id"] == song[
                            "song_id"] and rec_score["difficulty"] == song[
                                "difficulty"],
                        ptt_rec)))  # Check if a song is in PTT Recommendations
            songs_pool.extend(repeat(song, j + 1 + is_rec * 2))
        for j in range(nb_songs[i]):
            song = random.choice(songs_pool)
            while len(
                    list(
                        filter(
                            lambda score: score["song_id"] == song["song_id"]
                            and score["difficulty"] == song["difficulty"],
                            session_songs))) > 0:  # Avoid duplicate songs
                song = random.choice(songs_pool)
            session_songs.append(song)
    session_songs = sorted(session_songs,
                           key=itemgetter("constant"),
                           reverse=False)

    msg_emb = discord.Embed(title="Session Generator",
                            type="rich",
                            color=discord.Color.dark_teal())
    msg_emb.set_author(name=f'{prfl["name"]}', icon_url=get_partner_icon(prfl))
    msg_emb.set_footer(text="*(Credit: Okami)*")
    for elm in session_songs:
        msg_emb.add_field(
            name=
            f'**{songlist[elm["song_id"]]["en"]}\n<{diff[elm["difficulty"]]} '
            f'{get_diff(elm["constant"])}\>**',
            value=
            f'> **{format_score(elm["score"])}** [{clr[elm["best_clear_type"]]}] '
            f'(Rating: {round(elm["rating"], 3)})\n'
            f'> Pure: {elm["perfect_count"]} ({elm["shiny_perfect_count"]}) \n'
            f'> Far: {elm["near_count"]} | Lost: {elm["miss_count"]}\n'
            f'> Date: {format_time(elm["time_played"]).split(" - ")[0]}')
    await message.channel.send(embed=msg_emb)
示例#10
0
async def get_api_coroutine():
    global api_, sub_api_, user_code, info_list, recent_po_list

    while True:
        # User 파일 불러오기
        try:
            with open("user.bin", "rb") as f:
                user_data = pickle.load(f)

        except FileNotFoundError:  # 파일이 없으면
            with open("user.bin", "wb+") as f:
                user_data = []
                pickle.dump(user_data, f)

        # user_code 가 파일 내에 없는 경우
        if user_code not in user_data:
            user_data.append(user_code)

        # RL 파일 불러오기
        try:
            with open("recent_list.bin", "rb") as f:
                RL_data = pickle.load(f)

        except FileNotFoundError:  # 파일이 없으면
            with open("recent_list.bin", "wb+") as f:
                RL_data = dict()
                pickle.dump(RL_data, f)

        # 등록되어 있는 유저 수만큼 반복
        for i in range(len(user_data)):

            if user_data[i] not in RL_data:
                RL_data[user_data[i]] = [{} for j in range(0)]

            data = AsyncApi(user_data[i])
            try:
                sub_api_ = await data.constants(start=7, end=12)

            # 없는 user code이거나 타이리츠, 히카리를 입력한 경우는 예외 처리
            except websockets.exceptions.ConnectionClosedError:
                user_data.remove(user_code)
                user_code = "552925754"
                break

            if user_data[i] == "000000001" or user_data[i] == "000000002":
                user_data.remove(user_code)
                user_code = "552925754"
                break

            # 현재 불러온 임시 api_가 user_code의 것이라면
            if user_data[i] == user_code:
                info_list = [{} for i in range(0)]

                api_ = sub_api_
                for j in range(2, len(api_)):
                    for info in api_[j]:
                        info_list.append(get_info(info))

            # 최근 곡 하나를 불러옴
            recent_api_ = get_recent(sub_api_[1].get('recent_score')[0])

            if len(RL_data[user_data[i]]) == 0 or recent_api_ != RL_data[user_data[i]][0]:  # 결과가 update된 경우
                if (len(recent_po_list) < 10 or not (
                        recent_api_.get('potential') <= recent_po_list[9].get('potential') and recent_api_.get(
                        'score') >= 9800000)) or recent_api_.get('health') != -1:
                    # Recent Top 10 기록이 아니고, EX 이상인 경우와 반갈죽 당한 경우는 제외

                    for j in range(len(RL_data[user_data[i]]) - 1, -1, -1):  # recent_list를 뒤로 밈.
                        if j == len(RL_data[user_data[i]]) - 1:
                            RL_data[user_data[i]].append(RL_data[user_data[i]][j])
                        else:
                            RL_data[user_data[i]][j + 1] = RL_data[user_data[i]][j]

                    if len(RL_data[user_data[i]]) == 0:
                        RL_data[user_data[i]].append(recent_api_)
                    else:
                        RL_data[user_data[i]][0] = recent_api_

                    with open("recent_list.bin", "wb") as f:  # RL_data 저장
                        pickle.dump(RL_data, f)

            if user_data[i] == user_code:
                recent_po_list = arrange('potential', RL_data[user_code])  # recent_po_list 정렬

        with open("user.bin", "wb") as f:  # user_data 저장
            pickle.dump(user_data, f)

        await asyncio.sleep(153)
        print(recent_po_list)