예제 #1
0
async def interactions(req: Request):
    body = await req.body()
    sig = req.headers["X-Signature-Ed25519"]
    ts = req.headers["X-Signature-Timestamp"]

    with supressed():
        verified = verify_key(body, sig, ts, PUBKEY)

    if not verified:
        raise HTTPException(400)

    data = await req.json()

    if data["type"] == InteractionType.PING:
        return {"type": InteractionResponseType.PONG}

    print(data)
    await http.init()

    name = data["data"]["name"]
    if name in handlers:
        try:
            return await handlers[name].call(data)
        except:
            return respond_ephemeral(
                f"An error occurred while processing the command:\n```py\n{format_exc(1900)}```"
            )
    return respond_ephemeral("This command has not yet been implemented.")
예제 #2
0
    async def __recv(self, req: Request):
        body = await req.body()

        sig = req.headers["X-Signature-Ed25519"]
        ts = req.headers["X-Signature-Timestamp"]

        if not verify_key(body, sig, ts, self.pubkey):
            raise HTTPException(400)

        data = await req.json()
        context = Context(data)
        args = self.parse_data(context.data)

        name = context.name
        if name in self.commands:
            cog, cmd = self.commands[name]

            result = await cmd(cog, context, *args)
            if isinstance(result, JSONResponse):
                return result

            raise Exception(
                "Command responses must be valid JSONResponse objects.")

        raise HTTPException(404, "Command not found.")
예제 #3
0
    def _verify_request(self):
        signature = request.headers.get("X-Signature-Ed25519")
        timestamp = request.headers.get("X-Signature-Timestamp")

        if signature is None or timestamp is None:
            return False

        return verify_key(request.data, signature, timestamp, self._public_key)
    def authorize(self, event: Dict) -> (AuthorizationResult, LambdaResponse):
        body = event['body'].encode()
        headers = event['headers']
        signature = headers['x-signature-ed25519']
        timestamp = headers['x-signature-timestamp']

        result = discord_interactions.verify_key(
            body, signature, timestamp, os.environ.get('DISCORD_PUBLIC_KEY'))
        if result:
            return AuthorizationResult.PASS, None
        else:
            return AuthorizationResult.FAIL, LambdaResponse.unauthorized(
                "could not verify authorization")
예제 #5
0
        def wrapper(*args, **kwargs):
            # Verify request
            signature = request.headers.get("X-Signature-Ed25519")
            timestamp = request.headers.get("X-Signature-Timestamp")

            if (signature is None or timestamp is None or not verify_key(
                    request.data, signature, timestamp, client_public_key)):
                return "Bad request signature", 401

            # Automatically respond to pings
            if request.json and request.json.get(
                    "type") == InteractionType.PING:
                return jsonify({"type": InteractionCallbackType.PONG})

            # Pass through
            return f(*args, **kwargs)
예제 #6
0
def handler(request):
    # Verify request
    signature = request.headers.get("X-Signature-Ed25519")
    timestamp = request.headers.get("X-Signature-Timestamp")
    if (
        signature is None
        or timestamp is None
        or not verify_key(request.data, signature, timestamp, PUBLIC_KEY)
    ):
        return "Bad request signature", 401

    # Automatically respond to pings
    if request.json and request.json.get("type") == InteractionType.PING:
        return jsonify({"type": InteractionResponseType.PONG})

    # Pass through
    if request.json["type"] == InteractionType.APPLICATION_COMMAND:
        if request.json["data"]["name"] == "color":
            return jsonify(color.main(request.json))
예제 #7
0
def inner_handler(event, context):
    data = event.get('body', '')
    encoded = event.get('isBase64Encoded', False)

    if not encoded:
        data = data.encode('utf-8')
    else:
        data = base64.b64decode(data)

    signature = event['headers'].get('x-signature-ed25519')
    timestamp = event['headers'].get('x-signature-timestamp')

    if not (signature and timestamp and discord_interactions.verify_key(
            data, signature, timestamp, PUBLIC_KEY)):
        return Response(401, {'error': 'Request signature invalid.'})

    interaction = json.loads(data)

    if interaction['type'] == discord_interactions.InteractionType.PING:
        return Response(
            200, {'type': discord_interactions.InteractionResponseType.PONG})

    guild_id = interaction['guild_id']
    channel_id = interaction['channel_id']

    if channel_id not in ALLOWED_CHANNELS.get(guild_id, []):
        channel_ids = ALLOWED_CHANNELS.get(guild_id)
        mentions = ' '.join(f'<#{x}>' for x in channel_ids) or 'other servers'

        data = {
            'type': discord_interactions.InteractionResponseType.
            CHANNEL_MESSAGE_WITH_SOURCE,
            'data': {
                'content': f'This command can only be used in {mentions}!',
                'flags':
                discord_interactions.InteractionResponseFlags.EPHEMERAL,
            },
        }

        return Response(200, data)

    data = {
        'type': discord_interactions.InteractionResponseType.
        CHANNEL_MESSAGE_WITH_SOURCE,
        'data': {
            'content': 'Request accepted. Blurplefying...'
        },
    }
    send_response(interaction, data=data, followup=False)

    try:
        user = interaction['member']['user']
        avatar = user['avatar']
        user_id = user['id']
        url = None

        if interaction['data']['options'][0]['name'] == 'classic':
            method = '--blurplefy'
        else:
            method = '--filter'

        variations = []
        if 'options' in interaction['data']['options'][0]:
            for option in interaction['data']['options'][0]['options']:
                if option['name'] == 'url':
                    url = option['value']
                    continue

                to_add = option['value'].split()
                for v in to_add:
                    variations.append(v)

        if url is None:
            ext = 'gif' if avatar.startswith('a_') else 'png'
            url = f'https://cdn.discordapp.com/avatars/{user_id}/{avatar}.{ext}?size=512'

        try:
            resp = requests.get(url, stream=True)
        except requests.exceptions.MissingSchema:
            data = {
                'content':
                f'The supplied URL was invalid <@!{user_id}>! {SAD_EMOJI}'
            }
            send_response(interaction, data=data, followup=True)
            return

        if resp.status_code != 200:
            data = {
                'content':
                f'I couldn\'t download your image <@!{user_id}>! {SAD_EMOJI}'
            }
            send_response(interaction, data=data, followup=True)
            return

        # if int(resp.headers.get('content-length', '0')) > 1024 ** 2 * 8:
        #     data = {'content': f'Your image is too large (> 8MiB) <@!{user_id}>! {SAD_EMOJI}'}
        #     send_response(interaction, data=data, followup=True)
        #     return

        # try:
        data = {'content': f'Your requested image is ready <@!{user_id}>!'}
        image = Image(
            *magic.convert_image(resp.content, 'light', method, variations))
        # except Exception:
        #     image = None
        #     data = {'content': f'I was unable to blurplefy your image <@!{user_id}>! {SAD_EMOJI}'}
        resp = send_response(interaction,
                             data=data,
                             image=image,
                             followup=True)

        if 400 <= resp.status_code <= 599:
            data = {
                'content':
                f'I couldn\'t upload your finished image <@!{user_id}>! {SAD_EMOJI}'
            }
            send_response(interaction, data=data, followup=True)
    except Exception:
        data = {'content': traceback.format_exc()}
        send_response(interaction, data=data, followup=True)
예제 #8
0
 def request_is_valid(self, request):
     signature = request.headers.get('X-Signature-Ed25519')
     timestamp = request.headers.get('X-Signature-Timestamp')
     if signature and timestamp and verify_key(request.body, signature, timestamp, PUBLIC_KEY):
         return True
     return False