예제 #1
0
파일: utils.py 프로젝트: xZwop/PCBOT
def get_member(client: discord.Client, member_id: str):
    """ Get a member from the specified ID. """
    for member in client.get_all_members():
        if member.id == member_id:
            return member

    return None
예제 #2
0
def get_member_count(client: discord.Client):
    member_count = 0

    for user in client.get_all_members():
        if not user.bot:
            member_count += 1

    return member_count
예제 #3
0
def on_ready(client: discord.Client):
    while not client.is_closed:
        try:
            yield from asyncio.sleep(update_interval)

            # Go through all set channels (if they're online on discord) and update their status
            for member_id, channel in twitch_channels.data["channels"].items():
                member = discord.utils.find(
                    lambda m: m.status is not discord.Status.offline and m.id
                    == member_id, client.get_all_members())

                if member:
                    with aiohttp.ClientSession() as session:
                        response = yield from session.get(twitch_api +
                                                          "/streams/" +
                                                          channel)

                        if response:
                            json = yield from response.json(
                            ) if response.status == 200 else {}
                        else:
                            json = {}

                    stream = json.get("stream")

                    if member_id in live_channels:
                        if not stream:
                            live_channels.pop(member_id)
                    else:
                        if stream:
                            live_channels[member_id] = stream

                            # Tell every mutual channel between the streamer and the bot that streamer started streaming
                            for server in client.servers:
                                if member in server.members:
                                    m = "{0} went live at {1[channel][url]}.\n" \
                                        "**{1[channel][display_name]}**: {1[channel][status]}\n" \
                                        "*Playing {1[game]}*".format(member.mention, stream)
                                    asyncio. async (client.send_message(
                                        server, m))

                                    preview = yield from download_file(
                                        stream["preview"]["medium"])
                                    yield from client.send_file(
                                        server,
                                        preview,
                                        filename="preview.jpg")

                    # Wait a second before sending a new server request
                    yield from asyncio.sleep(1)

        except:
            print_exc()
예제 #4
0
def get_single_player(bot: discord.Client, player_id: str):
    player = None
    username = {str(x.id): str(x.name) for x in bot.get_all_members() if str(x.id) == str(player_id)}.get(str(player_id), str(player_id))

    conn = pymysql.connect(host=secrets.DBAddress, port=secrets.DBPort, user=secrets.DBName,
                           password=secrets.DBPassword, database="rpg", charset="utf8", use_unicode=True)
    c = conn.cursor()
    try:
        # Get basic playerinfo
        c.execute("SELECT * FROM characters WHERE characterid=%s", (player_id,))
        _, exp, health, maxhealth, damage, weaponskill, critical = c.fetchone()
        c.execute("SELECT * FROM players WHERE playerid=%s", (player_id,))
        _, money, role, levelups, bosstier, extratime = c.fetchone()
        player = RPGPlayer(userid=player_id, pets=[], username=username, role=role, health=health,
                           maxhealth=maxhealth, damage=damage,
                           ws=weaponskill, critical=critical, exp=exp, levelups=levelups, money=money,
                           bosstier=bosstier, extratime=extratime)

        # Get players current action
        c.execute("SELECT * FROM busy WHERE playerid=%s", (player_id,))
        _, desc, time, channel, kingtime = c.fetchone()
        player.set_busy(desc, time, channel)
        player.kingtimer = kingtime

        # Get players items
        c.execute("SELECT * FROM items WHERE playerid=%s", (player_id,))
        for _, item_id, item_type, name in c.fetchall():
            if item_type in [TYPE_WEAPON, TYPE_ARMOR]:
                c.execute("SELECT * from equipment WHERE equipmentid=%s", (item_id,))
                if item_type == TYPE_WEAPON:
                    weaponid, cost, element, dam, ws, cr = c.fetchone()
                    player.weapon = rpgw.RPGWeapon(weaponid=weaponid, name=name, cost=cost, element=element, damage=dam,
                                                   weaponskill=ws,
                                                   critical=cr)
                if item_type == TYPE_ARMOR:
                    armorid, cost, element, mh, hr, bonusmoney = c.fetchone()
                    player.armor = rpga.RPGArmor(armorid=armorid, name=name, cost=cost, element=element, maxhealth=mh,
                                                 healthregen=hr, money=bonusmoney)
            if item_type == TYPE_PET:
                c.execute("SELECT * FROM characters WHERE characterid=%s", (item_id,))
                petid, petexp, hp, mh, dam, ws, cr = c.fetchone()
                player.add_pet(
                    RPGPet(petid=petid, name=name, exp=petexp, health=hp, maxhealth=mh, damage=dam, weaponskill=ws,
                           critical=cr))
    finally:
        conn.commit()
        conn.close()
        return player if player else RPGPlayer(player_id, player_id)
예제 #5
0
def get_member(bot: discord.Client,
               user_id,
               server: discord.Server = None,
               server_list=None) -> discord.Member:
    """Returns a member matching the id

    If no server_id is specified, the first member matching the id will be returned, meaning that the server he
    belongs to will be unknown, so member-only functions may be inaccurate.
    User functions remain the same, regardless of server"""
    if server_list is not None and len(server_list) > 0:
        members = [m for ml in [s.members for s in server_list] for m in ml]
        return discord.utils.find(lambda m: m.id == str(user_id), members)
    if server is not None:
        return server.get_member(str(user_id))
    else:
        return discord.utils.get(bot.get_all_members(), id=str(user_id))
예제 #6
0
파일: osu.py 프로젝트: xZwop/PCBOT
def update_user_data(client: discord.Client):
    """ Go through all registered members playing osu!, and update their data. """
    global osu_tracking

    # Go through each member playing and give them an "old" and a "new" subsection
    # for their previous and latest user data
    for member_id, profile in osu_config.data["profiles"].items():
        def check_playing(m):
            """ Check if a member has "osu!" in their Game name. """
            # The member doesn't even match
            if not m.id == member_id:
                return False

            # See if the member is playing
            if m.game and "osu!" in m.game.name:
                return True

            return False

        member = discord.utils.find(check_playing, client.get_all_members())

        # If the member is not playing anymore, remove them from the tracking data
        if not member:
            if member_id in osu_tracking:
                del osu_tracking[member_id]

            continue

        mode = get_mode(member_id).value
        user_data = yield from api.get_user(u=profile, type="id", m=mode)

        # Just in case something goes wrong, we skip this member (these things are usually one-time occurances)
        if user_data is None:
            continue

        # User is already tracked
        if member_id in osu_tracking:
            # Move the "new" data into the "old" data of this user
            osu_tracking[member_id]["old"] = osu_tracking[member_id]["new"]
        else:
            # If this is the first time, update the user's list of scores for later
            scores = yield from api.get_user_best(u=profile, type="id", limit=score_request_limit, m=mode)
            osu_tracking[member_id] = dict(member=member, scores=scores)

        # Update the "new" data
        osu_tracking[member_id]["new"] = user_data
예제 #7
0
파일: twitch.py 프로젝트: EdwardBetts/PCBOT
def on_ready(client: discord.Client):
    while not client.is_closed:
        try:
            yield from asyncio.sleep(update_interval)

            # Go through all set channels (if they're online on discord) and update their status
            for member_id, channel in twitch_channels.data["channels"].items():
                member = discord.utils.find(lambda m: m.status is not discord.Status.offline and m.id == member_id,
                                            client.get_all_members())

                if member:
                    with aiohttp.ClientSession() as session:
                        response = yield from session.get(twitch_api + "/streams/" + channel)

                        if response:
                            json = yield from response.json() if response.status == 200 else {}
                        else:
                            json = {}

                    stream = json.get("stream")

                    if member_id in live_channels:
                        if not stream:
                            live_channels.pop(member_id)
                    else:
                        if stream:
                            live_channels[member_id] = stream

                            # Tell every mutual channel between the streamer and the bot that streamer started streaming
                            for server in client.servers:
                                if member in server.members:
                                    m = "{0} went live at {1[channel][url]}.\n" \
                                        "**{1[channel][display_name]}**: {1[channel][status]}\n" \
                                        "*Playing {1[game]}*".format(member.mention, stream)
                                    asyncio.async(client.send_message(server, m))

                                    preview = yield from download_file(stream["preview"]["medium"])
                                    yield from client.send_file(server, preview, filename="preview.jpg")

                    # Wait a second before sending a new server request
                    yield from asyncio.sleep(1)

        except:
            print_exc()
예제 #8
0
def get_member_by_name(bot: discord.Client,
                       name: str,
                       server: discord.Server = None,
                       server_list=None) -> discord.Member:
    """Returns a member matching the name

    If no server is specified, the first member matching the id will be returned, meaning that the server he
    belongs to will be unknown, so member-only functions may be inaccurate.
    If server_list is defined, only members within that server list will be searched for
    User functions remain the same, regardless of server"""
    if server_list is not None and len(server_list) > 0:
        members = [m for ml in [s.members for s in server_list] for m in ml]
        return discord.utils.find(
            lambda m: m.display_name.lower() == name.lower(), members)
    if server is not None:
        return discord.utils.find(
            lambda m: m.display_name.lower() == name.lower(), server.members)
    else:
        return discord.utils.find(
            lambda m: m.display_name.lower() == name.lower(),
            bot.get_all_members())
예제 #9
0
def id_to_member(member_id: str, bot: discord.Client):
    return discord.utils.find(lambda m: m.id == member_id, bot.get_all_members())
예제 #10
0
파일: osu.py 프로젝트: EdwardBetts/PCBOT
def on_ready(client: discord.Client):
    global osu_tracking

    if osu.data["key"] == "change to your api key":
        logging.warning(
            "osu! functionality is unavailable until an API key is provided")

    sent_requests = 0
    updated = 0

    while not client.is_closed:
        try:
            yield from asyncio.sleep(update_interval)

            # Go through all set channels playing osu! and update their status
            for member_id, profile in osu.data["profiles"].items():

                def check_playing(m):
                    if m.id == member_id and m.game:
                        if m.game.name.startswith("osu!"):
                            return True

                    return False

                member = discord.utils.find(check_playing,
                                            client.get_all_members())

                if member:
                    sent_requests += 1

                    params = {
                        "k": osu.data["key"],
                        "u": profile,
                        "type": "id",
                        "limit": request_limit
                    }

                    with aiohttp.ClientSession() as session:
                        response = yield from session.get(osu_api +
                                                          "get_user_best",
                                                          params=params)

                        scores = yield from response.json(
                        ) if response.status == 200 else []

                    if scores:
                        # Go through all scores and see if they've already been tracked
                        if member_id in osu_tracking:
                            new_score = None

                            for score in scores:
                                if score not in osu_tracking[member_id]:
                                    new_score = score

                            # Tell all mutual servers if this user set a nice play
                            if new_score:
                                for server in client.servers:
                                    if member in server.members:
                                        # Find some beatmap information
                                        beatmap_search = yield from get_beatmaps(
                                            b=int(new_score["beatmap_id"]))
                                        beatmap = get_beatmap(beatmap_search)

                                        yield from client.send_message(
                                            server,
                                            format_new_score(member=member,
                                                             score=new_score,
                                                             beatmap=beatmap))

                        osu_tracking[member_id] = list(scores)

            # Send info on how many requests were sent the last 30 minutes (60 loops)
            updated += 1

            if updated % updates_per_log() == 0:
                logging.info(
                    "Requested osu! scores {} times in {} minutes.".format(
                        sent_requests, logging_interval))
                sent_requests = 0

        except:
            print_exc()
예제 #11
0
def id_to_member(member_id: str, bot: discord.Client):
    return discord.utils.find(lambda m: m.id == member_id,
                              bot.get_all_members())
예제 #12
0
def get_user_servers(bot: discord.Client, user_id):
    """Returns a list of the user's shared servers with the bot"""
    return [m.server for m in bot.get_all_members() if m.id == str(user_id)]
예제 #13
0
파일: osu.py 프로젝트: EdwardBetts/PCBOT
def on_ready(client: discord.Client):
    global osu_tracking

    if osu.data["key"] == "change to your api key":
        logging.warning("osu! functionality is unavailable until an API key is provided")

    sent_requests = 0
    updated = 0

    while not client.is_closed:
        try:
            yield from asyncio.sleep(update_interval)

            # Go through all set channels playing osu! and update their status
            for member_id, profile in osu.data["profiles"].items():
                def check_playing(m):
                    if m.id == member_id and m.game:
                        if m.game.name.startswith("osu!"):
                            return True

                    return False

                member = discord.utils.find(check_playing, client.get_all_members())

                if member:
                    sent_requests += 1

                    params = {
                        "k": osu.data["key"],
                        "u": profile,
                        "type": "id",
                        "limit": request_limit
                    }

                    with aiohttp.ClientSession() as session:
                        response = yield from session.get(osu_api + "get_user_best", params=params)

                        scores = yield from response.json() if response.status == 200 else []

                    if scores:
                        # Go through all scores and see if they've already been tracked
                        if member_id in osu_tracking:
                            new_score = None

                            for score in scores:
                                if score not in osu_tracking[member_id]:
                                    new_score = score

                            # Tell all mutual servers if this user set a nice play
                            if new_score:
                                for server in client.servers:
                                    if member in server.members:
                                        # Find some beatmap information
                                        beatmap_search = yield from get_beatmaps(b=int(new_score["beatmap_id"]))
                                        beatmap = get_beatmap(beatmap_search)

                                        yield from client.send_message(
                                            server,
                                            format_new_score(member=member, score=new_score, beatmap=beatmap)
                                        )

                        osu_tracking[member_id] = list(scores)

            # Send info on how many requests were sent the last 30 minutes (60 loops)
            updated += 1

            if updated % updates_per_log() == 0:
                logging.info("Requested osu! scores {} times in {} minutes.".format(sent_requests, logging_interval))
                sent_requests = 0

        except:
            print_exc()