Ejemplo n.º 1
0
def _load_program_settings(args):
    """Load program settings if file provided by user, else use default. """
    config_file = Path(args.aux_dir) / f"{BASENAME_NO_EXT}.cfg"
    config = DEFAULT_CONFIG.copy()
    cfg = ConfigParser()
    cfg.optionxform = str  # maintain case even on Windows
    secn = 'Files'

    if Path.exists(config_file):
        logging.info(f"Reading program settings from {config_file}:")
        cfg.read(config_file)
        config['max_flines'] = int(cfg[secn].get('max_flines'))
        config['max_fsize_kb'] = int(cfg[secn].get('max_fsize_kb'))
        config['ignore_dirs'] = _array_from_str(cfg[secn].get('ignore_dirs'))
        config['ignore_files'] = _array_from_str(cfg[secn].get('ignore_files'))
        none_keys = []
        for key, val in config.items():
            if val is None:
                none_keys.append(key)
        if None in config.values():
            logging.print(INVALID_CONFIG_FILE_MSG.format(**locals()))
            _exit()
    else:
        logging.info("Using default program configuration settings:")
        if args.bashcomp or not args.no_log:  # only write when allowed to
            logging.print(("Writing default program configuration settings "
                           f"to {config_file}"))
            cfg[secn] = _str_dict(config)
            with open(config_file, 'w') as file:
                cfg.write(file)

    logging.info(config)

    return config
Ejemplo n.º 2
0
def getOrderPosition(wantedorder):
    orderlist = getOrderCache()
    #splitting the orderlist into buy and sellorders
    buylist = []
    selllist = []
    #sort by boughtat, which is also the standard sorting in eve's my orders
    #todo implement check to look if "expires in" is sorted in the correct direction (lowest timestamp first)
    orderlist.sort(key=lambda x: x.issuedate, reverse=False)
    print(orderlist)
    for order in orderlist:
        if (order.bid):
            buylist.append(order)
        else:
            selllist.append(order)
    if (wantedorder.bid):
        for idx, x in enumerate(buylist):
            if (areOrdersTheSame(x, wantedorder)):
                return (idx, len(buylist))
    else:
        for idx, x in enumerate(selllist):
            if (areOrdersTheSame(x, wantedorder)):
                return (idx, len(selllist))
    print("couldnt find order: " + str(wantedorder.__dict__) +
          "  in getorderposition")
    refreshAllOrders()
    return getOrderPosition(wantedorder)
Ejemplo n.º 3
0
    def test_detector_example(self):
        distribution = [0.1, 1.1, 4.78, 2.0, 7.2, 5.3, 8.1, -14.1, 5.4]
        from outlier_detector.detectors import OutlierDetector

        od = OutlierDetector(buffer_samples=5)
        for x in distribution:
            print(od.is_outlier(x))
Ejemplo n.º 4
0
    def test_function_example(self):
        sample = -14.5
        distribution = [0.1, 1.1, 4.78, 2.0, 7.2, 5.3]

        from outlier_detector.functions import is_outlier

        print(is_outlier(distribution, sample))
Ejemplo n.º 5
0
def safetypewrite(text):
    while True:
        pyautogui.keyDown('ctrl')
        pyautogui.keyDown('a')
        sleep(0.3)
        pyautogui.keyUp('a')
        pyautogui.keyUp('ctrl')
        pyautogui.typewrite(['backspace'])
        pyautogui.typewrite(str(text), interval=0.04)
        sleep(0.1)
        pyautogui.keyDown('ctrl')
        pyautogui.keyDown('a')
        sleep(0.3)
        pyautogui.keyUp('a')
        pyautogui.keyUp('ctrl')
        sleep(0.1)
        pyautogui.keyDown('ctrl')
        pyautogui.keyDown('c')
        sleep(0.5)
        pyautogui.keyUp('c')
        pyautogui.keyUp('ctrl')
        sleep(0.5)
        realtext = pyperclip.paste()
        print(realtext)
        if (str(text) == str(realtext)):
            return
Ejemplo n.º 6
0
def clear():
    print("clearing quickbar...")
    show()
    cm.sleep(0.2)
    cm.clickPointPNG('imgs/resetquickbar.png', 5, 5)
    cm.sleep(0.5)
    cm.clickPointPNG('imgs/yesno.png', 5, 5)
    itemlist.clear()
Ejemplo n.º 7
0
def _handle_errors(err_types, msg):
    """Use 'with:' to handle an error and print a message. """
    try:
        yield
    except err_types as err:
        logging.print(msg)
        logging.debug(err)
        _exit()
Ejemplo n.º 8
0
def optionset(args_arr):
    """Main optionset function. Input array of string arguments. """
    start_time = time()  # time program

    # Parse arguments
    args, parser = _parse_args(args_arr)

    if args.help_full:
        parser.description = FULL_HELP_DESCRIPTION
        parser.print_help()
        return True

    if args.version:
        logging.print(f"{BASENAME} {__version__}")
        return True

    # Setup logging
    log_path = setup_logging(args)

    # Run algorithm
    logging.info("Executing main optionset function")

    logging.info("Checking input options")
    logging.debug(f"args = {args}")
    config = _load_program_settings(args)
    input_db = _parse_and_check_input(args, config)
    logging.info(f"<tag><raw_opt> <setting> = "
                 f"{input_db.tag}{input_db.raw_opt} {input_db.setting}")

    logging.info("Generating valid files")
    valid_files = list(
        _gen_valid_files(config['ignore_files'], config['ignore_dirs']))
    logging.info(f"Valid files: {[str(vf) for vf in valid_files]}")

    optns_settings_db, var_optns_values_db, show_files_db, f_changes_made \
        = _scroll_through_files(valid_files, input_db=input_db)

    if args.available or args.showfiles:
        glob_pat = '*' if args.option is None else f"{args.option}*"
        _print_available(optns_settings_db, var_optns_values_db, show_files_db,
                         glob_pat, args.available)

    if args.bashcomp:
        _write_bashcompletion_file(optns_settings_db,
                                   var_optns_values_db,
                                   parser,
                                   bashcomp_path=args.aux_dir / BASHCOMP_NAME)

    if f_changes_made:
        logging.print(f"See all modifications in {log_path}")

    total_prog_time = time() - start_time
    total_prog_time_msg = f"Finished in {total_prog_time:1.5f} s"
    logging.info(total_prog_time_msg)

    # logging.StreamHandler().flush()  # flush logging output at end

    return True
Ejemplo n.º 9
0
def _print_available(ops_db,
                     var_ops_db,
                     show_files_db,
                     glob_pat='*',
                     f_available=True):
    """Print available options and options for use; optionally sort with unix
    expression. """
    common_files = []
    body_msg = ""
    num_optns = 0
    for db in (ops_db, var_ops_db):
        logging.info(pformat(db, indent=1))
        for item in sorted(db.items()):
            optn_str = item[0]
            if not fnmatch(optn_str, glob_pat):
                continue
            body_msg += os.linesep + f"  {optn_str}"
            num_optns += 1
            if f_available:
                for sub_item in sorted(item[1].items()):
                    setting_str = sub_item[0]
                    if sub_item[1] is True:
                        left_str, right_str = '>', '<'
                    elif sub_item[1] is False:
                        left_str, right_str = ' ', ' '
                    elif sub_item[1] is None:
                        left_str, right_str = ' ', ' '
                    elif sub_item[1] is not None:
                        left_str, right_str = sub_item[1], sub_item[1]
                    else:
                        left_str, right_str = '?', '?'
                    body_msg += os.linesep
                    body_msg += f"\t{left_str} {setting_str} {right_str}"
            if show_files_db is not None:
                if show_files_db[optn_str]:
                    files_str = ' '.join(show_files_db[optn_str].keys())
                    body_msg += os.linesep + "  " + files_str + os.linesep
                    body_msg += "-" * 60
                    for file_ in show_files_db[optn_str].keys():
                        common_files.append(file_)

    sub_hdr_msg = r"('  inactive  ', '> active <', '? both ?', '= variable =')"
    if not body_msg:
        hdr_msg = f"No available options and settings matching '{glob_pat}'"
    else:
        hdr_msg = ("Showing available options and settings matching "
                   f"'{glob_pat}'")
        hdr_msg += os.linesep + sub_hdr_msg

    # Find files common to all options
    if show_files_db is not None and num_optns > 1:
        common_files_str = "  Common files:" + os.linesep + "  "
        for common_file in sorted(set(common_files)):
            common_files_str += str(common_file).lstrip("'").rstrip("'") + " "
        body_msg += os.linesep + common_files_str

    full_msg = hdr_msg + body_msg
    logging.print(full_msg)
Ejemplo n.º 10
0
def refreshOrderList():
    cm.clickPointPNG('imgs/marketordersbutton.png', 10, 10, cache=True)
    cm.sleep(0.2)
    cm.clickPointPNG('imgs/marketordersbutton.png', 10, 10, cache=True)
    cm.sleep(0.2)
    while pyautogui.locateOnScreen('imgs/myordersselling.png',
                                   confidence=0.9) is None:
        print("didnt properly reopen order list")
        cm.clickPointPNG('imgs/marketordersbutton.png', 10, 10, cache=True)
        cm.sleep(1)
Ejemplo n.º 11
0
def deleteMarketLogs():
    marketlogsfolder = os.path.expanduser(
        '~\\Documents\\EVE\\logs\\Marketlogs')
    for filename in os.listdir(marketlogsfolder):
        file_path = os.path.join(marketlogsfolder, filename)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except:
            print("failed deleting all files in marketlogs")
Ejemplo n.º 12
0
def getNameFromID(typeid):
    try:
        loop = asyncio.get_event_loop()
        future = asyncio.ensure_future(agetNameFromID(typeid))
        typename = loop.run_until_complete(future)
        loop.close
    except:
        print("failed to get info from fuzzwork, retrying in 15s")
        pyautogui.sleep(15)
        return getNameFromID(typeid)
    return typename
Ejemplo n.º 13
0
    def handle(self, nomorebuy=False):
        orderstuff.refreshAllOrders()
        goodprices = orderstuff.getGoodPrices(self.typeid)

        if self.buyorder is not None:
            print("leftoveritemhandler is cancelling it's buyorder")
            orderstuff.cancelOrder(self.buyorder)
            return

        if (len(self.sellorderlist) == 0):
            variables.itemhandlerlist.remove(self)
            return

        orderstuff.checkAndUnderBid(self, goodprices)
Ejemplo n.º 14
0
def _check_varop_groups(re_str):
    """Calculate the number of regex groups designated by (). """
    all_groups = re.findall(r'([^\\]\(.*?[^\\]\))', re_str)
    if all_groups:
        if len(all_groups) > 1:
            logging.print(
                INVALID_REGEX_GROUP_MSG.format(
                    specific_problem='More than one regex group \'()\' found'))
            raise AttributeError
    else:
        logging.print(
            INVALID_REGEX_GROUP_MSG.format(
                specific_problem='No regex groups found.\r\n'))
        raise AttributeError
Ejemplo n.º 15
0
def _process_file(filepath, input_db, optns_settings_db, var_optns_values_db,
                  show_files_db):
    """Process individual file.
    Update optns_settings_db and var_optns_values_db
    Return if changes have been made or not

    General algorithm is to scroll through file line by line, applying
    consistent logic to make build database of available options or to make the
    desired changes.
    """
    logging.debug(f"FILE CANDIDATE: {filepath}")

    # Check file size and line count of file
    linecount = _line_count(filepath, line_limit=input_db.max_flines)
    fsize_kb = filepath.stat().st_size / 1000
    if fsize_kb > input_db.max_fsize_kb:
        reason_str = f"File exceeds kB size limit of {input_db.max_fsize_kb}"
        _skip_file_warning(filepath, reason=reason_str)
        return False

    if linecount > input_db.max_flines:
        reason_str = f"File exceeds line limit of {input_db.max_flines}"
        _skip_file_warning(filepath, reason=reason_str)
        return False

    # Instantiate and initialize file variables
    fdb = FileVarsDatabase(filepath, input_db)

    # Only continue if a comment index is found in the file
    if not fdb.com_ind:
        return False
    logging.debug(f"FILE MATCHED [{fdb.com_ind}]: {filepath}")

    # Read file and parse options in comments
    with open(filepath, 'r', encoding='UTF-8') as file:
        newlines = [''] * linecount
        for idx, line in enumerate(_yield_utf8(file)):
            line_num = idx + 1
            newlines[idx] = _process_line(line, line_num, fdb,
                                          optns_settings_db,
                                          var_optns_values_db, show_files_db)

    # Write file
    if fdb.f_filemodified:
        with open(filepath, 'w', encoding='UTF-8') as file:
            file.writelines(newlines)
        logging.print(f"File modified: {file.name}")
        return True

    return False
Ejemplo n.º 16
0
def find(event=None):

    text.tag_configure("found", background='yellow', foreground='red')

    # prepare re
    input_text = entry.get()
    target_re = re.compile(input_text)

    # get scrolled text's all text
    src_text = text.get("1.0", END)
    lines = src_text.splitlines()
    for i, line in enumerate(lines):
        for mo in target_re.finditer(line):
            text.tag_add('found', f"{i+1}.{mo.span()[0]}",
                         f"{i+1}.{mo.span()[1]}")
            print(mo)
    pass
Ejemplo n.º 17
0
async def fetch(item, session):
    async with session.get(
            "https://esi.evetech.net/latest/markets/10000002/history/?datasource=tranquility&type_id="
            + str(item.typeid)) as response:
        repo = await response.read()
        try:
            rsjson = json.loads(repo)
        except:
            print("failed to load volume for item: " + str(item.__dict__))
            return item
        vol = 0
        for day in range(len(rsjson) - 14, len(rsjson)):
            try:
                vol += rsjson[day]['volume']
            except:
                break
        item.volume = int(vol / 14)
        return item
Ejemplo n.º 18
0
    def test_filter_object_example(self):
        distribution = [0.1, 1.1, 4.78, 2.0, 7.2, 5.3, 8.1, -14.1, 5.4]
        from outlier_detector.filters import OutlierFilter

        class MyGen:
            def __init__(self):
                self.cursor = -1

            def pop(self):
                self.cursor += 1
                return distribution[self.cursor]

        g = MyGen()
        of = OutlierFilter()
        try:
            for sample in of.filter(g.pop):
                print(sample)
        except IndexError:
            print("No more data")
Ejemplo n.º 19
0
    def test_filter_example(self):
        distribution = [0.1, 1.1, 4.78, 2.0, 7.2, 5.3, 8.1, -14.1, 5.4]
        from outlier_detector.filters import filter_outlier

        class MyGen:
            def __init__(self):
                self.cursor = -1

            @filter_outlier()
            def pop(self):
                self.cursor += 1
                return distribution[self.cursor]

        g = MyGen()
        while True:
            try:
                r = g.pop()
                print(r)
            except IndexError:
                print("No more data")
                break
Ejemplo n.º 20
0
def sellItem(itemhandler, goodprices):
    if (len(getOrderCache()) > 16):
        print(
            "will exceeded max orders, cancelling a leftoveritemhandler's cheapest sellorder"
        )
        cancelOrder(getWorthlessLOIHSellorder())
        return sellItem(itemhandler, goodprices)
    sellprice = goodprices[1]
    if (sellprice == -1):
        print("Warning, not selling item: " +
              api.getNameFromID(itemhandler.typeid) +
              " because there is no good price.")
        return
    sellprice = round(sellprice - random.random() / 7 - 0.01, 2)
    flag = sellitemininventory(itemhandler.typeid, sellprice)
    if (flag == 0):
        print("couldnt sell item from inventory, doesnt exist")
        return
    quantity = 0
    if itemhandler.buyorder is None or itemhandler.buyorder.finished:
        #adjust the quantity if there are previous sellorders
        quantity = itemhandler.volume
        for sellorder in itemhandler.sellorderlist:
            quantity -= sellorder.volentered
    else:
        #we only get here once, because we check if sellorderlist has no
        #elements in the ifstatement in the selling part in itemhandler's handle()
        quantity = itemhandler.buyorder.volentered - itemhandler.buyorder.volremaining
    itemhandler.sellorderlist.append(
        cm.Order(itemhandler.typeid, -1, False, sellprice, quantity, quantity,
                 cm.getEVETimestamp()))
    #this line sets the orderid from -1 to something else
    refreshAllOrders()
Ejemplo n.º 21
0
def _parse_and_check_input(args, config):
    """Parse input arguments. """
    InputDb = namedtuple('InputDb', [
        'tag',
        'raw_opt',
        'setting',
        'f_available',
        'f_showfiles',
        'f_bashcomp',
        'rename_optn',
        'rename_setting',
        'max_flines',
        'max_fsize_kb',
    ])

    # Check if renaming an option
    if args.rename_optn or args.rename_setting:
        #  No setting, available, and showfiles arguments if renaming option
        msg = "Must remove {argStr} argument if renaming an option or setting."
        if args.available:
            logging.print(msg.format(argStr='available'))
            _exit()
        elif args.showfiles:
            logging.print(msg.format(argStr='showfiles'))
            _exit()
        elif args.rename_setting and not args.setting:
            logging.print("Must input a setting if renaming a setting.")
            _exit()
    else:
        # If no setting is input, default to displaying available options
        if (not args.setting and not args.showfiles):
            args.available = True

    # If displaying available options or associated file paths
    if args.available or args.showfiles:
        tag_ = ANY_TAG
        raw_opt_ = ANY_RAW_OPTN
        setting_ = args.setting
        f_available_ = args.available
        f_showfiles_ = args.showfiles
    else:  # standard operation of setting an option
        if args.rename_optn and not args.rename_setting:
            setting_ = ''
            _, _ = _check_optn_fmt(args.rename_optn)

        setting_ = _check_setting_fmt(args.setting) if args.setting else ''
        tag_, raw_opt_ = _check_optn_fmt(args.option)
        f_available_ = False
        f_showfiles_ = False

    return InputDb(tag=tag_,
                   raw_opt=raw_opt_,
                   setting=setting_,
                   f_available=f_available_,
                   f_showfiles=f_showfiles_,
                   f_bashcomp=args.bashcomp,
                   rename_optn=args.rename_optn,
                   rename_setting=args.rename_setting,
                   max_flines=config['max_flines'],
                   max_fsize_kb=config['max_fsize_kb'])
Ejemplo n.º 22
0
def init():
    global itemhandlerlist
    global bidaplh
    global sellaplh
    global minmargin
    global maxmargin
    global capital
    global minquantity
    global maxhandlers
    global tesseractpath
    global sleepmultiplier
    global minpricediff
    global minordercount
    itemhandlerlist = []
    bidaplh = (None, None)
    sellaplh = (None, None)
    with open('settings.txt', 'r') as settings:
        for line in settings:
            if line.isspace():
                continue
            print(line.strip().split(None, 1))
            (key, val) = line.strip().split(None, 1)
            if key == "minmargin":
                minmargin = float(val)
            elif key == "maxmargin":
                maxmargin = float(val)
            elif key == "capital":
                capital = float(val)
            elif key == "minquantity":
                minquantity = int(val)
            elif key == "maxhandlers":
                maxhandlers = int(val)
            elif key == "tesseractpath":
                tesseractpath = val
            elif key == "sleepmultiplier":
                sleepmultiplier = float(val)
            elif key == "minpricediff":
                minpricediff = float(val)
            elif key == "minordercount":
                minordercount = float(val)
Ejemplo n.º 23
0
def openItem(typeid):
    show()
    for idx, item in enumerate(itemlist):
        if api.getNameFromID(typeid) == item:
            print("found typeid: " + str(typeid) + " in quickbar at index: " +
                  str(idx))
            print("all items in quickbar:")
            print(itemlist)
            cm.clickPointPNG('imgs/regionalmarkettopleft.png',
                             35,
                             81 + idx * 20,
                             cache=True)
            return
    print("couldn't find item in quickbar: " + api.getNameFromID(typeid))
Ejemplo n.º 24
0
def getGoodPrices(typeid):
    toporders = getTopOrders(typeid)
    buyprice, sellprice = -1, -1
    buyhighestbidderflag = False
    sellhighestbidderflag = False
    for o in toporders[0]:
        if (o.volremaining > variables.minquantity):
            buyhighestbidderflag = any(
                areOrdersTheSame(o, co) for co in getOrderCache())
            buyprice = o.price
            break
    for o in toporders[0]:
        #if we are highest bidder, but some other order that isnt ours has the same price as ours
        if (buyhighestbidderflag and buyprice == o.price
                and not any(areOrdersTheSame(o, co)
                            for co in getOrderCache())):
            #we set highestbidder to false so we can overbid people that have the same price as us
            buyhighestbidderflag = False
            break
    #highest bidder checks for sell orders
    for o in toporders[1]:
        if (o.volremaining > variables.minquantity):
            sellhighestbidderflag = any(
                areOrdersTheSame(o, co) for co in getOrderCache())
            sellprice = o.price
            break
    for o in toporders[1]:
        if (sellhighestbidderflag and sellprice == o.price
                and not any(areOrdersTheSame(o, co)
                            for co in getOrderCache())):
            sellhighestbidderflag = False
            break
    print("finished getgoodprices")
    returntuple = (buyprice, sellprice, buyhighestbidderflag,
                   sellhighestbidderflag)
    print(returntuple)
    return returntuple
Ejemplo n.º 25
0
def collectItems():
    page = 1
    pagemultiple = 50
    allorders = []
    running = True
    while running:
        urls = []
        for i in range(page, page + pagemultiple):
            urls.append(
                "https://esi.evetech.net/latest/markets/10000002/orders/?datasource=tranquility&page="
                + str(i))
        rs = (grequests.get(u) for u in urls)
        allresponses = grequests.map(rs)
        while (any(r.status_code != 200 for r in allresponses)):
            print("received non 200 status code")
            rs = (grequests.get(u) for u in urls)
            allresponses = grequests.map(rs)
        for response in allresponses:
            rsjson = None
            try:
                rsjson = response.json()
            except:
                print("json decode in collectitems wasn't perfect")
                print(response.text)
            if not rsjson:
                running = False
                break
            for order in rsjson:
                #todo only jita
                if (order['location_id'] == 60003760):
                    allorders.append(
                        SimpleOrder(int(order['type_id']),
                                    str(order['is_buy_order']) == "True",
                                    float(order['price'])))
        page += pagemultiple
    simpleitemlist = []
    #have fun understanding this
    for i in range(0, 60000):
        simpleitemlist.append(SimpleItem(i, -1, -1))
    for order in allorders:
        si = simpleitemlist[order.typeid]
        if order.is_buy_order:
            si.buycount += 1
            if (si.highestbuy < order.price or si.highestbuy == -1):
                si.highestbuy = order.price
        if not order.is_buy_order:
            si.sellcount += 1
            if (si.lowestsell > order.price or si.lowestsell == -1):
                si.lowestsell = order.price

    return simpleitemlist
Ejemplo n.º 26
0
def buyItem(itemhandler, goodprices):
    if (len(getOrderCache()) > 16):
        print(
            "will exceeded max orders, cancelling a leftoveritemhandler's cheapest sellorder"
        )
        cancelOrder(getWorthlessLOIHSellorder())
        return buyItem(itemhandler, goodprices)
    quantity = itemhandler.volume
    buyprice = goodprices[0]
    if (buyprice == -1):
        print("Warning, not buying item: " +
              api.getNameFromID(itemhandler.typeid) +
              " because there is no good price.")
        return
    buyprice = round(buyprice + random.random() / 7 + 0.01, 2)
    print("itemhandler called: " + api.getNameFromID(itemhandler.typeid) +
          " is initiating buyorder. price:" + str(buyprice) + ", quantity:" +
          str(quantity))
    buyorder(itemhandler.typeid, buyprice, quantity)
    itemhandler.buyorder = cm.Order(itemhandler.typeid, -1, True, buyprice,
                                    quantity, quantity, cm.getEVETimestamp())
    #this line sets the orderid from -1 to something else
    refreshAllOrders()
Ejemplo n.º 27
0
@Telescopy.on_message(filters.new_chat_members & filters.me)
async def greet(client, message):
    await message.reply_text(
        '**Thanks for Adding me Here !\n\nI will Convert Square Videos or Gif When they will be send in this Chat**',
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton(text="📣 Support Group 📣",
                                 url="https://t.me/FutureCodes")
        ]]))


@Telescopy.on_message(filters.private & filters.command('start'))
async def pmfilter(client, message):
    await message.reply_text(
        "**I can Convert Square Video or Gif to Circle Form...\n\nJust send me Square Video or Gif\n\nJoin @FutureCodes**",
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton(text="🌟 Support Group 🌟",
                                 url=f"https://t.me/FutureCodes")
        ]]),
        quote=True)


@Telescopy.on_message(filters.group & filters.command('start'))
async def groupo(client, message):
    await message.reply_text('Hi, I am Alive', quote=True)


Telescopy.run()
hm = Telescopy.get_me()
logging.print(f"{hm.username} Deployed Successfully !!")
logging.print("Join @FutureCodes...")
Ejemplo n.º 28
0
def addItemToQuickbar(typeid):
    dontShow()
    itemname = api.getNameFromID(typeid)
    pyautogui.moveTo(200, 10)
    pyautogui.sleep(0.3)
    thing = pyautogui.locateOnScreen('imgs/regionalmarkettopleft.png',
                                     confidence=0.9)
    thing2 = pyautogui.locateOnScreen('imgs/search.png', confidence=0.9)
    if thing is None or thing2 is None:
        print("im blind")
        return addItemToQuickbar(typeid)
    search_market(itemname)
    cm.sleep(4)
    searchareacapturepos = cm.Area(thing.left, thing.top + 100,
                                   thing2.left - thing.left + 50, 400)

    for loopidx in range(20):
        ocr = cm.grabandocr(searchareacapturepos)
        ocrlines = ocr.splitlines()
        if loopidx == 10:
            search_market(itemname)
            cm.sleep(0.5)
        stringdict = {}
        curstring = ""
        for idx, s in enumerate(ocrlines):
            s = s.lower()
            if (len(s.split()) <= 11 or len(s.split()[-1]) < 2):
                if curstring:
                    stringdict[curstring.strip()] = idx - 1
                curstring = ""
            else:
                curstring += s.split()[-1] + " "
            if (idx == len(ocrlines) - 1):
                stringdict[curstring.strip()] = idx - 1
        highestsim = -1
        bestidx = 0
        for s in stringdict:
            cursim = cm.similar(itemname.lower(), s)
            if cursim > highestsim:
                highestsim = cursim
                bestidx = stringdict[s]
        if (highestsim > 0.8):
            s = ocrlines[bestidx]
            print("found item in search results: " + s)
            offsetpos = searchareacapturepos
            mousex = offsetpos.x + int(s.split()[6]) / 4 + 5
            mousey = offsetpos.y + int(s.split()[7]) / 4 + 5

            cm.clickxy(mousex, mousey)
            cm.sleep(1.5)

            thing = pyautogui.locateOnScreen('imgs/search.png', confidence=0.9)
            marketnamearea = cm.Area(thing.left + 158, thing.top + 14, 375, 30)
            ocr = cm.grabandocr(marketnamearea)
            marketname = ""
            for line in ocr.splitlines():
                if len(line.split()) > 11:
                    marketname += line.split()[-1] + ' '
            #strips marketname of whitespace and the list 4 characters, which should be: " i ©"
            marketname = marketname.strip()[:-4]
            print("read marketname while adding item: " + marketname)
            #marketname is the ocr result, itemname is the actual item were trying to add
            if (cm.similar(marketname.lower(), itemname.lower()) < 0.75):
                print("clicked wrong item while adding, retrying")
                return addItemToQuickbar(typeid)

            cm.clickxy(mousex, mousey, right=True)
            cm.sleep(0.2)
            cm.clickxy(mousex + 52, mousey + 29)
            print("old itemlist:")
            print(itemlist)
            if itemname not in itemlist:
                itemlist.append(itemname)
            itemlist.sort(key=str.lower)
            print("new itemlist:")
            print(itemlist)
            return

        if loopidx > 12:
            #we only get here if it didnt find an item: the item must have been in a collapsed category
            for s in ocr.splitlines():
                if (len(s.split()) > 11 and len(s.split()[-1]) > 3):
                    #we do NOT want to open the blueprint category
                    if not "prints" in s and not "react" in s:
                        offsetpos = searchareacapturepos
                        mousex = offsetpos.x + int(s.split()[6]) / 4 + 5
                        mousey = offsetpos.y + int(s.split()[7]) / 4 + 5
                        cm.clickxy(mousex, mousey)
                        break
        cm.sleep(0.5)

    print("looped through item adding a lot without success, aborting")
    sys.exit()
Ejemplo n.º 29
0
    def handle(self, nomorebuy=False):
        orderstuff.refreshAllOrders()

        if (nomorebuy and not self.sellorderlist and not self.buyorder):
            return

        goodprices = orderstuff.getGoodPrices(self.typeid)
        #check unprofitable, cancel buyorder if it is
        orderstuff.refreshUnprofitable(self, goodprices)
        if self.unprofitable:
            if self.unprofitabledate == -1:
                self.unprofitabledate = getEVETimestamp()
        else:
            self.unprofitabledate = -1
        #we can only cancel if it has been unprofitable for 20 minutes
        if (self.unprofitable and self.buyorder is not None
                and (getEVETimestamp() - self.unprofitabledate > 1200)):
            print("cancelling itemhandler: " + api.getNameFromID(self.typeid) +
                  "'s buyorder due to unprofitability")
            orderstuff.cancelOrder(self.buyorder)
            print("trying to sell itemhandler: " +
                  api.getNameFromID(self.typeid) + "'s purchases")
            orderstuff.sellItem(self, goodprices)
            #we only replace the handler when the sellorder is gone
            #todo implement function that converts an unprofitable itemhandler to an leftoveritemhandler, so there's space for a normal itemhandler
            if len(self.sellorderlist) == 0:
                print(
                    "didn't have any purchases, fetching new itemhandlers from api..."
                )
                api.fetchItemHandlers()
            return
        #we only sell half of bought once per item cycle
        if self.buyorder is not None and not self.unprofitable:
            if (self.buyorder.volremaining < (self.buyorder.volentered / 2)
                    and not self.sellorderlist) or self.buyorder.finished:
                orderstuff.sellItem(self, goodprices)
                if self.buyorder.finished:
                    self.buyorder = None
        #we place buyorder when there are no orders
        if not nomorebuy:
            if not self.buyorder and not self.sellorderlist and not self.unprofitable:
                orderstuff.buyItem(self, goodprices)
                return
        #check if all sellorders are done
        #finished is false if its not finished
        if len(self.sellorderlist) > 0 and all(
                order.finished == True
                for order in self.sellorderlist) and self.buyorder is None:
            self.sellorderlist = []
            print("itemhandler went through full trade cycle")
            if self.unprofitable and (getEVETimestamp() - self.unprofitabledate
                                      > 3600):
                print("fetching new itemhandlers from api...")
                api.fetchItemHandlers()
                return
            else:
                print("increasing volume by 5%...")
                self.volume = math.ceil(self.volume * 1.05)

        #update prices
        orderstuff.checkAndUnderBid(self, goodprices)
Ejemplo n.º 30
0
if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, filename="logfile.txt", filemode="a+",
                        format="%(asctime)-15s %(levelname)-8s %(message)s")
    #need this for the sleep calls in cm.clickpoint
    variables.init()
    tradedaystart = cm.getEVETimestamp()
    process = multiprocessing.Process(target=mainwrapper.doTradeBot, args=(tradedaystart,))
    process.start()
    while True:
        try:
            if not process.is_alive():
                sys.exit()
            cl = pyautogui.locateOnScreen("imgs/connectionlost.png", confidence=0.9)
            if(cl is not None):
                process.terminate()
                print("we lost connection, initiating restart procedure")
                point = cm.Point(cl.left + 169, cl.top + 194)
                cm.clickPoint(point, 5)
                #wait 20 minutes for internet to come back or eve to restart
                time.sleep(1200)
                lg = pyautogui.locateOnScreen("imgs/launchgroup.png")
                pn = pyautogui.locateOnScreen("imgs/playnow.png")
                while (lg is None and pn is None):
                    cm.clickPointPNG("imgs/evetaskbar.png", 5, 5)
                    lg = pyautogui.locateOnScreen("imgs/launchgroup.png")
                    pn = pyautogui.locateOnScreen("imgs/playnow.png")
                    time.sleep(5)
                print("starting eve client")
                cm.clickPointPNG("imgs/launchgroup.png", 10, 10)
                cm.clickPointPNG("imgs/playnow.png", 10, 10)
                #wait for game to start