예제 #1
0
def _post(url, timeout, **kwargs):
    if timeout is None:
        response = yield from aiohttp.post(url, **kwargs)
    else:
        response = yield from asyncio.wait_for(aiohttp.post(url, **kwargs),
                                               timeout)

    try:
        data = yield from response.json()
    except ValueError:
        text = yield from response.text()
        raise BadHTTPResponse(response.status, text, response)

    if data['ok']:
        return data['result']
    else:
        description, error_code = data['description'], data['error_code']

        # Look for specific error ...
        for e in TelegramError.__subclasses__():
            n = len(e.DESCRIPTION_PATTERNS)
            if any(
                    map(re.search, e.DESCRIPTION_PATTERNS, n * [description],
                        n * [re.IGNORECASE])):
                raise e(description, error_code, data)

        # ... or raise generic error
        raise TelegramError(description, error_code, data)
예제 #2
0
파일: __init__.py 프로젝트: jlbmdm/telepot
    def _sendFile(self, inputfile, filetype, params):
        method = {'photo':    'sendPhoto',
                  'audio':    'sendAudio',
                  'document': 'sendDocument',
                  'sticker':  'sendSticker',
                  'video':    'sendVideo',
                  'voice':    'sendVoice',}[filetype]

        if isinstance(inputfile, io.IOBase):
            files = {filetype: inputfile}
            r = yield from aiohttp.post(
                    self._methodurl(method), 
                    params=self._rectify(params, allow_namedtuple=['reply_markup']), 
                    data=files)

            # `_http_timeout` is not used here because, for some reason, the larger the file, 
            # the longer it takes for the server to respond (after upload is finished). It is hard to say
            # what value `_http_timeout` should be. In the future, maybe I should let user specify.
        else:
            params[filetype] = inputfile
            r = yield from asyncio.wait_for(
                    aiohttp.post(
                        self._methodurl(method), 
                        params=self._rectify(params, allow_namedtuple=['reply_markup'])), 
                    self._http_timeout)

        return (yield from self._parse(r))
예제 #3
0
    async def test_device_CRUD(self):
        async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices') as r:
            self.assertEqual(r.status, 200)
            rst = await r.json()
            self.assertSetEqual(set(rst), {'1', '2', '3'})
        async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/1') as r:
            self.assertEqual(r.status, 200)
            rst = await r.json()
            self.assertDictEqual(rst, mock_data.device1)
        async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/99') as r:
            self.assertEqual(r.status, 404)
            rst = await r.text()
            self.assertEqual(rst, 'device_id not found!')

        async with aiohttp.post('http://127.0.0.1:8080/api/v1/devices',
                                data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.hgetall('HS:DEVICE:4')
            self.assertEqual(rst['name'], '测试集中器4')
            rst = self.redis_client.sismember('SET:DEVICE', 4)
            self.assertTrue(rst)
        async with aiohttp.post('http://127.0.0.1:8080/api/v1/devices',
                                data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 409)
            rst = await r.text()
            self.assertEqual(rst, 'device already exists!')

        mock_data.test_device['name'] = '测试集中器5'
        mock_data.test_device['id'] = 5
        async with aiohttp.put('http://127.0.0.1:8080/api/v1/devices/4',
                               data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.exists('HS:DEVICE:4')
            self.assertFalse(rst)
            rst = self.redis_client.sismember('SET:DEVICE', 4)
            self.assertFalse(rst)
            rst = self.redis_client.hgetall('HS:DEVICE:5')
            self.assertEqual(rst['name'], '测试集中器5')
            rst = self.redis_client.sismember('SET:DEVICE', 5)
            self.assertTrue(rst)
        async with aiohttp.put('http://127.0.0.1:8080/api/v1/devices/99',
                               data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 404)
            rst = await r.text()
            self.assertEqual(rst, 'device_id not found!')

        async with aiohttp.delete(
                'http://127.0.0.1:8080/api/v1/devices/5') as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.exists('HS:DEVICE:5')
            self.assertFalse(rst)
            rst = self.redis_client.sismember('SET:DEVICE', 5)
            self.assertFalse(rst)

        devices = [1, 2, 3]
        async with aiohttp.post('http://127.0.0.1:8080/api/v2/devices/del',
                                data=json.dumps(devices)) as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.smembers('SET:DEVICE')
            self.assertEqual(len(rst), 0)
예제 #4
0
def _post(url, timeout, **kwargs):
    if timeout is None:
        response = yield from aiohttp.post(url, **kwargs)
    else:
        response = yield from asyncio.wait_for(aiohttp.post(url, **kwargs), timeout)

    try:
        data = yield from response.json()
    except ValueError:
        text = yield from response.text()
        raise BadHTTPResponse(response.status, text, response)

    if data['ok']:
        return data['result']
    else:
        description, error_code = data['description'], data['error_code']

        # Look for specific error ...
        for e in TelegramError.__subclasses__():
            n = len(e.DESCRIPTION_PATTERNS)
            if any(map(re.search, e.DESCRIPTION_PATTERNS, n*[description], n*[re.IGNORECASE])):
                raise e(description, error_code, data)

        # ... or raise generic error
        raise TelegramError(description, error_code, data)
예제 #5
0
    def _sendFile(self, inputfile, filetype, params):
        method = {
            'photo': 'sendPhoto',
            'audio': 'sendAudio',
            'document': 'sendDocument',
            'sticker': 'sendSticker',
            'video': 'sendVideo',
            'voice': 'sendVoice',
        }[filetype]

        if isinstance(inputfile, io.IOBase):
            files = {filetype: inputfile}
            r = yield from aiohttp.post(self._methodurl(method),
                                        params=self._rectify(params),
                                        data=files)

            # `_http_timeout` is not used here because, for some reason, the larger the file,
            # the longer it takes for the server to respond (after upload is finished). It is hard to say
            # what value `_http_timeout` should be. In the future, maybe I should let user specify.
        else:
            params[filetype] = inputfile
            r = yield from asyncio.wait_for(
                aiohttp.post(self._methodurl(method),
                             params=self._rectify(params)), self._http_timeout)

        return (yield from self._parse(r))
예제 #6
0
    async def coliru(self, ctx, *, code: CodeBlock):
        """Compiles code via Coliru.

        You have to pass in a codeblock with the language syntax
        either set to one of these:

        - cpp
        - python
        - py
        - haskell

        Anything else isn't supported. The C++ compiler uses g++ -std=c++14.

        Please don't spam this for Stacked's sake.
        """
        payload = {'cmd': code.command, 'src': code.source}

        data = json.dumps(payload)

        async with aiohttp.post('http://coliru.stacked-crooked.com/compile',
                                data=data) as resp:
            if resp.status != 200:
                await self.bot.say('Coliru did not respond in time.')
                return
            output = await resp.text()

            if len(output) < 1992:
                fmt = '```\n{}\n```'.format(output)
                await self.bot.say(fmt)
                return

            # output is too big so post it in gist
            gist = {
                'description':
                'The response for {0.author}\'s compilation.'.format(
                    ctx.message),
                'public':
                True,
                'files': {
                    'output': {
                        'content': output
                    },
                    'original': {
                        'content': code.source
                    }
                }
            }

            async with aiohttp.post('https://api.github.com/gists',
                                    data=json.dumps(gist)) as gh:
                if gh.status != 201:
                    await self.bot.say('Could not create gist.')
                else:
                    js = await gh.json()
                    await self.bot.say(
                        'Output too big. The content is in: {0[html_url]}'.
                        format(js))
예제 #7
0
파일: __init__.py 프로젝트: apasni/telepot
    def setWebhook(self, url=None, certificate=None):
        p = {'url': url}

        if certificate:
            files = {'certificate': certificate}
            r = yield from asyncio.wait_for(aiohttp.post(self._methodurl('setWebhook'), params=self._rectify(p), data=files), self._http_timeout)
        else:
            r = yield from asyncio.wait_for(aiohttp.post(self._methodurl('setWebhook'), params=self._rectify(p)), self._http_timeout)

        return (yield from self._parse(r))
예제 #8
0
    async def test_device_CRUD(self):
        async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices') as r:
            self.assertEqual(r.status, 200)
            rst = await r.json()
            self.assertSetEqual(set(rst), {'1', '2', '3'})
        async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/1') as r:
            self.assertEqual(r.status, 200)
            rst = await r.json()
            self.assertDictEqual(rst, mock_data.device1)
        async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/99') as r:
            self.assertEqual(r.status, 404)
            rst = await r.text()
            self.assertEqual(rst, 'device_id not found!')

        async with aiohttp.post('http://127.0.0.1:8080/api/v1/devices', data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.hgetall('HS:DEVICE:4')
            self.assertEqual(rst['name'], '测试集中器4')
            rst = self.redis_client.sismember('SET:DEVICE', 4)
            self.assertTrue(rst)
        async with aiohttp.post('http://127.0.0.1:8080/api/v1/devices', data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 409)
            rst = await r.text()
            self.assertEqual(rst, 'device already exists!')

        mock_data.test_device['name'] = '测试集中器5'
        mock_data.test_device['id'] = 5
        async with aiohttp.put('http://127.0.0.1:8080/api/v1/devices/4', data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.exists('HS:DEVICE:4')
            self.assertFalse(rst)
            rst = self.redis_client.sismember('SET:DEVICE', 4)
            self.assertFalse(rst)
            rst = self.redis_client.hgetall('HS:DEVICE:5')
            self.assertEqual(rst['name'], '测试集中器5')
            rst = self.redis_client.sismember('SET:DEVICE', 5)
            self.assertTrue(rst)
        async with aiohttp.put('http://127.0.0.1:8080/api/v1/devices/99', data=json.dumps(mock_data.test_device)) as r:
            self.assertEqual(r.status, 404)
            rst = await r.text()
            self.assertEqual(rst, 'device_id not found!')

        async with aiohttp.delete('http://127.0.0.1:8080/api/v1/devices/5') as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.exists('HS:DEVICE:5')
            self.assertFalse(rst)
            rst = self.redis_client.sismember('SET:DEVICE', 5)
            self.assertFalse(rst)

        devices = [1, 2, 3]
        async with aiohttp.post('http://127.0.0.1:8080/api/v2/devices/del', data=json.dumps(devices)) as r:
            self.assertEqual(r.status, 200)
            rst = self.redis_client.smembers('SET:DEVICE')
            self.assertEqual(len(rst), 0)
예제 #9
0
파일: lounge.py 프로젝트: pchard/RoboDanny
    async def coliru(self, ctx, *, code : CodeBlock):
        """Compiles code via Coliru.

        You have to pass in a codeblock with the language syntax
        either set to one of these:

        - cpp
        - python
        - py
        - haskell

        Anything else isn't supported. The C++ compiler uses g++ -std=c++14.

        Please don't spam this for Stacked's sake.
        """
        payload = {
            'cmd': code.command,
            'src': code.source
        }

        data = json.dumps(payload)

        async with aiohttp.post('http://coliru.stacked-crooked.com/compile', data=data) as resp:
            if resp.status != 200:
                await self.bot.say('Coliru did not respond in time.')
                return
            output = await resp.text()

            if len(output) < 1992:
                fmt = '```\n{}\n```'.format(output)
                await self.bot.say(fmt)
                return

            # output is too big so post it in gist
            gist = {
                'description': 'The response for {0.author}\'s compilation.'.format(ctx.message),
                'public': True,
                'files': {
                    'output': {
                        'content': output
                    },
                    'original': {
                        'content': code.source
                    }
                }
            }

            async with aiohttp.post('https://api.github.com/gists', data=json.dumps(gist)) as gh:
                if gh.status != 201:
                    await self.bot.say('Could not create gist.')
                else:
                    js = await gh.json()
                    await self.bot.say('Output too big. The content is in: {0[html_url]}'.format(js))
예제 #10
0
async def post(ctx):
    tkn = await db.select(table='members',
                          fields=['konishi'],
                          params={'id': ctx.message.author.id})
    if not tkn:
        return await client.say(
            ":negative_squared_cross_mark: Not logged in...")
    else:
        tkn = tkn.konishi
    await client.say(
        ":pencil: Write your post. You can also include an image...")
    msg = await client.wait_for_message(author=ctx.message.author,
                                        channel=ctx.message.channel,
                                        timeout=300)
    if not msg:
        return await client.say(":negative_squared_cross_mark: Cancelled...")
    content = msg.content
    img = await handle_image(msg)
    if img:
        data = aiohttp.FormData()
        data.add_field('file', img['data'], filename=img['name'])
        async with aiohttp.post("{}/imageupload".format(BASE_URL),
                                data=data,
                                headers={'Authorization':
                                         'Bearer ' + tkn}) as resp:
            if resp.status == 200:
                r = await resp.json()
                img = r['image_id']
            else:
                t = await resp.text()
                return await client.say(
                    ":negative_squared_cross_mark: Image upload error: {}".
                    format(t))
    async with aiohttp.post("{}/posts".format(BASE_URL),
                            data=json.dumps({
                                'content': content,
                                'image_id': img
                            }),
                            headers={
                                'Authorization': 'Bearer ' + tkn,
                                'Content-type': 'application/json'
                            }) as resp:
        r = await resp.json()
        if '2' in str(resp.status):
            return await client.say(
                ":white_check_mark: Post created successfully!")
        else:
            return await client.say(
                ":negative_squared_cross_mark: Error: {}".format(r['message']))
예제 #11
0
    def setWebhook(self, url=None, certificate=None):
        p = {'url': url}

        if certificate:
            files = {'certificate': certificate}
            r = yield from asyncio.wait_for(
                aiohttp.post(self._methodurl('setWebhook'),
                             params=self._rectify(p),
                             data=files), self._http_timeout)
        else:
            r = yield from asyncio.wait_for(
                aiohttp.post(self._methodurl('setWebhook'),
                             params=self._rectify(p)), self._http_timeout)

        return (yield from self._parse(r))
예제 #12
0
async def device_call(address,
                      port=8080,
                      method='call',
                      device_id=0,
                      term_id=0,
                      item_id=0,
                      value=None):
    try:
        call_dict = {
            'device_id': device_id,
            'term_id': term_id,
            'item_id': item_id,
            'value': value
        }
        uri = 'http://{}:{}/api/v1/device_{}'.format(address, port, method)
        print('send %s to %s' % (call_dict, uri))
        async with aiohttp.post(uri, data=json.dumps(call_dict)) as r:
            if r.status == 200:
                rst = await r.json()
                print('SUCCESS!')
                print('result =', rst)
            else:
                rst = await r.text()
                print('ERROR! code =', r.status)
                print('err_msg =', rst)
    except Exception as e:
        print('ERROR: %s', repr(e))
예제 #13
0
파일: halscript.py 프로젝트: UrLab/hal
def change_status_spaceapi(trigger, state):
    response_incubator = yield from aiohttp.post(INCUBATOR_STATUS_CHANGE_URL, data={
        "secret": INCUBATOR_SECRET,
        "open": 1 if state else 0,
    })

    yield from response_incubator.release()
예제 #14
0
async def login(ctx):
    creds = {"username": "", "password": ""}
    await client.say("""
		Logging into Konishi through >PBot will bind your account to your Discord ID
		If you agree proceed or else type `cancel`...""")
    for i in creds:
        await client.say("Enter your {}".format(i))
        msg = await client.wait_for_message(author=ctx.message.author,
                                            channel=ctx.message.channel,
                                            timeout=120)
        if msg == None or 'cancel' in msg.content:
            return await client.say(":zzz: Cancelled...")
        creds[i] = msg.content
    await client.send_typing(ctx.message.channel)
    async with aiohttp.post("{}/login".format(BASE_URL),
                            data=json.dumps(creds),
                            headers=h) as resp:
        r = await resp.json()
        if resp.status == 200:
            await client.say(""":white_check_mark: Login successfull!
			Please delete your password for safety reasons""")
            return await db.update(table='members',
                                   values={'konishi': r['access_token']},
                                   params={'id': ctx.message.author.id})
        else:
            return await client.say(":negative_squared_cross_mark: {}".format(
                r['message']))
예제 #15
0
async def create_poll(title,
                      options,
                      multi=True,
                      permissive=True,
                      captcha=False,
                      dupcheck='normal'):
    """ Create a strawpoll.

    Example:

        new_poll = strawpy.create_poll('Is Python the best?', ['Yes', 'No'])

    :param title:
    :param options:
    :param multi:
    :param permissive:
    :param captcha:
    :param dupcheck:
    :return: strawpy.Strawpoll object
    """

    query = {
        'title': title,
        'options': options,
        'multi': multi,
        'permissive': permissive,
        'captcha': captcha,
        'dupcheck': dupcheck
    }

    async with aiohttp.post(api_url, data=json.dumps(query)) as r:
        return await StrawPoll(r)
예제 #16
0
def on_new_client(client):
    headers = {}
    if client.type == 'human':
        headers["Authorization"] = client.token
    elif client.type == 'robot':
        headers["X-Robot-Key"] = client.token

    try:
        data = yield from asyncio.wait_for(aiohttp.post(settings.WEBRTC_LISTENER,
                                                        headers=headers),
                                           5)
    except (aiohttp.ClientResponseError, aiohttp.errors.ClientOSError, TimeoutError) as e:
        yield from request_close(client, "Auth server not available for token: " + client.token + " due to: " + str(e))
        return

    if data.status == 202:
        response = yield from data.json()
        client.id = response['client_id']
        client.session_id = response['webrtc_session_id']
        g_sessions[client.session_id] = client
        yield from ping_client(client)
        welcome_answer(client)
        log.info('-- ' + client.session_id + ' registered--')

    else:
        response = yield from data.text()
        log.error('Auth result: ' + str(response))
        yield from data.release()
        yield from request_close(client, "Not Authorized token: " + client.token)
예제 #17
0
파일: api.py 프로젝트: qualing/ooi3
    def api(self, request):
        """ 转发客户端和游戏服务器之间的API通信。

        :param request: aiohttp.web.Request
        :return: aiohttp.web.Response or aiohttp.web.HTTPBadRequest
        """
        action = request.match_info['action']
        session = yield from get_session(request)
        world_ip = session['world_ip']
        if world_ip:
            if action == 'api_start2' and self.api_start2 is not None:
                return aiohttp.web.Response(body=self.api_start2,
                                            headers=aiohttp.MultiDict({'Content-Type': 'text/plain'}))
            else:
                referrer = request.headers.get('REFERER')
                referrer = referrer.replace(request.host, world_ip)
                referrer = referrer.replace('https://', 'http://')
                url = 'http://' + world_ip + '/kcsapi/' + action
                headers = aiohttp.MultiDict({
                    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
                    'Origin': 'http://' + world_ip + '/',
                    'Referer': referrer,
                })
                data = yield from request.post()
                coro = aiohttp.post(url, data=data, headers=headers, connector=self.connector)
                try:
                    response = yield from asyncio.wait_for(coro, timeout=5)
                except asyncio.TimeoutError:
                    return aiohttp.web.HTTPBadRequest()
                body = yield from response.read()
                if action == 'api_start2' and len(body) > 100000:
                    self.api_start2 = body
                return aiohttp.web.Response(body=body, headers=aiohttp.MultiDict({'Content-Type': 'text/plain'}))
        else:
            return aiohttp.web.HTTPBadRequest()
예제 #18
0
    def handle_ws_part(self, ws, pub, channel):
        while not ws.closed:
            msg = yield from ws.receive()

            if msg.tp == aiohttp.MsgType.text:
                if msg.data != 'close':
                    json_msg = json.dumps({
                        'timestamp': time.time(),
                        'sender': self.sender_name,
                        'text': msg.data
                    })
                    yield from pub.publish_json(channel, json_msg)

                    post_url = '{0}/{1}/'.format(
                        SEND_MESSAGE_API_URL, self.thread_id
                    )
                    payload = {
                        'message': msg.data,
                        'api_key': API_KEY,
                        'sender_id': self.user_id
                    }
                    response = yield from aiohttp.post(post_url, data=payload)
                    assert response.status == 200
                else:
                    yield from ws.close()
            elif msg.tp == aiohttp.MsgType.close:
                print('ws connection closed')
            elif msg.tp == aiohttp.MsgType.error:
                print('ws connection exception {0}'.format(ws.exception()))
예제 #19
0
 async def login(self):
     async with aiohttp.post(self.auth_url + "/auth/tokens",
                             data=json.dumps(self.credentials),
                             headers=self.headers) as r:
         self.token_data = await r.json()
         self.headers["X-Auth-Token"] = r.headers["X-Subject-Token"]
     self.project_id = self.token_data["token"]["project"]["id"]
예제 #20
0
async def findDuplicates(imageUrl, message):
    logging.debug('Searching for %s' % message.author)
    results = []

    # Tineye reverse image search
    async with aiohttp.post(TINEYE_LOCATION, data={'url':
                                                   imageUrl}) as response:
        lines = (await response.text()).split('\n')
        for line in lines:
            if re.match(RESULT_REGEX, line):
                if int(re.sub('\D', '', line)):
                    results.append('Tineye: ' + shortener.short(response.url))
                    break

    # Google reverse image search
    searchUrl = 'https://www.google.com/searchbyimage?image_url={}'.format(
        imageUrl)
    async with aiohttp.get(searchUrl, allow_redirects=True,
                           headers=HEADERS) as response:
        result = re.search(MATCHING_REGEX, await response.text())
        if result != None:
            results.append('Google: ' + shortener.short(response.url))

    if results:
        await sendMessage(
            message.channel,
            'Other instances of this image have been found on the internet.\nThey can be found here:\n{}'
            .format('\n'.join(results)))
    else:
        await client.add_reaction(message, '\u2611')
예제 #21
0
async def upload_to_imgur(buf):
    """
    Uploads a byte array to imgur

    :param buf: The byte array to upload
    :return:
    A link to the image on imgur or None if the image could not be uploaded
    """

    # Seeking to 0
    buf.seek(0)
    data = {
        'url': 'https://api.imgur.com/3/image',
        'data': {
            'image': buf,
            'type': 'file'
        },
        'headers': {
            'authorization': 'Client-ID %s' % IMGUR_TOKEN
        }
    }

    async with http.post(**data) as r:
        json = await r.json()

        # Checking if request is okay
        if json is None or not json['success']:
            return None

        return json['data']['link']
예제 #22
0
async def join_room(room_uri):
    url = urls.api.rooms
    async with aiohttp.post(url, data={'uri': room_uri}, headers=headers) as r:
        j = await r.json()
        if 'error' in j:
            raise ValueError(j['error'] + ': {0}'.format(r))
        return j
예제 #23
0
def on_new_client(client):
    headers = {}
    if client.type == 'human':
        headers["Authorization"] = client.token
    elif client.type == 'robot':
        headers["X-Robot-Key"] = client.token

    try:
        data = yield from asyncio.wait_for(
            aiohttp.post(settings.WEBRTC_LISTENER, headers=headers), 5)
    except (aiohttp.ClientResponseError, aiohttp.errors.ClientOSError,
            TimeoutError) as e:
        yield from request_close(
            client, "Auth server not available for token: " + client.token +
            " due to: " + str(e))
        return

    if data.status == 202:
        response = yield from data.json()
        client.id = response['client_id']
        client.session_id = response['webrtc_session_id']
        g_sessions[client.session_id] = client
        yield from ping_client(client)
        welcome_answer(client)
        log.info('-- ' + client.session_id + ' registered--')

    else:
        response = yield from data.text()
        log.error('Auth result: ' + str(response))
        yield from data.release()
        yield from request_close(client,
                                 "Not Authorized token: " + client.token)
예제 #24
0
    async def guggyhd(self, ctx, *keywords):
        """Usage: /guggyhd text caption here"""
        chan = ctx.message.channel

        if keywords:
            keywords = " ".join(keywords)
        else:
            await self.bot.send_cmd_help(ctx)
            return

        req_head = {
            "Content-Type": "application/json",
            "apiKey": self.settings["GUGGY_API_KEY"]
        }
        req_body = {"sentence": keywords}

        async with aiohttp.post(GUGGY_URL,
                                data=json.dumps(req_body),
                                headers=req_head) as r:
            result = await r.json()
            if r.status == 200:
                if result["reqId"]:
                    try:
                        e = discord.Embed()
                        #e.set_image(url=result["animated"][0]["gif"]["lowQuality"]["secureUrl"])
                        e.set_image(url=result["animated"][0]["gif"]["hires"]
                                    ["secureUrl"])
                        await self.bot.send_message(chan, embed=e)
                    except:
                        await self.bot.say("Error loading image.")
                else:
                    await self.bot.say("No results found.")
            else:
                await self.bot.say("Error contacting the API")
예제 #25
0
    def test_update(self):

        resp = yield from aiohttp.post(
            self.full_url(self.app.reverse('fruit_index')),
            data=json.dumps(dict(name='pear', colors=['green'])),
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(
            self.full_url(self.app.reverse('fruit_item', id='pear'))
        )

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()
        self.assertEqual(jr['body'], dict(colors=['green']))
        resp.close()

        resp = yield from aiohttp.put(
            self.full_url(self.app.reverse('fruit_item', id='pear')),
            data=json.dumps(dict(colors=['green', 'yellow'])),
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(
            self.full_url(self.app.reverse('fruit_item', id='pear'))
        )

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()
        self.assertEqual(jr['body'], dict(colors=['green', 'yellow']))
        resp.close()
예제 #26
0
    def test_delete(self):

        resp = yield from aiohttp.post(
            self.full_url(self.app.reverse('fruit_index')),
            data=json.dumps(dict(name='grape', colors=['purple'])),
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(
            self.full_url(self.app.reverse('fruit_item', id='grape'))
        )

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()

        self.assertEqual(jr['body'], dict(colors=['purple']))
        resp.close()

        resp = yield from aiohttp.delete(
            self.full_url(self.app.reverse('fruit_item', id='grape'))
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(
            self.full_url(self.app.reverse('fruit_item', id='grape'))
        )

        self.assertEqual(resp.status, 404)
        resp.close()
예제 #27
0
 async def test_device_call(self):
     call_dict = {'device_id': '1', 'term_id': '10', 'item_id': 1000}
     async with aiohttp.post('http://127.0.0.1:8080/api/v1/device_call',
                             data=json.dumps(call_dict)) as r:
         self.assertEqual(r.status, 200)
         rst = await r.json()
         self.assertAlmostEqual(rst['value'], 102, delta=0.0001)
예제 #28
0
 def login(self, username, password):
     """
     """
     yield from self.get_login()
     s = yield from aiohttp.post(LOGIN_AJAX,
                                 data={
                                     'email': username,
                                     'password': password,
                                 },
                                 headers={
                                     'X-CSRFToken': self.csrf_token,
                                     'User-Agent': USER_AGENT,
                                     'Referer': LOGIN_URL,
                                     'Origin': ORIGIN,
                                     'X-Requested-With': 'XMLHttpRequest',
                                 },
                                 cookies=self.cookies)
     self.get = partial(aiohttp.get,
                        headers={'X-CSRFToken': self.csrf_token},
                        cookies=s.cookies)
     a = yield from s.json()
     if a['success']:
         print('登录成功:', s.status)
     else:
         print('登录失败:', a['value'])
     yield from s.release()
예제 #29
0
 async def test_sql_check(self):
     async with aiohttp.post('http://127.0.0.1:8080/api/v1/sql_check',
                             data=json.dumps(
                                 mock_data.term10_item1000)) as r:
         self.assertEqual(r.status, 200)
         rst = await r.text()
         self.assertEqual(rst, 'not found sql to check')
예제 #30
0
파일: ui.py 프로젝트: pombredanne/piscina
    def auth_twitter_start(self, request):
        ''' Begin the Twitter 3-legged OAuth process. '''

        api_url = 'https://api.twitter.com/oauth/request_token'
        callback_url = 'http://{}:{}/auth/twitter-callback' \
                       .format(self._fqdn, self._port)
        redirect_url = 'https://api.twitter.com/oauth/authorize?oauth_token={}'

        oauth = self._twitter.oauth_sign(
            method='POST',
            url=api_url,
            oauth_extra={'oauth_callback': callback_url}
        )

        log.debug('Getting Twitter request token: {}'.format(oauth))

        response = yield from aiohttp.post(api_url, headers={'Authorization': oauth})
        body = yield from response.read()
        body = body.decode('utf8')

        if response.status != 200:
            log.error('auth_twitter_start() failed: Twitter API status {} "{}"' \
                      .format(response.status, body))

            raise aiohttp.web.HTTPInternalServerError(body=b'Failed to log in to Twitter.')

        token_data = parse_qs(body)
        log.debug('Got Twitter request token: {}'.format(token_data))
        oauth_token = token_data['oauth_token']
        oauth_token_secret = token_data['oauth_token_secret']
        self._temp_tokens['twitter'][oauth_token] = oauth_token_secret

        raise aiohttp.web.HTTPFound(redirect_url.format(oauth_token))
예제 #31
0
def getImgWords(imgUrl):
    bImage = ''
    m = re.match(r'^http.+/(.+)', imgUrl)
    imgName = m.group(1) if m is not None else None
    if imgName is None:
        pass
    try:
        r = yield from aiohttp.get(imgUrl)
    except aiohttp.errors.ClientOSError as e:
        print('[error url:%s]  %s' % (url, e))
    else:
        bImage = yield from r.read()
        with open(dirBase + imgName, 'wb') as f:
            f.write(bImage)
        #百度OCR
        payload = {
            'fromdevice': 'pc',
            'clientip': '115.28.134.55',
            'detecttype': 'LocateRecognize',
            'languagetype': 'CHN_ENG',
            'imagetype': '1',
            'image': base64.b64encode(bImage).decode("utf-8")
        }
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "apikey": "0830a440f9e1b9a31c5e807fa2f0ab61"
        }
        url = 'http://apis.baidu.com/apistore/idlocr/ocr'
        rdd = yield from aiohttp.post(url, data=payload, headers=headers)
        return (yield from rdd.text())
예제 #32
0
파일: bot.py 프로젝트: banteg/aiotg
    def api_call(self, method, **params):
        """Call Telegram API
        See https://core.telegram.org/bots/api for the reference
        """
        if isinstance(params.get('reply_markup'), dict):
            params['reply_markup'] = json.dumps(params['reply_markup'])

        url = "{0}/bot{1}/{2}".format(API_URL, self.api_token, method)
        response = yield from aiohttp.post(url, data=params)

        if response.status == 200:
            return (yield from response.json())
        elif response.status in RETRY_CODES:
            logger.info("Server returned %d, retrying in %d sec.",
                        response.status, RETRY_TIMEOUT)
            yield from response.release()
            yield from asyncio.sleep(RETRY_TIMEOUT)
            return (yield from self.api_call(method, **params))
        else:
            if response.headers['content-type'] == 'application/json':
                err_msg = (yield from response.json())["description"]
            else:
                err_msg = yield from response.read()
            logger.error(err_msg)
            raise RuntimeError(err_msg)
예제 #33
0
def getImgWords(imgUrl):
    bImage = ''
    m = re.match(r'^http.+/(.+)', imgUrl)
    imgName = m.group(1) if m is not None else None
    if imgName is None:
        pass
    try:
        r = yield from aiohttp.get(imgUrl)
    except aiohttp.errors.ClientOSError as e:
        print('[error url:%s]  %s' % (url, e))
    else:
        bImage = yield from r.read()
        with open(dirBase+imgName, 'wb') as f:
           f.write(bImage)
        #百度OCR
        payload = {'fromdevice':'pc',
                           'clientip':'115.28.134.55',
                           'detecttype':'LocateRecognize',
                           'languagetype':'CHN_ENG',
                           'imagetype':'1',
                           'image': base64.b64encode(bImage).decode("utf-8")
                           }
        headers = {"Content-Type": "application/x-www-form-urlencoded",
                            "apikey": "0830a440f9e1b9a31c5e807fa2f0ab61"
                          }
        url = 'http://apis.baidu.com/apistore/idlocr/ocr'
        rdd = yield from aiohttp.post(url,data=payload,headers=headers)
        return (yield from rdd.text())
예제 #34
0
파일: snare.py 프로젝트: nsmfoo/snare
 def submit_data(self, data):
     with aiohttp.Timeout(10.0):
         r = yield from aiohttp.post(
             'http://{0}:8090/event'.format(self.run_args.tanner), data=json.dumps(data)
         )
         event_result = yield from r.json()
     return event_result
예제 #35
0
def report_links():
    db = sqlite3.connect('links.db')
    while True:
        link = yield from broken_links.get()

        issue = json.dumps({
            'title':
            "Found a broken link in {repo_short}!".format(
                repo_short=urlparse(link[1]).path[1:]),
            'body':
            """
@{owner}, there's a [broken link]({broken_link}) in the README of [one of your repositories]({repo}).
You should fix it so that users don't get confused while browsing it!

> A `HEAD` request was sent to {broken_link} and an `HTTP {http_status}` was returned.

*This is a bot-generated issue, reply to this issue if this link wasn't broken or if you fixed it so I can close it!*
            """.format(owner=link[0],
                       repo=link[1],
                       broken_link=link[2],
                       http_status=link[3]).strip(),
            'labels': [
                'broken-link',
            ]
        })

        r = yield from aiohttp.post(ISSUES, data=issue, auth=(USR, PWD))

        db.execute('insert into links values (?)', (link[2], ))
        db.commit()

        yield from wait_if_required(r.headers)

        r.close()
    db.close()
예제 #36
0
 def send_file_pcap(self,f):
     data = FormData()
     data.add_field('file',
            open(f, 'rb'),
            filename=f
            )
     yield from aiohttp.post(url, data=data)
예제 #37
0
 def getUpdates(self, offset=None, limit=None, timeout=None):
     p = {'offset': offset, 'limit': limit, 'timeout': timeout}
     r = yield from asyncio.wait_for(
         aiohttp.post(self._methodurl('getUpdates'),
                      params=self._rectify(p)),
         self._http_timeout + (0 if timeout is None else timeout))
     return (yield from self._parse(r))
예제 #38
0
 async def gist(self, ctx, *, content: str):
     """Upload inputed text to gist.github.com"""
     gist = {
         'description':
         'Uploaded from NotSoSuper\'s Bot by {0} <{1}>.'.format(
             ctx.message.author.name, ctx.message.author.id),
         'public':
         True,
         'files': {
             'discord.py': {
                 'content': str(content)
             }
         }
     }
     headers = {'Authorization': 'token yourtoken'}
     async with aiohttp.post('https://api.github.com/gists',
                             data=json.dumps(gist),
                             headers=headers) as gh:
         if gh.status != 201:
             await self.bot.say('Could not create gist.')
         elif len(content) > 500:
             js = await gh.json()
             await self.bot.say(
                 'Output too big. The gist URL: {0[html_url]}'.format(js))
         else:
             js = await gh.json()
             await self.bot.say(
                 'Uploaded ```{0}``` to gist. The URL is: {1[html_url]}'.
                 format(content, js))
예제 #39
0
    def oauth(self, code, state):
        """Handler for Authorization callback URL.

        'code' and 'state' are GET variables given by github

        :param string code:
        :param string state:
        :return: Client instance
        :raises: exceptions.GithubException
        """
        try:
            scopes = self._requested_scopes.pop(state)
        except KeyError:
            raise exceptions.UnknownState(state)
        data = {
            "client_id": self._client_id,
            "client_secret": self._client_secret,
            "code": code,
            "state": state,
        }
        headers = {
            "accept": "application/json"
        }
        response = yield from aiohttp.post(REQ_TOKEN_URL,
                                           data=data,
                                           headers=headers)
        data = yield from response.json()
        return Client(data["access_token"], scopes)
예제 #40
0
    async def epvpis(self, user: str):
        '''Search for an username on elitepvpers.com

        Beispiel:
        -----------

        :epvpis Der-Eddy
        '''
        url = 'https://www.elitepvpers.com/forum/ajax.php?do=usersearch'
        payload = {'do': 'usersearch', 'fragment': user}
        async with aiohttp.post(url,
                                data=payload,
                                headers=self.bot.userAgentHeaders) as r:
            if r.status == 200:
                root = ET.fromstring(await r.text())
                if len(root) > 0:
                    embed = discord.Embed(color=0xf1c40f)  #golden
                    embed.set_footer(
                        text='A maximum of 15 user can be displayed')
                    embed.set_thumbnail(
                        url='https://abload.de/img/epvp_shield_hiresyskb3.png')
                    msg = ':ok: I could find {} user!'.format(len(root))
                    for i in root:
                        userURL = 'https://www.elitepvpers.com/forum/member.php?u=' + i.attrib[
                            'userid']
                        embed.add_field(name=i.text,
                                        value=userURL,
                                        inline=False)
                    await self.bot.say(msg, embed=embed)
                else:
                    msg = f':no_entry: Couldn\'t find any user **{username}** :sweat:'
                    await self.bot.say(msg)
예제 #41
0
    def event_occurred(self, event):
        if isinstance(event, minerdaemon.events.VersionEvent):
            # Save version and miner if this is a VersionEvent
            self._version = event.version
            self._miner = event.miner
        elif isinstance(event, minerdaemon.events.NetworkEvent):
            # Save username if this is a NetworkEvent
            self._username = event.username

        self._events.append(event)

        # Log events to endpoint, if we've reached the batch event count
        if self._version and self._miner and self._username and len(self._events) >= self._NUM_EVENTS_BATCHED:
            # Assemble payload
            payload = [{'channel': 'minerd', 'version': self._version, 'miner': self._miner, 'username': self._username, 'event': e} for e in self._events]
            payload = json.dumps(payload, cls=minerdaemon.events.EventEncoder)

            # Reset events list
            self._events = []

            # POST to endpoint
            try:
                r = yield from aiohttp.post(self._url, params={'bulk': 'true'}, data=payload)
                r.close()
            except Exception as e:
                logger.debug("[splunkloggerbackend] Error logging to endpoint: %s", str(e))
예제 #42
0
    async def epvpis(self, user: str):
        '''Sucht nach einem Benutzernamen auf Elitepvpers

        Beispiel:
        -----------

        :epvpis Der-Eddy
        '''
        url = 'https://www.elitepvpers.com/forum/ajax.php?do=usersearch'
        payload = {'do': 'usersearch', 'fragment': user}
        async with aiohttp.post(url,
                                data=payload,
                                headers=self.bot.userAgentHeaders) as r:
            if r.status == 200:
                root = ET.fromstring(await r.text())
                if len(root) > 0:
                    embed = discord.Embed(color=0xf1c40f)  #golden
                    embed.set_footer(
                        text='Es können maximal 15 Accounts gefunden werden')
                    embed.set_thumbnail(
                        url='https://abload.de/img/epvp_shield_hiresyskb3.png')
                    msg = ':ok: Ich konnte {} Accounts finden!'.format(
                        len(root))
                    for i in root:
                        userURL = 'https://www.elitepvpers.com/forum/member.php?u=' + i.attrib[
                            'userid']
                        embed.add_field(name=i.text,
                                        value=userURL,
                                        inline=False)
                    await self.bot.say(msg, embed=embed)
                else:
                    msg = f':no_entry: Ich konnte keine Epvp Accounts zu **{username}** finden :sweat:'
                    await self.bot.say(msg)
예제 #43
0
    async def _send(self, payload, processor):
        '''Send a payload to be converted to JSON.

        Handles temporary connection issues.  Daemon reponse errors
        are raise through DaemonError.
        '''
        self.prior_msg = None
        self.skip_count = None

        def log_error(msg, skip_once=False):
            if skip_once and self.skip_count is None:
                self.skip_count = 1
            if msg != self.prior_msg or self.skip_count == 0:
                self.skip_count = 10
                self.prior_msg = msg
                self.logger.error('{}  Retrying between sleeps...'.format(msg))
            self.skip_count -= 1

        data = json.dumps(payload)
        secs = 1
        max_secs = 16
        while True:
            try:
                async with self.workqueue_semaphore:
                    url = self.urls[self.url_index]
                    async with aiohttp.post(url, data=data) as resp:
                        # If bitcoind can't find a tx, for some reason
                        # it returns 500 but fills out the JSON.
                        # Should still return 200 IMO.
                        if resp.status in (200, 500):
                            if self.prior_msg:
                                self.logger.info('connection restored')
                            result = processor(await resp.json())
                            return result
                log_error('HTTP error code {:d}: {}'.format(
                    resp.status, resp.reason))
            except asyncio.TimeoutError:
                log_error('timeout error.', skip_once=True)
            except aiohttp.ClientHttpProcessingError:
                log_error('HTTP error.', skip_once=True)
            except aiohttp.ServerDisconnectedError:
                log_error('disconnected.', skip_once=True)
            except aiohttp.ClientConnectionError:
                log_error('connection problem - is your daemon running?')
            except self.DaemonWarmingUpError:
                log_error('starting up checking blocks.')
            except (asyncio.CancelledError, DaemonError):
                raise
            except Exception:
                self.log_error(traceback.format_exc())

            if secs >= max_secs and len(self.urls) > 1:
                self.url_index = (self.url_index + 1) % len(self.urls)
                logged_url = self.logged_url(self.urls[self.url_index])
                self.logger.info('failing over to {}'.format(logged_url))
                secs = 1
            else:
                await asyncio.sleep(secs)
                secs = min(max_secs, secs * 2)
예제 #44
0
    async def _post(self, ctx, *, url):
        """Performs POST or PUT request to selected URL"""

        await self.bot.say('Set headers by typing them in a `name=value` format, one on each line, or `pass`')

        answer = await self.bot.wait_for_message(timeout=50, author=ctx.message.author)

        parsed = self._parse_headers(answer)
        headers = parsed['headers']
        public_headers = parsed['public_headers']

        await self.bot.say('Headers are set to:\n```json\n{}```\nSet body typing in in a `name=value` one on each line or `pass`\nNested objects are not supported'
                           .format(json.dumps(public_headers, indent=4, sort_keys=True)))

        answer = await self.bot.wait_for_message(timeout=50, author=ctx.message.author)

        body = self._parse_body(answer)

        await self.bot.say('Body is set to:\n```json\n{}```'.format(json.dumps(body, indent=4, sort_keys=True)))

        url = url.strip()
        method = ctx.invoked_with

        if method == 'post':
            t1 = time.perf_counter()
            async with aiohttp.post(url, headers=headers, data=json.dumps(body)) as r:
                t2 = time.perf_counter()
                data = await r.text()
                status = r.status

        if method == 'put':
            if 'Content-Type' not in headers:
                headers['Content-Type'] = 'application/json'

            t1 = time.perf_counter()
            async with aiohttp.put(url, headers=headers, data=json.dumps(body)) as r:
                t2 = time.perf_counter()
                data = await r.text()
                status = r.status

        try:
            parsed = json.loads(data)
        except:
            parsed = json.loads('{}')

        color = status == 200 and 0x2ecc71 or status >= 400 and 0xe74c3c
        embed = discord.Embed(title='Results for **{}** {}'.format(method.upper(), url),
                              color=color,
                              description='```json\n{}```'.format(len(data) < 700
                                                                  and
                                                                  json.dumps(parsed, indent=4, sort_keys=True)
                                                                  or
                                                                  json.dumps(parsed, indent=4, sort_keys=True)[:700]
                                                                  + '\n\n...\n\n'))
        embed.add_field(name='Status',
                        value=status)
        embed.add_field(name='Time',
                        value='{}ms'.format(str((t2-t1) * 1000)[:3]))
        await self.bot.say(embed=embed)
예제 #45
0
def get_tank_data_proxy(account_id, app_idx):
	queries['account_id'] = str(account_id)
	queries['application_id'] = app_ids[app_idx]
	stat_url = tank_stat_url + '?' + '&'.join([k + '=' + queries[k] for k in queries])
	payload = {'a': stat_url}
	response = yield from asyncio.wait_for(aiohttp.post(proxy_urls[app_idx], data=payload), 10)
	#response = yield from aiohttp.post('http://127.0.0.1:5000/', data=payload)
	return (yield from response.json())
예제 #46
0
def get_player_nicks(ids, app_idx):
  queries['account_id'] = ids
  queries['application_id'] = app_ids[app_idx]
  stat_url = tank_stat_url + '?' + '&'.join([k + '=' + queries[k] for k in queries])
  payload = {'a': stat_url}
  response = yield from asyncio.wait_for(aiohttp.post(player_proxy_urls[app_idx], data=payload), 10)
  #response = yield from asyncio.wait_for(aiohttp.get(tank_stat_url, params=queries), 10)
  return (yield from response.json())
예제 #47
0
def end(video_id, video_log_id):
    req_data = {
        'videolog_id': video_log_id,
        'video_id': video_id,
    }
    r = yield from aiohttp.post(URL_END, data=req_data, headers=get_headers(cookie))
    resp = yield from r.text()
    print(resp)
예제 #48
0
파일: bot.py 프로젝트: Oleg-MBO/aiotg
 def api_call(self, method, **params):
     """Call Telegram API
     See https://core.telegram.org/bots/api for the reference
     """
     url = "{0}/bot{1}/{2}".format(API_URL, self.api_token, method)
     response = yield from aiohttp.post(url, data=params)
     assert response.status == 200
     return (yield from response.json())
예제 #49
0
    async def _update_carbon(self):
        payload = {
            'key': self.bot.carbon_key,
            'servercount': len(self.bot.servers)
        }

        async with aiohttp.post(CARBONITEX_API_BOTDATA, data=payload) as resp:
            log.info('Carbon statistics returned {0.status} for {1}'.format(resp, payload))
예제 #50
0
    def _sendFile(self, inputfile, filetype, params):
        method = {
            'photo': 'sendPhoto',
            'audio': 'sendAudio',
            'document': 'sendDocument',
            'sticker': 'sendSticker',
            'video': 'sendVideo',
            'voice': 'sendVoice',
        }[filetype]

        if telepot._isstring(inputfile):
            params[filetype] = inputfile
            r = yield from asyncio.wait_for(
                aiohttp.post(self._methodurl(method),
                             data=self._rectify(
                                 params, allow_namedtuple=['reply_markup'])),
                self._http_timeout)
        else:
            if isinstance(inputfile, tuple):
                if len(inputfile) == 2:
                    filename, fileobj = inputfile
                else:
                    raise ValueError(
                        'Tuple must have exactly 2 elements: filename, fileobj'
                    )
            else:
                filename, fileobj = guess_filename(
                    inputfile) or filetype, inputfile

            mpwriter = aiohttp.MultipartWriter('form-data')
            part = mpwriter.append(fileobj)
            part.set_content_disposition('form-data',
                                         name=filetype,
                                         filename=filename)

            r = yield from aiohttp.post(self._methodurl(method),
                                        params=self._rectify(
                                            params,
                                            allow_namedtuple=['reply_markup']),
                                        data=mpwriter)

            # `_http_timeout` is not used here because, for some reason, the larger the file,
            # the longer it takes for the server to respond (after upload is finished). It is hard to say
            # what value `_http_timeout` should be. In the future, maybe I should let user specify.

        return (yield from self._parse(r))
예제 #51
0
 async def post_captcha_base(self, post_data):
     async with aiohttp.post(self.input_url, data=post_data) as response:
         resp_text = await response.text()
         parsed_resp = resp_text.split('|')
         if 'OK' in parsed_resp:
             return parsed_resp[1]
         else:
             raise AntigateException(resp_text)
예제 #52
0
    def post_smfile_data(self):
        url = "http://smleaderboards.net/api/v1/parse_meta/"
        post_data = {'file': self.get_smfile_data()}

        result = yield from aiohttp.post(url, data=post_data)

        a = yield from result.text()
        print(a)
예제 #53
0
 def api_call(self, method, **params):
     """Call Telegram API
     See https://core.telegram.org/bots/api for the reference
     """
     url = "{0}/bot{1}/{2}".format(API_URL, self.api_token, method)
     response = yield from aiohttp.post(url, data=params)
     assert response.status == 200
     return (yield from response.json())
예제 #54
0
async def feed(ctx):
    tkn = await db.select(table='members',
                          fields=['konishi'],
                          params={'id': ctx.message.author.id})
    if not tkn:
        return await client.say(
            ":negative_squared_cross_mark: Not logged in...")
    else:
        tkn = tkn.konishi
    if ctx.message.author in usr:
        for m in usr[ctx.message.author]:
            await client.delete_message(m['message'])
        usr[ctx.message.author] = []
    else:
        usr[ctx.message.author] = []
    async with aiohttp.get("{}/feed".format(BASE_URL),
                           params={'limit': 10},
                           headers={'Authorization': 'Bearer ' + tkn}) as resp:
        if resp.status == 200:
            r = await resp.text()
            async with aiohttp.post("{}/feed".format(BASE_URL),
                                    data=r,
                                    headers=({
                                        'Content-type': 'application/json',
                                        'Authorization': 'Bearer ' + tkn
                                    })) as r:
                if r.status == 200:
                    r = await r.json()
                    for r in r['posts']:
                        embed = discord.Embed()
                        embed.set_author(name=r['creator_name'])
                        embed.description = r['content']
                        embed.add_field(
                            name="{} Likes".format(len(r['likes'])),
                            value="{} Comments".format(len(r['comments'])),
                            inline=True)
                        embed.set_footer(
                            text="Created at {}".format(r['created']))
                        m = await client.say(embed=embed)
                        await client.add_reaction(m, '\U0001f44d')
                        if len(r['comments']) > 0:
                            await client.add_reaction(m, '\U0001f5e8')
                        await client.add_reaction(m, '\U0000270f')
                        usr[ctx.message.author].append({
                            'message': m,
                            'post': r['id'],
                            'embed': embed
                        })
                else:
                    r = await r.json()
                    await client.say(
                        ":negative_squared_cross_mark: Error: {}".format(
                            r['message']))
        else:
            resp = await resp.json()
            await client.say(":negative_squared_cross_mark: Error: {}".format(
                resp['message']))
    return
예제 #55
0
    async def coliru(self, ctx, *, code: CodeBlock):
        """Compiles code via Coliru.

        You have to pass in a code block with the language syntax
        either set to one of these:

        - cpp
        - c
        - python
        - py
        - haskell

        Anything else isn't supported. The C++ compiler uses g++ -std=c++14.

        The python support is only python2.7 (unfortunately).

        Please don't spam this for Stacked's sake.
        """
        payload = {'cmd': code.command, 'src': code.source}

        data = json.dumps(payload)

        await self.bot.type()
        async with aiohttp.post('http://coliru.stacked-crooked.com/compile',
                                data=data) as resp:
            if resp.status != 200:
                await self.bot.say('Coliru did not respond in time.')
                return
            output = await resp.text()

            if len(output) < 1992:
                fmt = '```\n{}\n```'.format(output)
                await self.bot.say(fmt)
                return

            # output is too big so post it in gist
            async with aiohttp.post('http://coliru.stacked-crooked.com/share',
                                    data=data) as resp:
                if resp.status != 200:
                    await self.bot.say('Could not create coliru shared link')
                else:
                    shared_id = await resp.text()
                    await self.bot.say(
                        'Output too big. Coliru link: http://coliru.stacked-crooked.com/a/'
                        + shared_id)
예제 #56
0
파일: client.py 프로젝트: eevee/dywypi
 async def login(self, username, password):
     # TODO this should wait on the challstr
     # TODO but then this can't be called from the same stack that's reading events.  unless there's an independent big ol' buffer
     challenge = await self.get_challenge()
     # TODO in my browser this has a /~~localhost/ bit
     async with aiohttp.post('https://play.pokemonshowdown.com/action.php', data={'act': 'login', 'name': username, 'pass': password, 'challstr': challenge}, loop=self.loop) as resp:
         text = await resp.text()
         login_payload = json.loads(text[1:])
         await self.websocket.send('|' + '/trn {},0,{}'.format(username, login_payload['assertion']))
예제 #57
0
 def forwardMessage(self, chat_id, from_chat_id, message_id, disable_notification=None):
     p = self._strip(locals())
     r = yield from asyncio.wait_for(
             aiohttp.post(
                 self._methodurl('forwardMessage'), 
                 data=self._rectify(p)), 
             self._http_timeout
         )
     return (yield from self._parse(r))
예제 #58
0
 def sendMessage(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
     p = self._strip(locals())
     r = yield from asyncio.wait_for(
             aiohttp.post(
                 self._methodurl('sendMessage'), 
                 data=self._rectify(p, allow_namedtuple=['reply_markup'])), 
             self._http_timeout
         )
     return (yield from self._parse(r))
예제 #59
0
 def answerInlineQuery(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None):
     p = self._strip(locals())
     r = yield from asyncio.wait_for(
             aiohttp.post(
                 self._methodurl('answerInlineQuery'), 
                 data=self._rectify(p, allow_namedtuple=['results'])),
             timeout=self._http_timeout
         )
     return (yield from self._parse(r))
예제 #60
0
 def getUpdates(self, offset=None, limit=None, timeout=None):
     p = self._strip(locals())
     r = yield from asyncio.wait_for(
             aiohttp.post(
                 self._methodurl('getUpdates'), 
                 data=self._rectify(p)), 
             self._http_timeout+(0 if timeout is None else timeout)
         )
     return (yield from self._parse(r))