aboutsummaryrefslogtreecommitdiff
path: root/compile_api.py
blob: bea1de53cafde360de54f3bc555004569d1715dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import base64
from io import BytesIO
from typing import Optional, List, Union

import aiohttp
from discord import File

EXECUTE_ENDPOINT = "http://rextester.com/rundotnet/api"


def get_parameters(**kwargs):
    return kwargs


class ExecuteResponse(object):

    def __init__(self, warnings: Optional[str], errors: Optional[str], output: str, stats, files):
        self.output: Optional[str] = output
        self.warnings: Optional[str] = warnings
        self.errors: Optional[str] = errors
        self.stats: str = stats
        self.files: Optional[List[str]] = files

    @property
    def discord_files(self) -> List[File]:
        if not self.files:
            return []

        def convert_file(b64, i):
            bytesio = BytesIO()
            bytesio.write(base64.b64decode(b64))
            bytesio.seek(0)
            return File(bytesio, filename=f'output{i}.png')

        return [convert_file(b64, i) for i, b64 in enumerate(self.files)]


def parse_execute_response(response: dict) -> ExecuteResponse:
    warnings = response['Warnings']
    errors = response['Errors']
    output = response['Result']
    stats = response['Stats']
    files = response['Files']
    return ExecuteResponse(warnings, errors, output, stats, files)


async def execute(code: str, language: Union[str, int]) -> ExecuteResponse:
    async with aiohttp.ClientSession() as session:
        response = await session.get(EXECUTE_ENDPOINT, data=get_parameters(
            Program=code,
            LanguageChoice=language,
            Input="",
            CompilerArgs="",
        ))
        return parse_execute_response(await response.json(content_type=None))