Esempio n. 1
0
    def play_manu(self):
        choices = {
            'go back': '0',
        }
        while True:
            time.sleep(1)
            render(start_menu.select_characters)
            choice = input(':')
            try:
                if choice == choices['go back']:
                    return
                else:
                    date = datetime.datetime
                    name_file = f'{conf.database_dir}\\{choice}_{date.year}_{date.month}_{date.day}_{date.hour}_{date.min}_{date.second}.json'
                    i = 0
                    while os.path.exists(name_file):
                        name_file = f'{name_file}_{i}'
                        i += 1

                    with open(name_file, 'w') as f:
                        json.dump({'name': choice}, f)

                    return self.select_characters()
            except:
                print(error())
Esempio n. 2
0
    def select_name(self):
        choices = {
            'go back': '0',
        }
        while True:
            time.sleep(1)
            render(start_menu.select_name)
            choice = input(':')
            try:
                if choice == choices['go back']:
                    return
                else:
                    date = datetime.datetime
                    name_file = f'{conf.database_dir}\\{choice}_{date.year}_{date.month}_{date.day}_{date.hour}_{date.min}_{date.second}.json'
                    i = 0
                    while os.path.exists(name_file):
                        name_file = f'{name_file}_{i}'
                        i += 1

                    self.game.data['name'] = choice
                    self.game.file = name_file
                    self.game.save()

                    return self.select_characters()
            except:
                print(error())
Esempio n. 3
0
async def mainloop(session: ClientSession):
    while True:
        try:
            print('getting from fortnite-api')
            if not os.path.exists('./json'):
                os.mkdir('json')
            async with session.get('https://fortnite-api.com/cosmetics/br/') as resp:
                data = (await resp.json())['data']
            async with session.get('https://fortnite-api.com/v1/banners') as resp:
                banners = (await resp.json())['data']
            async with session.get('https://benbot.app/api/v1/newCosmetics') as resp:
                _newitems = (await resp.json())['items']
            async with session.get('https://cdn2.unrealengine.com/Kairos/data/avatars.json') as resp:
                _avatars = await resp.json()
            newitems = []
            for item in _newitems:
                newitems.append({
                    'name':item['name'],
                    'description':item['description'],
                    'id':item['id'],
                    'rarity':item['rarity'].lower(),
                    'images':{
                        'icon':{
                            'url':item['icons']['icon']
                        }
                    }
                })
            avatars=[]
            for avatarid in _avatars.keys():
                avatars.append({
                    'name':_avatars[avatarid],
                    'description':'',
                    'id':avatarid,
                    'rarity':'common',
                    'images':{
                        'icon':{
                            'url':f'https://cdn2.unrealengine.com/Kairos/portraits/{avatarid}.png?preview=1'
                        }
                    }
                })
            async def _save(t: str, data: list):
                async with aiofiles.open(f'json/{t}.json', 'w', encoding='utf-8') as f:
                    await f.write(json.dumps(sorted([i for i in data if i["type"] == t], key=lambda x:x['id'], reverse=False), indent='    '))
                print('saved:', t, end='          \r')
            async def _save2(filename: str, data): # :list | dict
                async with aiofiles.open(f'json/{filename}.json', 'w', encoding='utf-8') as f:
                    if isinstance(type(data), list):data.sort()
                    await f.write(json.dumps(sorted(data, key=lambda x:x['id'], reverse=False) if isinstance(type(data), dict) else data, indent='   '))
                print('saved:', filename, end='          \r')
            await gather(*[_save(t, data) for t in types], _save2('all', data), _save2('banners', banners), _save2('newitems', newitems), _save2('avatars', avatars))
            await sleep(600)
        except Exception as e:
            print('Exception in mainloop:', e)
            print(error())
            await sleep(15)
            continue
Esempio n. 4
0
 def start(self):
     choices = {
         'quit': '0',
         'new game': '1',
         'load game': '2'
     }
     while True:
         time.sleep(1)
         render(start_menu.start_menu)
         choice = input(':')
         try:
             if choice == choices['quit']:
                 self.game.exit()
             elif choice == choices['new game']:
                 self.select_name()
             elif choice == choices['load game']:
                 self.load_game()
             else:
                 print('invalid choice, try again', end='\r')
         except:
             print(error())
Esempio n. 5
0
    def select_characters(self):
        choices = {
            'go back': '0',
        }
        for i, player in enumerate(players):
            choices[player.__class__.__name__] = str(i+1)
        characters = ''.join([f'({i+1}) {player.__class__.__name__}' for i, player in enumerate(players)])

        while True:
            time.sleep(1)
            render(start_menu.select_characters+characters)
            choice = input(':')
            try:
                if choice == choices['go back']:
                    return
                elif choice in choices.values():
                    self.game.data['character'] = choice
                    self.game.save()
                    self.play_manu()
                else:
                    print('invalid choice, try again', end='\r')
            except:
                print(error())
Esempio n. 6
0
def reload(self, context, modules):
    global prev
    addons = addon_utils.addons_fake_modules

    os.system('cls')
    try:
        for addon_name in modules:
            disable(addon_name)
            addon_utils.disable(module_name=addon_name)
            os.system("cls")
    except:
        os.system("cls")
        self.report({'INFO'}, f"Error: Addon['{modules}'] failed to disable")
        error()

    for addon_name in modules:
        try:
            addon = sys.modules.get(addon_name)
            if addon is None or addon.__spec__ is None:
                self.report({
                    'INFO'
                }, f"Error: could not find addon['{addon_name}'] in sys.modules"
                            )
                print(
                    f"Error reloading {addon_name}, not found in sys.modules")
                continue
                # if not addons.get(addon_name):
                # self.report({'INFO'}, message="Addon not available")
                # continue
                # try:
                # print(f"Addon ['{addon_name}'] not found in system, but still exists. \nDefaulting to addon operators for reload.")
                # disable(addon_name)
                # refresh(addon_name)
                # enable(addon_name)
                # except:
                # self.report({'INFO'}, f"Error: Addon['{addon_name}'] failed to initialize or reload")
                # error()
                # continue

            if len(modules) == 1 or addon_name == modules[0]:
                print(f"Reloading {addon_name}")
                if addon_name != prev:  # Print filepath when selecting a new addon
                    print(f"\t{addon.__file__}")

            (root, folder) = Get.path(addon)
            if folder is not None:  # Is folder addon
                for sub_name in sys.modules:
                    sub_addon = sys.modules[sub_name]
                    (file, sub_folder) = Get.path(sub_addon)
                    if file is None or not file.startswith(
                            folder) or sub_addon.__spec__ is None:
                        continue
                    try:
                        importlib.reload(sub_addon)
                    except:
                        self.report({
                            'INFO'
                        }, f"Error: Sub Module['{sub_name}'] failed to reload")
                        error()
            # TODO: folders using dots in name would reload too, despite being two separate base folders:
            #   ex: ["scripts/addon/files", "scripts/addon.different_folder/files"]
            importlib.reload(addon)
            enable(addon_name)
        except:
            self.report({'INFO'},
                        f"Error: Addon['{addon_name}'] failed to reload")
            error()

    prev = modules[0]
Esempio n. 7
0
# Об ошибке , которая произошла в коде, который ниже, никто никогда не узнает, но бот перестанет работать.
# Поэтому сохраняйте этот код без изменений. Это гарант того, что в
# основном файле можно делать любые ошибки и это не смертельно.

chdir('/'.join(abspath(argv[0]).split('/')[:-1]))
try:
    token_vk = open('../kpml.bot.token_vk').read()
except BaseException:
    token_vk = ''
while True:
    system('git pull --no-edit')
    try:
        exec(open('./kpml.bot.py').read())
        q = ''
    except BaseException:
        q = str(error())
    if q:
        try:
            a = open('../kpml.bot.error').read()
        except BaseException:
            a = str(time() - 400) + '\x08'
        try:
            bt = float(a.split('\x08')[0])
        except BaseException:
            bt = time() - 400
        if time() - float(bt) > 100 or '\x08'.join(a.split('\x08')[1:]) != q:
            try:
                for w in admin:
                    sleep(1 / 3)
                    url = 'https://api.vk.com/method/messages.send?random_id='
                    url += str(time()).replace('.', '0')