Ejemplo n.º 1
0
def main():
    bot_home = os.path.dirname(os.path.abspath(__file__))

    with open(os.path.join(bot_home, 'config/config.json'), 'r') as conf:
        config = json.loads(conf.read())
        log.info("Loaded file with configurations")
    with open(os.path.join(bot_home, 'config/credentials.json'), 'r') as creds:
        credentials = json.loads(creds.read())
        log.info("Loaded file with credentials")
    with open(os.path.join(bot_home, 'config/messages.json'), 'r') as msg:
        messages = json.loads(msg.read())
        log.info("Loaded file with messages")

    bot = Bot(config, credentials, messages, bot_home, log)
    log.info("Bot initialized")

    while True:
        try:
            bot.check_messages()
            bot.check_unkicked()
            bot.check_intruders()
            bot.check_friends()
            #bot.check_news()
            time.sleep(1)

        except KeyboardInterrupt:
            log.error("Shutdown...")
            raise
Ejemplo n.º 2
0
def root(stream_log):
    bot = Bot()

    logging.getLogger('discord').setLevel(logging.INFO)

    log_dir = Path(os.path.dirname(__file__)).parent / 'logs'
    log_dir.mkdir(exist_ok=True)

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    file_handler = logging.FileHandler(
        filename=
        f'../logs/2b-py.{datetime.now().strftime("%d%m%y-%H%M%S")}.log',
        encoding='utf-8',
        mode='w')

    formatter = logging.Formatter(
        '[{levelname}] ({asctime}) - {name}:{lineno} - {message}',
        '%Y-%m-%d %H:%M:%S',
        style='{')
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    if stream_log:
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)

    try:
        bot.run()
    except KeyboardInterrupt:
        bot.loop.create_task(bot.logout())
Ejemplo n.º 3
0
 async def add_users(self, ctx):
     if (Bot.is_levels_empty()):
         await ctx.send("Devi prima inserire i livelli")
         return
     Bot.add_users()
     await ctx.send(
         "Tutti gli utenti del server tranne i bot sono stati aggiunti con successo"
     )
Ejemplo n.º 4
0
async def on_ready():
    guild = discord.utils.get(client.guilds, name=GUILD)
    Bot.set_guild(guild)
    Bot.set_client(client)
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )
Ejemplo n.º 5
0
 async def rank(self, ctx):
     rank = int(await Bot.get_rank(ctx.message.author.id))
     level = int(await Bot.get_level(ctx.message.author.id))
     max_xp = int(Bot.get_max_xp(ctx.message.author.id))
     reward = Bot.get_reward(level)
     reward_name = str(Bot.get_role_name(reward))
     uptime = round(rank * 60,1)
     text_uptime = ''
     if(uptime == 0):
         text_uptime = 'Nessuna attività'
     elif(uptime < 1):
         text_uptime = 'Pochi secondi'
     else:
         if(uptime > 60):
             uptime = round(uptime/60,1)
             if(uptime > 60):
                 uptime = round(uptime/60,1)
                 if(uptime == 1):
                     text_uptime = str(uptime) + " ora"
                 else:
                     text_uptime = str(uptime) + " ore"
                 if(uptime > 24):
                     uptime = round(uptime/24,1)
                     if(uptime == 1):
                         text_uptime = str(uptime) + " giorno"
                     else:
                         text_uptime = str(uptime) + " giorni"
             else:
                 if(uptime == 1):
                     text_uptime = str(uptime) + " minuto"
                 else:
                     text_uptime = str(uptime) + " minuti"
         else:
             if(uptime == 1):
                 text_uptime = str(uptime) + " secondo"
             else:
                 text_uptime = str(uptime) + " secondi"
         
     embed=discord.Embed(
         title=ctx.author.name,
         description= 'Ecco il tuo punteggio',
         colour = discord.Colour.blue()
     )
     embed.set_thumbnail(url=ctx.author.avatar_url)
     embed.add_field(name="Livello", value=str(level), inline=True)
     embed.add_field(name="Punti", value=str(rank) + ' XP', inline=True)
     embed.add_field(name="Uptime", value=text_uptime , inline=True)
     if not(level == Bot.get_max_level_number() and rank > max_xp):
         embed.add_field(name="Completamento livello", value=str(max_xp) + ' XP' , inline=False)
         embed.add_field(name="Ruolo ricompensa", value=reward_name , inline=False)
     else:
         embed.add_field(name="Tutti i livelli sono completati!", value='Complimenti, goditi il potere' , inline=False)
     await ctx.send(embed = embed)
    def __init__(self, acc):  # acc为账户名
        # 此处为兼容连接
        self._bot = Bot()
        self.server_bot = self._bot.server_bot
        os.makedirs("log", exist_ok=True)
        self.acc_name = acc  # 账户名
        # self.acc_message[self.acc_name] = []
        # self.clean()

        self.norm_log = logging.getLogger(acc)
        self.norm_log.setLevel('INFO')  # 设置日志级别
        self.norm_hdl_std = logging.StreamHandler(stdout)
        self.norm_hdl_std.setLevel('INFO')  # 设置Handler级别

        self.norm_hdl = logging.FileHandler(os.path.join(
            self.dst_folder, '%s.log' % (acc)),
                                            encoding='utf-8')
        self.norm_hdl.setLevel('INFO')

        self.norm_fomatter = logging.Formatter(
            '%(asctime)s\t%(name)s\t--%(levelname)s\t%(message)s')  # 设置输出格式
        self.norm_hdl_std.setFormatter(self.norm_fomatter)

        self.norm_hdl.setFormatter(self.norm_fomatter)
        if not self.norm_log.handlers:
            self.norm_log.addHandler(self.norm_hdl_std)
            self.norm_log.addHandler(self.norm_hdl)
Ejemplo n.º 7
0
def config_init(args):
    config_root = os.environ['FPTBOT_CONFIG']
    
    bot = Bot(root=config_root, level=logging.INFO)
    bot.init(runlevel.LOCAL_FILESYSTEM)
    
    logger = logging.getLogger('tools.config')
    
    def _init(identifier, object):
        logger.info('initializing configuration: %s', identifier)
        
        object.init(object.default_values())
        object.save()
    
    if args.identifier is None:
        for (identifier, object) in bot.get_configs().items():
            _init(identifier, object)
    
    else:
        identifier = args.identifier
        
        try:
            object = bot.get_config(identifier)
            
            _init(identifier, object)
        
        except KeyError:
            logger.critical('invalid identifier: %s', identifier)
            
    bot.init(runlevel.HALT)
Ejemplo n.º 8
0
async def edit_user_role(user_id):
    level_id = User.get_level(user_id)
    if level_id > 1:
        role_prev_id = Level.get_reward(level_id - 1)
        user_roles = Bot.get_user_roles(user_id)
        for role in user_roles:
            if(role.id == role_prev_id):
                await Bot.delete_user_role(user_id, role.id)
    role_id = Level.get_reward(level_id)
    await Bot.apply_user_role(user_id, role_id)
Ejemplo n.º 9
0
    async def start(self, ctx):
        if (Bot.state):
            embed = discord.Embed(title="Levelup",
                                  description="levelup è già in funzione",
                                  colour=discord.Colour.blue())
            await ctx.send(embed=embed)
            return
        if (Bot.is_ready()):
            Bot.turn_on()
            embed = discord.Embed(title="Levelup",
                                  description="levelup ora è in funzione",
                                  colour=discord.Colour.blue())
        else:
            embed = discord.Embed(
                title="Levelup",
                description=
                "Il bot non può essere avviato\n.help per la lista degli aiuti",
                colour=discord.Colour.blue())

        await ctx.send(embed=embed)
Ejemplo n.º 10
0
    def __init__(self, acc):  # acc为账户名
        # 此处为兼容连接
        self._bot = Bot()
        self.server_bot = self._bot.server_bot
        os.makedirs("log", exist_ok=True)
        self.acc_name = acc  # 账户名
        # self.acc_message[self.acc_name] = []
        # self.clean()

        self.norm_log = logging.getLogger(acc)
        self.norm_log.setLevel('DEBUG')  # 设置日志级别
        self.norm_hdl_std = logging.StreamHandler(stdout)
        if debug:
            self.norm_hdl_std.setLevel('DEBUG')  # 设置Handler级别
        else:
            self.norm_hdl_std.setLevel('INFO')  # 设置Handler级别

        # self.norm_hdl = logging.FileHandler(os.path.join(self.dst_folder, '%s.log' % acc), encoding='utf-8')
        # self.norm_hdl.setLevel('INFO')

        if colorlogsw:
            self.norm_fomatter = colorlog.ColoredFormatter('%(log_color)s[%(asctime)s]\t'
                                                           '[%(name)s] \t%(message)s',
                                                           log_colors=self.log_colors_config)
        else:
            self.norm_fomatter = logging.Formatter('[%(asctime)s]\t[%(name)s]\t%(message)s')  # 设置输出格式

        # 创建一个FileHandler,用于写到本地
        # maxBytes=1024 * 1024 * 5, backupCount=5,
        self.fhbacker = RotatingFileHandler(filename=os.path.join(self.dst_folder, '%s.log' % acc),
                                            mode='a+', encoding='utf-8')  # 使用RotatingFileHandler类,滚动备份日志
        self.fhbacker.setLevel('DEBUG')
        self.fhbacker.setFormatter(self.norm_fomatter)

        self.norm_hdl_std.setFormatter(self.norm_fomatter)
        # self.norm_hdl.setFormatter(self.norm_fomatter)

        if not self.norm_log.handlers:
            self.norm_log.addHandler(self.norm_hdl_std)
            # self.norm_log.addHandler(self.norm_hdl)
            self.norm_log.addHandler(self.fhbacker)
Ejemplo n.º 11
0
def main() -> None:
    # create the argument parser
    ap = argparse.ArgumentParser(prog="CryptoHFT.py")
    ap.add_argument("-w", "--warranty",
                    help="shows the details about the warranty.",
                    action="store_true")
    ap.add_argument("-c", "--conditions",
                    help="shows the details about the redistribution.",
                    action="store_true")
    ap.add_argument("-i", "--init",
                    help="create a new configuration.",
                    action="store_true")

    # retrieve the arguments
    args = ap.parse_args()

    # check if the -w flag or the -c flag has been written
    shownWarrantyOrConditions = False
    if args.conditions:
        printConditions()
        shownWarrantyOrConditions = True

    if args.warranty:
        printWarranty()
        shownWarrantyOrConditions = True

    if shownWarrantyOrConditions:
        sys.exit(0)

    # shows the license
    printLicense()

    # check if it's necessary to create a new configuration file
    if args.init:
        Configuration.createConfiguration(CONFIG_FILE_PATH)

    # load the configuration
    userConfig = Configuration(CONFIG_FILE_PATH)

    # create the bot object
    bot = Bot(userConfig)

    # setup the bot
    bot.setup()

    # enter the trade loop
    bot.tradeLoop()
Ejemplo n.º 12
0
def config_write(args):
    config_root = os.environ['FPTBOT_CONFIG']
    
    bot = Bot(root=config_root, level=logging.INFO)
    bot.init(runlevel.LOCAL_FILESYSTEM)
    
    logger = logging.getLogger('tools.config') 
    
    identifier = args.identifier
    key = args.key
    type = args.type
    value = args.value
    
    try:
        object = bot.get_config(identifier)
        
    except KeyError:
        logger.critical('invalid identifier: %s', identifier)
        
    if key not in object.valid_keys():
        logger.critical('invalid key: %s', key)
        return
        
    
    value = ' '.join(value)
    
    if type == 'int':
        new_value = int(value)
        
    elif type == 'bool':
        new_value = bool(value)
        
    elif type == 'list':
        new_value = value.split(',')
    
    else:
        new_value = value
    
    
    object.set(key, new_value)
    object.save()
    
    logger.info('%s.%s set to %s', identifier, key, new_value)
    
    bot.init(runlevel.HALT)
Ejemplo n.º 13
0
def config_read(args):
    config_root = os.environ['FPTBOT_CONFIG']
    
    bot = Bot(root=config_root, level=logging.INFO)
    bot.init(runlevel.LOCAL_FILESYSTEM)
    
    logger = logging.getLogger('tools.config')
    
    identifier = args.identifier
    
    def _read(identifier, key, value, padding=0):
        print "{}.{} {}= '{}' ({})".format(identifier, key, ' ' * padding, value, type(value))
    
    try:
        object = bot.get_config(identifier)
    except KeyError:
        logger.critical('invalid identifier: %s', identifier)
        return
        
    if(args.key is None):
        spacelist = [len(item) for item in object.get_all().keys()]
        
        if spacelist:
            space = max(spacelist)
        else:
            space = 0
        
        for (key, value) in object.get_all().items():
            _read(identifier, key, value, (space - len(key)))
        
    else:
        try:
            key = args.key
            value = object.get(key)
        except KeyError:
            logger.critical('invalid key: %s', key)
            return
            
        _read(identifier, key, value)
    
    bot.init(runlevel.HALT)
Ejemplo n.º 14
0
def test_bot_send_valid_command(valid_bot: Bot):
    response = valid_bot.invoke_command(ALL_COMMANDS.GET_ME)
    data = response.json()
    assert response.status_code == requests.codes.ok
    assert data['ok']
Ejemplo n.º 15
0
def test_bot_init_raises_with_invalid_token():
    with pytest.raises(exceptions.HTTPConnectionError):
        Bot(API_INVALID_TOKEN)
Ejemplo n.º 16
0
def test_bot_init_valid():
    bot = Bot(API_VALID_TOKEN)

    assert bot.token == API_VALID_TOKEN
Ejemplo n.º 17
0
def start():
    start_time = time.time()
    bot = Bot()
    module_manager = ModuleManager()
    logger.log(
        2, "Starting %s bot with %s %s" %
        (colored("Fusion", "magenta"), colored("Discord API", "blue"),
         colored("v" + discord.__version__, "green")))
    logger.info("Setting up django")
    django.setup()
    logger.info(
        "Loading modules from \"%s\" and \"core/modules\" directories" %
        modules_dir)
    load_modules_from_dir("core/modules", ignore={"TemplateModule"})
    load_modules_from_dir(modules_dir)

    module_manager.initialize(bot)
    logger.info("Setting up django models")
    for app in INSTALLED_APPS:
        call_command("makemigrations", app.split(".")[-1:][0])
    call_command("migrate")
    logger.info("Connecting to discord")

    @bot.event
    async def on_ready():
        logger.info("Logged into Discord as \"%s\"." % bot.user.name)
        logger.info("Running modules..")
        await module_manager.run_modules(bot)
        logger.info("Deploying threads and starting protocol processing")
        core.protocol.deploy()

        print("")
        logger.log(
            2,
            "INIT FINISHED! (took %ss)" % math.floor(time.time() - start_time))
        logger.log(2, "Loaded Modules: %s" % module_manager.modules_count)
        logger.log(2, "Loaded Commands: %s" % module_manager.commands_count)
        logger.log(
            2, "Listening %s:%s" %
            (listen_ip if listen_ip != "" else "0.0.0.0", listen_port))
        print("")

    @bot.event
    async def on_message(message: discord.Message):
        for mod in sorted(module_manager.modules.values(),
                          key=lambda x: x.on_message.priority):
            await mod.on_message(message, bot)
        if not message.content.startswith(cmd_prefix):
            return

        if message.author.bot:
            return
        args = message.content.split()
        cmd = args.pop(0)[len(cmd_prefix):].lower()

        if cmd not in module_manager.commands:
            # await bot.send_error_embed(message.channel, "Команда \"%s\" не найдена." % cmd,
            #                            "Команда не найдена")
            return

        command = module_manager.commands[cmd]
        if command.guild_lock and message.guild.id not in command.guild_lock:
            await bot.send_error_embed(
                message.channel,
                "Команда \"%s\" недоступна на данном сервере." % cmd,
                "Команда не найдена")
            return
        logger.info(
            "Выполнение команды %s от %s (%s)." %
            (repr(message.content), str(message.author), message.author.id))
        try:
            args_1, keys = parse(args)
            if not module_manager.check_permissions(message.author.guild_permissions, command.permissions) \
                    or not module_manager.check_sp_permissions(message.author.id, command.future_permissions):
                embed: discord.Embed = bot.get_error_embed(
                    "У вас недостаточно прав для выполнения данной команды",
                    "Нет прав!")
                required_perms = "\n".join(
                    perm.special_name for perm in
                    sorted(command.permissions, key=lambda x: x.value) +
                    sorted(command.future_permissions, key=lambda x: x.value))
                embed.add_field(name="Необходимые права:",
                                value=required_perms)
                await message.channel.send(embed=embed)
                await message.add_reaction(emoji_warn)
                return
            async with message.channel.typing():
                result = await command.execute(message, args_1, keys)
        except ParseError as e:
            await message.add_reaction(emoji_warn)
            await bot.send_error_embed(message.channel, str(e),
                                       "Ошибка разбора аргументов")
        except discord.Forbidden:
            await message.add_reaction(emoji_error)
            await bot.send_error_embed(message.channel, "У бота нет прав!")
        except AccessDeniedException:
            await message.add_reaction(emoji_warn)
            await bot.send_error_embed(
                message.channel,
                "У вас недостаточно прав для выполнения данной команды",
                "Нет прав!")
        except CommandException as e:
            await message.add_reaction(emoji_warn)
            await bot.send_error_embed(message.channel, str(e), e.title)
        except OpenComputersError as e:
            await bot.send_error_embed(message.channel,
                                       "```\n%s\n```" % str(e),
                                       "⚠ Криворукий уебан, у тебя ошибка! ⚠")
            await message.add_reaction(emoji_error)
        except Exception:
            await bot.send_error_embed(message.channel,
                                       "```\n%s\n```" % traceback.format_exc(),
                                       "⚠ Криворукий уебан, у тебя ошибка! ⚠")
            await message.add_reaction(emoji_error)
        else:
            if result == CommandResult.success:
                await message.add_reaction(emoji_ok)
            elif result == CommandResult.arguments_insufficient:
                embed: discord.Embed = bot.get_error_embed(
                    title="Недостаточно аргументов!")
                embed.add_field(name="%s%s %s" %
                                (cmd_prefix, command.name, command.arguments),
                                value=command.description)
                await message.channel.send(embed=embed)
                await message.add_reaction(emoji_warn)

    @bot.event
    async def on_message_delete(message: discord.Message):
        for _, mod in list(module_manager.modules.items()):
            await mod.on_message_delete(message, bot)

    @bot.event
    async def on_message_edit(before: discord.Message, after: discord.Message):
        for _, mod in list(module_manager.modules.items()):
            await mod.on_message_edit(before, after, bot)

    @bot.event
    async def on_member_remove(member: discord.Member):
        for _, mod in list(module_manager.modules.items()):
            await mod.on_member_remove(member, bot)

    @bot.event
    async def on_member_join(member: discord.Member):
        for _, mod in list(module_manager.modules.items()):
            await mod.on_member_join(member, bot)

    bot.run(discord_token)
import time

from core.bot import Bot

bot = Bot()


def test_get_path():
    print("=== test path ===")
    print("bot.main_path: ", bot.main_path)
    print("bot.img_path: ", bot.img_path)


def test_grab_image():
    print("=== test grab image ===")
    bot.grab_img()
    print("=== grab image OK! ===")


def test_mouse_click():
    print("=== test mouse click ===")
    cord = (50, 50)
    print("mouse click at (x, y): ", cord)
    bot.mouse_click(cord)


def test_start_game():
    print("=== test start game ===")
    bot.start_game()

Ejemplo n.º 19
0
async def on_member_join(member):
    Bot.add_users()
Ejemplo n.º 20
0
    def RunTasks(self,
                 tasks: dict,
                 continue_=True,
                 max_retry=3,
                 first_init_home=True,
                 rec_addr="rec"):
        """
        运行任务集
        By TheAutumnOfRice 2020-07-26
        2020-7-27 Fix: 把tasks参数放在外面读,防止多进程同时读某一个文件造成的问题
        :param tasks: 合法的任务字典
        :param continue_: 是否继续上次未完成的任务
        :param max_retry:  最大试错次数,超过max_retry却还不停报错则只能下次再见!
        :param first_init_home: 是否一开始执行init_home。
        :param rec_addr: 记录文件存放目录
        """
        user = self.AR.getuser()  # 获取配置文件
        account = user["account"]
        password = user["password"]
        check_task_dict(tasks, True)
        self.ms = moveset(account, rec_addr)  # 创建行为列表用于断点恢复
        self.ms.startw(None, start=True)  # 使用自动序列创建的起手式

        def funwarper(funname, title, kwargs):
            # 将funname包装为一个函数,调用self.funname(**kwargs)
            def fun(var):
                # var参数:用于断点恢复的变量
                # 使用try来保证兼容性:如果函数没有var参数,则不传入var参数。
                self.log.write_log("info", f"正在执行: {title} 记录存放目录: {rec_addr}")
                # 标记当前执行的位置!
                self.task_current(title)
                # 防止泄露全局影响
                self.ES.FCs.clear()  # 清除全部ES
                self.headers_group.clear()  # 清除全部header
                self.register_basic_ES()
                self.prechecks.clear()
                self.enable_precheck = True
                flag = False
                try:
                    self.__getattribute__(funname)(**kwargs, var=var)
                except TypeError as e:
                    if debug:
                        self.log.write_log(
                            "debug",
                            f"Catch Type Error:{e} - {funname} - {kwargs}")
                    flag = True
                    if 'var' not in str(e):
                        raise e
                if flag:
                    self.__getattribute__(funname)(**kwargs)

            return fun

        self.log.write_log("info", f"任务列表:")
        # 解析任务列表
        self._task_index = {}
        for task in tasks["tasks"]:
            typ = task["type"]

            if "__disable__" in task:
                # 存在禁用配置
                if task["__disable__"] is True:
                    typ = "nothing"  # 直接禁用
                elif task["__disable__"] is not False:
                    # 有开关
                    FLAGS = list_all_flags()
                    detail = None
                    for flag, details in FLAGS.items():
                        if task["__disable__"] == flag:
                            detail = details
                            break
                    if detail is not None:
                        use_default = True
                        if self.account in detail["user"] and detail["user"][
                                self.account] is True:
                            typ = "nothing"  # 针对用户特殊:直接禁用
                            use_default = False
                        elif self.account in detail["user"] and detail["user"][
                                self.account] is False:
                            use_default = False
                        else:
                            # 针对组特殊:
                            for group, set in detail["group"].items():
                                if is_in_group(self.account, group):
                                    if set is False:
                                        use_default = False
                                    else:
                                        typ = "nothing"
                                        use_default = False
                                    break
                        if use_default:
                            # 使用默认设置
                            if detail["default"] is True:
                                typ = "nothing"

            cur = VALID_TASK.T[typ]
            kwargs = {}
            if typ != "nothing":  # 未禁用
                for param in task:
                    if param == "type":
                        continue
                    if param == "__disable__":
                        continue
                    kwargs[param] = task[param]
            for v_p in cur["params"]:  # Valid Param: Default Param
                if v_p.default is not None and v_p.key not in kwargs:
                    kwargs[v_p.key] = v_p.default

            idx = self.ms.nextwv(
                funwarper(cur["funname"], cur['title'], kwargs))  # 自动创建序列
            if typ != "nothing":
                self.log.write_log("info", f"  +任务 {cur['title']}")  # 打印该任务
                for key in kwargs:
                    self.log.write_log("info", f"    参数 {key} : {kwargs[key]}")
                self._task_index[idx] = cur['title']
        self.ms.exitw(None)  # 结束自动序列创建
        # 未知异常:仍然是重启哒!万能的重启万岁!
        last_exception = None
        before_ = True
        retry = 0
        while retry <= max_retry:
            try:
                if before_:
                    self.task_current("登录")
                    _return_code = self.login_auth(account, password)
                    if _return_code == -1:
                        # 标记错误!
                        self.task_error(str('%s账号出现了验证码' % self.account))
                        if captcha_skip:
                            self.fix_reboot(False)
                            return False
                    if continue_ is False:
                        # 初次执行,记录一下
                        self.task_start()
                    if first_init_home:
                        self.init_home()  # 处理第一次进home的一系列问题
                    before_ = False
                try:
                    self.ms.run(continue_=continue_)
                except UnknownMovesetException as e:
                    pcr_log(account).write_log(
                        "warning", message=f'记录文件冲突,自动刷新运行记录:{str(e)}')
                    self.ms.run(continue_=False)
                # 刷完啦!标记一下”我刷完了“
                self.task_finished()
                return True
            except ForceKillException as e:
                pcr_log(account).write_log(level='info', message=f'强制终止')
                try:
                    self.fix_reboot(False)
                except:
                    pcr_log(account).write_log(level='warning',
                                               message=f'强制终止-重启失败!')
                raise e
            except FastScreencutException as e:
                pcr_log(account).write_log(
                    level='error', message=f'快速截图出现错误,{str(e)},尝试重新连接……')
                self.fix_reboot(not before_)
                self.init_fastscreen()
            except OfflineException as e:
                pcr_log(account).write_log('error',
                                           message=f'main-检测到设备离线:{str(e)}')
                return False
            except ReadTimeoutException as e:
                pcr_log(account).write_log(
                    'error', message=f'main-检测到连接超时,{str(e)},尝试重新连接……')
                self.init_device(self.address)
            except BadLoginException as e:
                pcr_log(account).write_log('error',
                                           message=f'main-严重登录错误,{e}跳过账号!')
                self.task_error(str(e))
                self.fix_reboot(False)
                return False
            except Exception as e:
                retry += 1
                try:
                    os.makedirs(f"error_screenshot/{account}", exist_ok=True)
                    nowtime = datetime.datetime.strftime(
                        datetime.datetime.now(), "%Y%m%d_%H%M%S")
                    target = f"error_screenshot/{account}/{nowtime}_RT{retry}.jpg"
                    cv2.imwrite(target, self.last_screen)
                    pcr_log(account).write_log(level="error",
                                               message=f"错误截图已经保存至{target}")
                    # 错误截图日志为0级消息,后面可能会改成warning级别或者error
                    Bot().server_bot(
                        '', '', '', self.last_screen, f"模拟器:{self.address}\n"
                        f"账号:{self.account}的运行错误重启截图\n"
                        f"错误原因:{str(e)}")
                except Exception as es:
                    pcr_log(account).write_log(level="error",
                                               message=f"错误截图保存失败:{str(es)}")
                if trace_exception_for_debug:
                    tb = traceback.format_exc()
                    pcr_log(account).write_log(level="error", message=tb)
                last_exception = e
                continue_ = True
                if retry == max_retry:
                    pcr_log(account).write_log(
                        level="error",
                        message=f"main-检测出异常{str(e)} 超出最大重试次数,跳过账号!")
                    # 标记错误!
                    self.task_error(str(last_exception))
                    self.fix_reboot(False)
                    return False
                pcr_log(account).write_log(
                    level='error',
                    message=f'main-检测出异常{str(e)},重启中 次数{retry}/{max_retry}')

                try:
                    self.fix_reboot(not before_)
                except Exception as e:
                    pcr_log(account).write_log(
                        level='error', message=f'main-自动重启失败,跳过账号!{str(e)}')
                    self.task_error(str(last_exception))
                    try:
                        self.fix_reboot(False)
                    except:
                        pass
                    return False
Ejemplo n.º 21
0
def run(bs, **kwargs):
    tasks = (Bot(bs, **kwargs).run(bs.token), )
    loop.run_until_complete(asyncio.gather(*tasks))
Ejemplo n.º 22
0
import logging
import sys
import time

import discord

from keys import token
from core.bot import Bot


def check_versions():
    dv = discord.__version__.split(".")
    pv = sys.version_info

    discord_version = (int(dv[0]), int(dv[1]), int(dv[2]))
    python_version = (pv.major, pv.minor, pv.micro)

    if not discord_version >= (1, 2, 0) and not python_version >= (3, 6, 0):
        return False
    return True


if __name__ == '__main__':
    if not check_versions():
        print(
            "Please check the versions of python and discord. You need Python 3.6+ and Discord rewrite version 1.2+"
        )
        time.sleep(10)
        exit()
    bot = Bot()
    bot.run(token)
Ejemplo n.º 23
0
@since Sep 29, 2011
@author Mario Steinhoff
"""

__version__ = '$Rev$'

import datetime

from core import runlevel
from core.bot import Bot
from objects.calendar import Calendar, Event
from components.calendar import LocalUserAuthority
from tools import dataloader

if __name__ == '__main__':
    bot = Bot()
    bot.register_subsystem('sqlite-persistence', 'core.persistence.SqlitePersistence', sqlite_file=dataloader.Parameters.source)
    bot.init(runlevel.NETWORK_SERVICE)
    
    sqlite = bot.get_subsystem('sqlite-persistence')
    cursor = sqlite.get_cursor()
    calendar = bot.get_subsystem('calendar-component')
    
    logger = bot.get_logger('tools.import.contacts')
    
    calendar_references = {}
    
    for category in dataloader.get_categories(cursor, dataloader.Parameters.event_categories):
        newCalendar = Calendar()
        newCalendar.title = category['Name']
        newCalendar.color = category['Color'][1:]
Ejemplo n.º 24
0
def run(token, prefix, owners):
    tasks = (Bot(token, prefix, owners).run(), )
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(*tasks))
Ejemplo n.º 25
0
@since Jul 23, 2011
@author Mario Steinhoff
"""

__version__ = '$$'

import datetime
import json

from core import runlevel
from core.bot import Bot
from objects.calendar import Calendar, Event
from components.calendar import GoogleBackend

try:
    bot = Bot()
    bot.init(runlevel.NETWORK_SERVICE)

    cc = bot.get_subsystem('calendar-component')
    """
    event = Event(start=datetime.date(2011, 9, 26), end=datetime.date(2011, 9, 27), title="sync-test")
    event = cc.insert_object(event)
    
    scnds = cc.datastore.secondary_backends
    gbe = [scnd for scnd in scnds if isinstance(scnd, GoogleBackend)][0]
    
    query = cc.datastore.get_query('event_by_id')
    local_id = [identity for identity in event.identities if identity.backend.typename == 'GoogleBackend'][0]
    
    query.id = json.loads(local_id.identity)['edit']
    
Ejemplo n.º 26
0
import time

from core.bot import Bot
from core.entity import Entity

bot = Bot()

if __name__ == '__main__':
    bot.show_topping_px()
    #bot.show_rice_px()

Ejemplo n.º 27
0
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@since Aug 15, 2011
@author Mario Steinhoff
"""

__version__ = '$Rev$'

import logging
import os

from core import runlevel
from core.bot import Bot
from core.persistence import SqlAlchemyPersistence

# Load all table definitions
import objects

if __name__ == '__main__':
    config_root = os.environ['FPTBOT_CONFIG']
    
    bot = Bot(root=config_root, level=logging.INFO)
    bot.init(runlevel.LOCAL_SERVICE)
    
    persistence = bot.get_subsystem('local-persistence')
    
    base = SqlAlchemyPersistence.Base
    base.metadata.drop_all(persistence.engine)
Ejemplo n.º 28
0
# coding=utf-8

from core.bot import Bot
from win32api import ShellExecute
import os
import time


if __name__ == "__main__":
    mcl_path = os.path.abspath(
        os.path.dirname(os.path.abspath(__file__))
        + os.path.sep + ".." +
        os.path.sep + ".." +
        os.path.sep + "mcl.cmd"
    )
    ShellExecute(0, "open", mcl_path, "", "", 1)
    time.sleep(7)

    Bot().start()
Ejemplo n.º 29
0
 def __init__(self):
     self.__connectors = load_connectors()
     self.__bots = dict()
     self.__bots['innovate_bot_73'] = Bot('innovate_bot_73')
Ejemplo n.º 30
0
import time

import win32api
import win32con

from core.bot import Bot
from core.entity import Entity
import keyboard

bot = Bot()


def test_get_path():
    print("=== test path ===")
    print("bot.main_path: ", bot.main_path)
    print("bot.img_path: ", bot.img_path)


def test_grab_image():
    print("=== test grab image ===")
    bot.grab_img()
    print("=== grab image OK! ===")


def test_mouse_click():
    print("=== test mouse click ===")
    cord = (50, 50)
    print("mouse click at (x, y): ", cord)
    bot.mouse_click(cord)

Ejemplo n.º 31
0
def main():
    logging.basicConfig(level=logging.WARN)
    bot = Bot(settings=settings)
    bot.run()
import time

from core.bot import Bot
from core.entity import Entity

bot = Bot()

if __name__ == '__main__':
    #bot.cant_buy_nori()
    #bot.cant_buy_roe()
    bot.cant_buy_rice()
import time

from core.bot import Bot
from core.entity import Entity

bot = Bot()

if __name__ == '__main__':
    #bot.mouse_click(Entity.topping_nori)
    time.sleep(1)
    color_nori = bot.grab_img().getpixel(Entity.topping_nori)
    # color_unagi = bot.grab_img().getpixel(Entity.topping_unagi)
    # color_shrimp = bot.grab_img().getpixel(Entity.topping_shrimp)
    print("Entity.topping_nori RGB: ", color_nori)
    # print("Entity.topping_unagi RGB: ", color_unagi)
    # print("Entity.topping_shrimp RGB: ", color_shrimp)

Ejemplo n.º 34
0
def valid_bot() -> Bot:
    yield Bot(API_VALID_TOKEN)
Ejemplo n.º 35
0
    "sharedBoxShape" : (4, 10),
    "blocksShape": (5,10),
    "nLSTMCells": 10,
    "decisionBlockShape": (3,10),
    "dropout": 1.,
    "batch_size": 10
}

print "Model configuration"

opt = LSTMNet(config, train_set, validation_set, n_series, n_features)

print "Learning started"
for i in xrange(0,1):
    out_ = opt.learn()
    print "Epoch" , i, ":", "train gain:", out_[0], "validation gain:", out_[1]

suggester = opt.finalize()

bot = Bot(suggester,n_series,n_features,False,1000, 0.1)
capital = []
for i in range(validation_set.shape[0]):
    bot.reset()
    for t in range(validation_set.shape[1]): 
        bot.step(validation_set[i,t,:])
    capital.append(bot.getVirtualCapital())

print "you gained:", (sum(capital) /( len(capital) + 0.0))
    
    
Ejemplo n.º 36
0
@since Jul 23, 2011
@author Mario Steinhoff
"""

__version__ = '$$'

import datetime
import json

from core import runlevel
from core.bot import Bot
from objects.calendar import Calendar, Event
from components.calendar import GoogleBackend

try:
    bot = Bot()
    bot.init(runlevel.NETWORK_SERVICE)
    
    cc = bot.get_subsystem('calendar-component')
    """
    event = Event(start=datetime.date(2011, 9, 26), end=datetime.date(2011, 9, 27), title="sync-test")
    event = cc.insert_object(event)
    
    scnds = cc.datastore.secondary_backends
    gbe = [scnd for scnd in scnds if isinstance(scnd, GoogleBackend)][0]
    
    query = cc.datastore.get_query('event_by_id')
    local_id = [identity for identity in event.identities if identity.backend.typename == 'GoogleBackend'][0]
    
    query.id = json.loads(local_id.identity)['edit']
    
Ejemplo n.º 37
0
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@since Aug 15, 2011
@author Mario Steinhoff
"""

__version__ = '$Rev$'

import logging
import os

from core import runlevel
from core.bot import Bot
from core.persistence import SqlAlchemyPersistence

# Load all table definitions
import objects

if __name__ == '__main__':
    config_root = os.environ['FPTBOT_CONFIG']

    bot = Bot(root=config_root, level=logging.INFO)
    bot.init(runlevel.LOCAL_SERVICE)

    persistence = bot.get_subsystem('local-persistence')

    base = SqlAlchemyPersistence.Base
    base.metadata.create_all(persistence.engine)
Ejemplo n.º 38
0
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@since Jan 6, 2011
@author Mario Steinhoff
"""

__version__ = '$Rev$'

import os

from core import runlevel
from core.bot import Bot

if __name__ == '__main__':
    config_root = os.environ['FPTBOT_CONFIG']
    
    bot = Bot(root=config_root)
    bot.init(runlevel.NETWORK_INTERACTION)