Ejemplo n.º 1
0
async def websocket_handler(request):
    global clients
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    query = dict(request.query)
    realIp = request.headers.get('X-FORWARDED-FOR', None)
    if realIp is None:
        realIp = request.remote
    if 'token' not in query:
        await ws.close(code=1000, message=b'No Token')
        print(
            f'[{datetime.datetime.now().strftime("%m-%d %H:%M:%S")}] {realIp} No token'
        )
        return ws
    serverConfig = getServerConfig(query['token'])
    if serverConfig is None:
        await ws.close(code=1000, message=b'Wrong Token')
        print(
            f'[{datetime.datetime.now().strftime("%m-%d %H:%M:%S")}] {realIp} {query["token"]} Wrong Token'
        )
        return ws
    if 'name' not in query:
        await ws.close(code=1000, message=b'No Name')
        print(
            f'[{datetime.datetime.now().strftime("%m-%d %H:%M:%S")}] {realIp} {query["token"]} No Name'
        )
        return ws
    if len(query['name']) == 0:
        await ws.close(code=1000, message=b'Empty Name')
        print(
            f'[{datetime.datetime.now().strftime("%m-%d %H:%M:%S")}] {realIp} {query["token"]} Empty Name'
        )
        return ws
    await addClient(query['token'], query['name'], ws)
    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            print(
                f'[{datetime.datetime.now().strftime("%m-%d %H:%M:%S")}] {realIp} {query["token"]} {query["name"]} {msg.data}'
            )
            await dataProcess(msg.data, query['token'], query['name'])
        elif msg.type == aiohttp.WSMsgType.ERROR:
            print(
                f'[{datetime.datetime.now().strftime("%m-%d %H:%M:%S")}] {realIp} {query["token"]} {query["name"]} ws connection closed with exception {ws.exception()}'
            )
    print(
        f'[{datetime.datetime.now().strftime("%m-%d %H:%M:%S")}] {realIp} {query["token"]} {query["name"]} websocket connection closed'
    )

    return ws
Ejemplo n.º 2
0
async def info(msg: TextMsg, *args):
    token = getToken(msg.guild_id)
    if token is None:
        await reply(msg, '未配置token')
    else:
        config = getServerConfig(token)
        if config is None:
            await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
        else:
            message = ''
            for functionType, function in config['function'].items():
                message += f'{functionType}:\n'
                for key in function.keys():
                    message += f' - {key}: {function[key]["enable"]}\n'
                    if 'channel_id' in function[key]:
                        if function[key]['channel_id'] != -1:
                            message += f'      channel_id: {function[key]["channel_id"]}\n'
            message += f'tellraw: {config["tellraw"]}\n'
            await reply(msg, message)
Ejemplo n.º 3
0
    return json.dumps(respData)


@app.route('/positions', methods=['GET'])
def positions():
    kite = getKite()
    positions = kite.positions()
    print('getKite positions => ', positions)
    return json.dumps(positions)


@app.route('/holdings', methods=['GET'])
def holdings():
    kite = getKite()
    holdings = kite.holdings()
    print('getKite holdings => ', holdings)
    return json.dumps(holdings)


# Execution starts here
initLoggingConfg()

serverConfig = getServerConfig()
logging.info('serverConfig => %s', serverConfig)

userConfig = getUserConfig()
logging.info('userConfig => %s', userConfig)

port = serverConfig['port']

app.run('localhost', port)
Ejemplo n.º 4
0
async def filter(msg: TextMsg, *args):
    token = getToken(msg.guild_id)
    if token is None:
        await reply(msg, '未配置token')
    else:
        adminPm = checkAdmin(token, int(msg.author_id))
        if adminPm is None:
            await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
        elif not adminPm:
            await reply(msg, '您无权使用该指令')
        else:
            if len(args) > 0:
                if args[0] == 'list':
                    config = getServerConfig(token)
                    if config is None:
                        await reply(
                            msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
                    else:
                        message = ''
                        for function in config['function']['receive']:
                            message += f'{function}: '
                            if len(config['function']['receive'][function]
                                   ['filter']) == 0:
                                message += '无\n'
                            else:
                                filterList = ''
                                for filter in config['function']['receive'][
                                        function]['filter']:
                                    filterList += f'{filter}, '
                                filterList = filterList[:-2]
                                message += f'{filterList}\n'
                        await reply(msg, message)
                elif args[0] == 'add':
                    if len(args) != 3:
                        await reply(
                            msg, '参数错误\n过滤关键词添加帮助: .filter add <功能名称> <关键词>')
                    else:
                        message = operationFilter(token, 'add', args[1],
                                                  args[2])
                        if message is None:
                            await reply(
                                msg,
                                '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
                        else:
                            await reply(msg, message)
                elif args[0] == 'del':
                    if len(args) != 3:
                        await reply(
                            msg, '参数错误\n过滤关键词移除帮助: .filter del <功能名称> <角色ID>')
                    else:
                        message = operationFilter(token, 'del', args[1],
                                                  args[2])
                        if message is None:
                            await reply(
                                msg,
                                '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
                        else:
                            await reply(msg, message)
                else:
                    message = '参数错误\n' \
                              'filter帮助:\n ' \
                              ' - filter list: 显示各功能的过滤关键词\n' \
                              ' - filter add <功能名称> <角色ID>: 添加该功能的过滤关键词\n' \
                              ' - filter del <功能名称> <角色ID>: 移除该功能的过滤关键词\n'
                    await reply(msg, message)
Ejemplo n.º 5
0
async def permission(msg: TextMsg, *args):
    token = getToken(msg.guild_id)
    if token is None:
        await reply(msg, '未配置token')
    else:
        adminPm = checkAdmin(token, int(msg.author_id))
        if adminPm is None:
            await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
        elif not adminPm:
            await reply(msg, '您无权使用该指令')
        else:
            if len(args) > 0:
                if args[0] == 'list':
                    config = getServerConfig(token)
                    if config is None:
                        await reply(
                            msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
                    else:
                        message = ''
                        roleData = await bot.get(
                            f'{API_URL}/guild-role/index?compress=0',
                            json={'guild_id': str(msg.guild_id)})
                        roleIdMapping = {}
                        for i in roleData:
                            roleIdMapping[str(i['role_id'])] = str(i['name'])
                        for function in config['permission']:
                            message += f'{function}: '
                            for roleId in config['permission'][function]:
                                roleId = str(roleId)
                                if roleId not in roleIdMapping:
                                    message += f'{roleId}(角色已被删除), '
                                else:
                                    message += f'{roleId}({roleIdMapping[roleId]}), '
                            if len(config['permission'][function]) != 0:
                                message = message[:-2] + '\n'
                            else:
                                message += '无\n'
                        await reply(msg, message)
                elif args[0] == 'add':
                    if len(args) != 3:
                        await reply(
                            msg, '参数错误\n权限添加帮助: .permission add <功能名称> <角色ID>')
                    else:
                        message = operationPermission(token, 'add', args[1],
                                                      args[2])
                        if message is None:
                            await reply(
                                msg,
                                '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
                        else:
                            await reply(msg, message)
                elif args[0] == 'del':
                    if len(args) != 3:
                        await reply(
                            msg, '参数错误\n权限删除帮助: .permission del <功能名称> <角色ID>')
                    else:
                        message = operationPermission(token, 'del', args[1],
                                                      args[2])
                        if message is None:
                            await reply(
                                msg,
                                '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理')
                        else:
                            await reply(msg, message)
                else:
                    message = '参数错误\n ' \
                              'permission帮助:\n' \
                              ' - permission list: 显示权限对应的角色名称及ID\n' \
                              ' - permission add <功能名称> <角色ID>: 给予角色对应权限\n' \
                              ' - permission del <功能名称> <角色ID>: 移除角色对应权限\n'
                    await reply(msg, message)
Ejemplo n.º 6
0
def start():
    #First, we get the basic information:
    info = config.getBasicInfo()
    MODE = info[0]
    lastTrigger = config.getLastTrigger()

    # Goal : Get basic config, load config, load tray and determine the TIMER
    if MODE == 0:
        EXERCISES_MODE, EXERCISES_SELECTED, NUMBER_TO_PICK_PER_SESSION, TIMER = info[
            1:]
        # Get List EXERCISES Config:
        ListEXERCISES = getListOfEXERCISES(EXERCISES_SELECTED)
        # Start STRAY as THREAD
        tray = Tray(MODE, TIMER, EXERCISES_MODE, EXERCISES_SELECTED)

    elif MODE == 1:
        EXERCISES_MODE, EXERCISES_SELECTED, NUMBER_TO_PICK_PER_SESSION, HOURS, MAXIMUM_NUMBER_OF_SESSIONS_PER_INTERVAL, RECUPERATION_TIME_SECONDS = info[
            1:]
        # Get List EXERCISES Config:
        ListEXERCISES = getListOfEXERCISES(EXERCISES_SELECTED)
        # Start STRAY as THREAD
        tray = Tray(MODE, [
            HOURS, MAXIMUM_NUMBER_OF_SESSIONS_PER_INTERVAL,
            RECUPERATION_TIME_SECONDS
        ], EXERCISES_MODE, EXERCISES_SELECTED)

        # Get current time and hour : determine TIMER

        HOURS.sort()
        expandedIntervals = [[j for j in range(*HOURS[i:i + 2])]
                             for i in range(0, len(HOURS), 2)]
        currentDT = datetime.datetime.now()
        n = 0
        if lastTrigger == None:
            lastTrigger = [0, -1]
            notify(
                "Workout Starter Pack",
                "Error: Couldn't get the last trigger from config. Switching to [0, -1] by default.",
                5)

        for i in range(len(expandedIntervals)):
            expandedInterval = expandedIntervals[i]
            if currentDT.hour in expandedInterval:

                if lastTrigger[
                        0] < MAXIMUM_NUMBER_OF_SESSIONS_PER_INTERVAL and lastTrigger[
                            1] == i:
                    TIMER = RECUPERATION_TIME_SECONDS
                    lastTrigger = [lastTrigger[0] + 1, i]

                elif lastTrigger[1] != i:
                    lastTrigger = [1, i]
                    TIMER = 5

                else:
                    nextHour = HOURS[0]
                    nextDay = datetime.datetime(currentDT.year,
                                                currentDT.month,
                                                currentDT.day + 1).day

                    for i in HOURS[::2]:
                        if i > currentDT.hour:
                            nextHour = i
                            nextDay = currentDT.day

                    nextDateTime = datetime.datetime(currentDT.year,
                                                     currentDT.month, nextDay,
                                                     nextHour, 0)
                    TIMER = (nextDateTime - currentDT).total_seconds()
                    print(
                        "Skipping to next interval because finished this one")
                    # config.updateLastTrigger(0, -1)
            else:
                n += 1

        # Update current interval and interation in config if currentDT not in any interval
        if n == len(expandedIntervals):
            print("Not in any intverval")
            lastTrigger = [0, -1]
            nextHour = HOURS[0]
            nextDay = datetime.datetime(currentDT.year, currentDT.month,
                                        currentDT.day + 1).day

            for i in HOURS[::2]:
                if i >= currentDT.hour:
                    nextHour = i
                    nextDay = currentDT.day

            nextDateTime = datetime.datetime(currentDT.year, currentDT.month,
                                             nextDay, nextHour, 0)
            TIMER = (nextDateTime - currentDT).total_seconds()

    # Notify for the user of what was done
    if len(ListEXERCISES) == 0:
        notify(
            "Workout Starter Pack",
            "Error: no exercises loaded. Please look at the configuration file. Quitting.",
            5)
        sys.exit(0)

    # EXERCISES_MODE :
    if EXERCISES_MODE == 1:
        shuffle(ListEXERCISES)
    ListEXERCISES = ListEXERCISES[:NUMBER_TO_PICK_PER_SESSION]

    # Notify of the next session's content
    names = [i[0] for i in ListEXERCISES]
    notify(
        "Workout Starter Pack",
        str(len(ListEXERCISES)) + " exercise(s) loaded!\nWaiting " +
        str(int(TIMER)) + " seconds. \nNext Session : " + " ".join(names), 5)

    # Starting the tray
    tray.init_icon_tray()

    # Sleep TIMER seconds
    time.sleep(TIMER)

    # Redirect the keys and mouse events
    print("Redirecting keys events...")
    inputs = config.getInputsConfig()
    keyboard = Thread(target=lambda: init_keyboard(*inputs))
    keyboard.start()

    # Run the server
    PORT = config.getServerConfig()
    if (has_internet()):
        notify("Workout Starter Pack",
               ((EXERCISES_MODE == 0) and "Ordered" or "Randomized") +
               " sequence :\n  - " + "\n  - ".join(names), 5)
        run(lastTrigger, ListEXERCISES, PORT, tray)
    else:
        notify(
            "Workout Starter Pack",
            "No internet connection (needed for the webserver)! Stopping...",
            5,
            threaded=False)