コード例 #1
0
ファイル: server.py プロジェクト: masternovab/Rpgstuff.py
    async def hub(ctx: HTTPRequestContext):
        token = ctx.request.args.get("token")
        if not token:
            return redirect("/register?" + urlencode({"redirect": ctx.request.url}))

        api_resp = await server.session.get("https://discordapp.com/api/users/@me",
                                            headers={
                                                "Authorization": f"Bearer {token}",
                                            })
        js = await api_resp.json()
        if "code" in js:
            return Response(js["message"], status=js["code"])
        resp = await server.get_userdata(js['id'])
        guilds = await (await server.session.get("https://discordapp.com/api/users/@me/guilds",
                                                 headers={
                                                     "Authorization": f"Bearer {token}",
                                                 })).json()

        fguilds = filter(lambda x: x["id"] in resp, guilds)
        servers = "\n".join(f"""
            <button>
                <a href="/guilds?guild_id={guild["id"]}&token={token}">
                    <img src="https://cdn.discordapp.com/icons/{guild["id"]}/{guild["icon"]}.webp?size=32" />
                    {guild["name"]}
                </a>
            </button>
            <br />""" for guild in fguilds)

        return as_html(server.hub_html.format(token=token, servers=servers))
コード例 #2
0
async def index(ctx):
    """Display the homepage of the website."""
    try:
        file_directory = 'templates/' + settings['pages']['index']
    except:
        file_directory = 'templates/index.html'

    with open(file_directory) as file:
        content = file.read()

        content = content.replace('{{AMOUNT}}', str(len(files)))
        content = content.replace('{{NAME}}', settings['meta']['name'])
        content = content.replace('{{DESCRIPTION}}',
                                  settings['meta']['description'])
        content = content.replace('{{TYPE}}', settings['meta']['type'])
        content = content.replace('{{TYPE-PLURAL}}',
                                  settings['meta']['plural'])
        content = content.replace('{{SITEURL}}', settings['meta']['siteurl'])
        content = content.replace('{{ENDPOINT-MAIN}}',
                                  settings['endpoints']['main']['name'])
        content = content.replace('{{ENDPOINT-JSON}}',
                                  settings['endpoints']['json']['name'])
        content = content.replace('{{ENDPOINT-RANDOM}}',
                                  settings['endpoints']['random']['name'])

        return util.as_html(content)
コード例 #3
0
async def tweet(ctx):
    """Host the API in which you can get random birbs from."""
    if not settings['endpoints']['main']['enabled']:
        return

    url = randint(0, len(files) - 1)

    header = {'Content-Type': 'text/plain'}

    return util.as_html("%s" % files[url])
コード例 #4
0
ファイル: app.py プロジェクト: hyphn/links
async def index(ctx):
    """Display the homepage of the website."""
    with open("templates/index.html") as file:
        readfile = file.read()

        database = list(r.table(tbname).run(conn))

        totalchars = 0
        totaluses = 0

        linkstable = "<table>\n<thead>\n<th>Original</th>\n<th>Date</th>\n<th>Link</th>\n<th>Uses</th>\n</thead>\n<tbody>\n"

        for value in database:
            totalchars = totalchars + \
                int(len(value['redirect_url']) - len(value['id']))

            try:
                totaluses = totaluses + value['count']
            except:
                pass

            linkstable = linkstable + "<tr>"
            linkstable = linkstable + "<td><a href=\"" + \
                value['redirect_url'] + "\">" + \
                value['redirect_url'] + "</a></td>"

            linkstable = linkstable + "<td>" + \
                time.strftime('%B %-d, %Y',
                              time.localtime(value['epoch'])) + "</td>"

            linkstable = linkstable + "<td><a href=\"" + siteurl + \
                value['id'] + "\">" + siteurl + "/" + \
                value['id'] + "</a></td>"

            try:
                linkstable = linkstable + "<td>" + \
                    str(value['count']) + "</td>"
            except:
                linkstable = linkstable + "<td>0</td>"

            linkstable = linkstable + "</tr>"

        linkstable = linkstable + "\n</tbody>"
        linkstable = linkstable + "\n</table>"

        readfile = readfile.replace("{ URLS_SHORTENED }", str(len(database)))
        readfile = readfile.replace("{ CHARACTERS }", str(totalchars))
        readfile = readfile.replace("{ TOTAL_USES }", str(totaluses))
        readfile = readfile.replace(
            "{ TOTAL_CHAR_SAVED }", str(totalchars * totaluses))
        readfile = readfile.replace("{ TABLE }", linkstable)

        return util.as_html(readfile)
コード例 #5
0
 async def index(ctx: HTTPRequestContext):
     with open("index.html") as f:
         return as_html(f.read())
コード例 #6
0
ファイル: server.py プロジェクト: masternovab/Rpgstuff.py
 async def register(ctx: HTTPRequestContext):  # Post form to complete registration, GET to see register page
     return as_html(server.register_html)
コード例 #7
0
ファイル: server.py プロジェクト: masternovab/Rpgstuff.py
    async def guilds(ctx: HTTPRequestContext):
        token = ctx.request.args.get("token")
        guild_id = ctx.request.args.get("guild_id")
        if not (token and guild_id):
            return redirect("/register")

        if not guild_id.isdigit():
            return Response(status=404)
        guild_id = int(guild_id)

        medata = await (await server.session.get("https://discordapp.com/api/users/@me",
                                                 headers={
                                                     "Authorization": f"Bearer {token}",
                                                 })).json()

        guilds = await (await server.session.get("https://discordapp.com/api/users/@me/guilds",
                                                 headers={
                                                     "Authorization": f"Bearer {token}",
                                                 })).json()

        guild = server.bot.get_guild(guild_id)

        if "code" in guilds:
            return Response(guilds["message"], status=guilds["code"])

        if str(guild_id) not in (g["id"] for g in guilds):
            return Response(status=403)

        try:
            guild_data = await server.get_serverdata(guild_id)
            user_data = (await server.get_userdata(medata["id"]))[str(guild_id)]
        except:
            import traceback
            traceback.print_exc()
            return Response("oof", status=400)

        html = server.guild_html
        start = "Start Money: {}".format(guild_data["start"])
        stats = "Balance: {}\n<br />Level: {}\n<br />Exp: {}".format(user_data["money"], user_data.get("level"),
                                                                     user_data.get("exp"))
        fmap = map(lambda x: f"{x[0]} x{x[1]}", sorted(user_data["items"].items()))
        inventory = "\n".join(fmap)

        req = f"""SELECT (UUID, info->'{guild_id}'->>'money') FROM userdata;"""
        async with server.pool.acquire() as connection:
            resp = await connection.fetch(req)

        users = [(discord.utils.get(guild.members, id=int(x["row"][0])), x["row"][1]) for x in resp if
                 (len(x["row"]) == 2) and (x["row"][1] is not None)]
        users = [x for x in users if x[0]]
        users.sort(key=lambda x: -float(x[1]))

        currency = await server.bot.di.get_currency(guild)
        baltop = "\n".join(f"<li> {y[0]} {y[1]} {currency}</li>" for y in users[:11])
        characters = "\n".join(f"<li>{name}</li>" for name, obj in guild_data["characters"].items() if obj[2] == str(medata["id"]))

        hubbutton = """
            <button>
                <a href="/hub?token={token}">
                    Return to Guilds
                </a>
            </button>
        """.format(token=token)

        html = html.format(
            start_money=start,
            my_stats=stats,
            my_inventory=inventory,
            baltop=baltop,
            my_characters=characters,
            my_guild="Guild: " + user_data["guild"],
            my_box=None,
            salaries=None,
            items=None,
            other_characters=None,
            guilds=None,
            shop=None,
            market=None,
            lotteries=None,
            hubbutton=hubbutton,
            guildname=guild.name,
        )
        return as_html(html, code=200)