Пример #1
0
    def distance_to(self, lat_lon: Tuple[float, float]) -> float:
        """
        Calculate the difference to the other coordinate (server) and also save it to the parameters.

        :param lat_lon: Location of the other server (latitude, longitude).

        :return: Distance in kilometers.
        """
        return speedtest.distance(self.lat_lon, lat_lon)
Пример #2
0
async def speedtest(context):
    """ Tests internet speed using speedtest. """
    test = Speedtest()
    server, server_json = [], False
    if len(context.parameter) == 1:
        try:
            server = [int(context.parameter[0])]
        except ValueError:
            await context.edit(lang('arg_error'))
            return
    elif len(context.parameter) >= 2:
        try:
            temp_json = findall(r'{(.*?)}', context.text.replace("'", '"'))
            if len(temp_json) == 1:
                server_json = loads("{" + temp_json[0] + "}")
                server_json['d'] = distance(
                    test.lat_lon,
                    (float(server_json['lat']), float(server_json['lon'])))
                test.servers = [server_json]
            else:
                await context.edit(lang('arg_error'))
                return
        except:
            pass
    await context.edit(lang('speedtest_processing'))
    try:
        if len(server) == 0:
            if not server_json:
                test.get_best_server()
            else:
                test.get_best_server(servers=test.servers)
        else:
            test.get_servers(servers=server)
    except (SpeedtestBestServerFailure, NoMatchedServers) as e:
        await context.edit(lang('speedtest_ServerFailure'))
        return
    test.download()
    test.upload()
    try:
        test.results.share()
    except (ShareResultsConnectFailure, ShareResultsSubmitFailure) as e:
        await context.edit(lang('speedtest_ConnectFailure'))
        return
    result = test.results.dict()
    des = (f"**Speedtest** \n"
           f"Server: `{result['server']['name']} - "
           f"{result['server']['cc']}` \n"
           f"Sponsor: `{result['server']['sponsor']}` \n"
           f"Upload: `{unit_convert(result['upload'])}` \n"
           f"Download: `{unit_convert(result['download'])}` \n"
           f"Latency: `{result['ping']}` \n"
           f"Timestamp: `{result['timestamp']}`")
    await context.client.send_file(context.chat_id,
                                   result['share'],
                                   caption=des)
    await context.delete()
Пример #3
0
async def speedtest(context):
    """ Tests internet speed using speedtest. """
    try:
        speed_test_path = config['speed_test_path']
    except KeyError:
        speed_test_path = ''
    if not speed_test_path == '':
        server = None
        if len(context.parameter) == 1:
            try:
                server = int(context.parameter[0])
            except ValueError:
                await context.reply(lang('arg_error'))
                return
        speed_test_path += ' -f json'
        if server:
            speed_test_path += f' -s {server}'
        msg = await context.reply(lang('speedtest_processing'))
        result = await execute(f'{speed_test_path}')
        result = loads(result)
        if result['type'] == 'log':
            await msg.edit(f"{result['level'].upper()}:{result['message']}")
        elif result['type'] == 'result':
            des = (
                f"**Speedtest** \n"
                f"Server: `{result['server']['name']} - "
                f"{result['server']['location']}` \n"
                f"Host: `{result['server']['host']}` \n"
                f"Upload: `{unit_convert(result['upload']['bandwidth'] * 8)}` \n"
                f"Download: `{unit_convert(result['download']['bandwidth'] * 8)}` \n"
                f"Latency: `{result['ping']['latency']}` \n"
                f"Jitter: `{result['ping']['jitter']}` \n"
                f"Timestamp: `{result['timestamp']}`"
            )
            # 开始处理图片
            data = (await get(f"{result['result']['url']}.png")).content
            with open('speedtest.png', mode='wb') as f:
                f.write(data)
            try:
                img = Image.open('speedtest.png')
                c = img.crop((17, 11, 727, 389))
                c.save('speedtest.png')
            except:
                pass
            try:
                await context.client.send_file(context.chat_id, 'speedtest.png', caption=des)
            except:
                pass
            try:
                remove('speedtest.png')
            except:
                pass
            await msg.delete()
        else:
            await msg.edit(result)
        return
    try:
        test = Speedtest()
    except SpeedtestHTTPError:
        await context.reply(lang('speedtest_ConnectFailure'))
        return
    server, server_json = [], False
    if len(context.parameter) == 1:
        try:
            server = [int(context.parameter[0])]
        except ValueError:
            await context.reply(lang('arg_error'))
            return
    elif len(context.parameter) >= 2:
        try:
            temp_json = findall(r'{(.*?)}', context.text.replace("'", '"'))
            if len(temp_json) == 1:
                server_json = loads("{" + temp_json[0] + "}")
                server_json['d'] = distance(test.lat_lon, (float(server_json['lat']), float(server_json['lon'])))
                test.servers = [server_json]
            else:
                await context.reply(lang('arg_error'))
                return
        except:
            pass
    msg = await context.reply(lang('speedtest_processing'))
    try:
        if len(server) == 0:
            if not server_json:
                test.get_best_server()
            else:
                test.get_best_server(servers=test.servers)
        else:
            test.get_servers(servers=server)
    except (SpeedtestBestServerFailure, NoMatchedServers) as e:
        await msg.edit(lang('speedtest_ServerFailure'))
        return
    try:
        test.download()
        test.upload()
        test.results.share()
    except (ShareResultsConnectFailure, ShareResultsSubmitFailure, RuntimeError) as e:
        await msg.edit(lang('speedtest_ConnectFailure'))
        return
    result = test.results.dict()
    des = (
        f"**Speedtest** \n"
        f"Server: `{result['server']['name']} - "
        f"{result['server']['cc']}` \n"
        f"Sponsor: `{result['server']['sponsor']}` \n"
        f"Upload: `{unit_convert(result['upload'])}` \n"
        f"Download: `{unit_convert(result['download'])}` \n"
        f"Latency: `{result['ping']}` \n"
        f"Timestamp: `{result['timestamp']}`"
    )
    # 开始处理图片
    data = (await get(result['share'])).content
    with open('speedtest.png', mode='wb') as f:
        f.write(data)
    try:
        img = Image.open('speedtest.png')
        c = img.crop((17, 11, 727, 389))
        c.save('speedtest.png')
    except:
        pass
    try:
        await context.client.send_file(context.chat_id, 'speedtest.png', caption=des)
    except:
        return
    try:
        remove('speedtest.png')
    except:
        pass
    await msg.delete()