Пример #1
0
    def diff_json(self, filename1, filename2):
        '''
        比较两个文件内容的md5值;比较两个文件并输出到html文件中
        '''
        file1Md5 = self.md5_file(filename1)
        file2Md5 = self.md5_file(filename2)

        if file1Md5 != file2Md5:
            #             log.info('两个json数据文件md5不一样:')
            text1_lines = self.read_json(filename1)
            text2_lines = self.read_json(filename2)
            d = difflib.HtmlDiff()
            # context=True时只显示差异的上下文,默认显示5行,由numlines参数控制,context=False显示全文,差异部分颜色高亮,默认为显示全文
            result = d.make_file(text1_lines,
                                 text2_lines,
                                 filename1,
                                 filename2,
                                 context=True)

            # 内容保存到result.html文件中
            try:
                with open(diffFile, 'a', encoding='utf-8') as result_file:
                    result_file.write(result)
            except Exception as e:
                log.error("写入文件失败:" + e)
Пример #2
0
 def handle_captcha(self):
     # wait for captcha to load
     time.sleep(DEFAULT_MAX_WEIRD_PAGE_DELAY)
     try:
         if self.driver.find_element_by_xpath(
                 '//form[@action="/errors/validateCaptcha"]'):
             try:
                 log.info("Stuck on a captcha... Lets try to solve it.")
                 captcha = AmazonCaptcha.fromdriver(self.driver)
                 solution = captcha.solve()
                 log.info(f"The solution is: {solution}")
                 if solution == "Not solved":
                     log.info(
                         f"Failed to solve {captcha.image_link}, lets reload and get a new captcha."
                     )
                     self.driver.refresh()
                 else:
                     if self.no_screenshots:
                         self.notification_handler.send_notification(
                             "Solving captcha")
                     else:
                         self.save_screenshot("captcha")
                     self.driver.find_element_by_xpath(
                         '//*[@id="captchacharacters"]').send_keys(
                             solution + Keys.RETURN)
             except Exception as e:
                 log.debug(e)
                 log.info(
                     "Error trying to solve captcha. Refresh and retry.")
                 self.driver.refresh()
     except exceptions.NoSuchElementException:
         log.error("captcha page does not contain captcha element")
         log.error("refreshing")
         self.driver.refresh()
Пример #3
0
    def get_cart_url(self, product_id):
        try:
            success, token = self.get_session_token()
            if not success:
                return False, ""

            data = {"products": [{"productId": product_id, "quantity": 1}]}
            headers = DEFAULT_HEADERS.copy()
            headers["locale"] = self.locale
            headers["nvidia_shop_id"] = token
            headers["Content-Type"] = "application/json"
            response = self.session.post(url=NVIDIA_ADD_TO_CART_API,
                                         headers=headers,
                                         data=json.dumps(data))
            if response.status_code == 203:
                response_json = response.json()
                if "location" in response_json:
                    return True, response_json["location"]
            else:
                log.error(response.text)
                log.error(
                    f"Add to cart failed with {response.status_code}. This is likely an error with nvidia's API."
                )
            return False, ""
        except requests.exceptions.RequestException as e:
            self.notification_handler.send_notification(
                f"Got an unexpected reply from the server, API may be down, nothing we can do but try again"
            )
            return False, ""
Пример #4
0
 def buy(self, product_id):
     try:
         log.info(
             f"Checking stock for {product_id} at {self.interval} second intervals."
         )
         while not self.add_to_cart(product_id) and self.enabled:
             self.attempt = self.attempt + 1
             time_delta = str(datetime.now() -
                              self.started_at).split(".")[0]
             with Spinner.get(
                     f"Still working (attempt {self.attempt}, have been running for {time_delta})..."
             ) as s:
                 sleep(self.interval)
         if self.enabled:
             self.apply_shopper_details()
             if self.auto_buy_enabled:
                 self.notification_handler.send_notification(
                     f" {self.gpu_long_name} with product ID: {product_id} available!"
                 )
                 log.info("Auto buy enabled.")
                 # self.submit_cart()
                 self.selenium_checkout()
             else:
                 log.info("Auto buy disabled.")
                 cart_url = self.open_cart_url()
                 self.notification_handler.send_notification(
                     f" {self.gpu_long_name} with product ID: {product_id} in stock: {cart_url}"
                 )
             self.enabled = False
     except Timeout:
         log.error("Had a timeout error.")
         self.buy(product_id)
Пример #5
0
    def get_session_token(self):
        """
        Ok now this works, but I dont know when the cookies expire so might be unstable.
        :return:
        """

        params = {"format": "json", "locale": self.locale}
        headers = DEFAULT_HEADERS.copy()
        headers["locale"] = self.locale
        headers["cookie"] = "; ".join([
            f"{cookie.name}={cookie.value}" for cookie in self.session.cookies
        ])

        try:
            response = self.session.get(
                NVIDIA_TOKEN_URL,
                headers=headers,
                params=params,
                cookies=self.cj,
            )
            if response.status_code == 200:
                response_json = response.json()
                if "session_token" not in response_json:
                    log.error("Error getting session token.")
                    return False, ""
                return True, response_json["session_token"]
            else:
                log.debug(f"Get Session Token: {response.status_code}")
        except requests.exceptions.RequestException as e:
            log.info(
                f"Got an unexpected reply from the server, API may be down, nothing we can do but try again"
            )
            return False
Пример #6
0
    def check_stock(self, asin, reserve):
        if self.checkshipping:
            f = furl(AMAZON_URLS["OFFER_URL"] + asin +
                     "/ref=olp_f_new&f_new=true")
        else:
            f = furl(AMAZON_URLS["OFFER_URL"] + asin +
                     "/ref=olp_f_new&f_new=true&f_freeShipping=on")
        try:
            self.driver.get(f.url)
            elements = self.driver.find_elements_by_xpath(
                '//*[@name="submit.addToCart"]')
            prices = self.driver.find_elements_by_xpath(
                '//*[@class="a-size-large a-color-price olpOfferPrice a-text-bold"]'
            )
            shipping = self.driver.find_elements_by_xpath(
                '//*[@class="a-color-secondary"]')
        except Exception as e:
            log.debug(e)
            return False

        for i in range(len(elements)):
            price = parse_price(prices[i].text)
            ship_price = parse_price(shipping[i].text)
            ship_float = ship_price.amount
            price_float = price.amount
            if price_float is None or ship_float is None:
                log.error("Error reading price information on row.")
                continue
            elif (price_float + ship_float) <= reserve:
                log.info("Item in stock and under reserve!")
                elements[i].click()
                log.info("clicking add to cart")
                return True
        return False
Пример #7
0
    def login(self):

        try:
            log.info("Email")
            self.driver.find_element_by_xpath('//*[@id="ap_email"]').send_keys(
                self.username + Keys.RETURN)
        except:
            log.info("Email not needed.")
            pass

        if self.driver.find_elements_by_xpath(
                '//*[@id="auth-error-message-box"]'):
            log.error(
                "Login failed, check your username in amazon_config.json")
            time.sleep(240)
            exit(1)

        log.info("Remember me checkbox")
        selenium_utils.button_click_using_xpath(self.driver,
                                                '//*[@name="rememberMe"]')

        log.info("Password")
        self.driver.find_element_by_xpath('//*[@id="ap_password"]').send_keys(
            self.password + Keys.RETURN)

        log.info(f"Logged in as {self.username}")
Пример #8
0
def find_endpoints(domain):
    import dns.resolver

    if not domain:
        log.error(
            "You must specify a domain to resolve for endpoints with --domain."
        )
        exit(0)
    log.info(f"Attempting to resolve '{domain}'")
    # Default
    my_resolver = dns.resolver.Resolver()
    try:
        resolved = my_resolver.resolve(domain)
        for rdata in resolved:
            log.info(f"Your computer resolves {domain} to {rdata.address}")
    except Exception as e:
        log.error(f"Failed to use local resolver due to: {e}")
        exit(1)

    # Find endpoints from various DNS servers
    endpoints, resolutions = resolve_domain(domain)
    log.info(
        f"{domain} resolves to at least {len(endpoints)} distinct IP addresses across {resolutions} lookups:"
    )
    endpoints = sorted(endpoints)
    for endpoint in endpoints:
        log.info(f" {endpoint}")

    return endpoints
Пример #9
0
    def sign_in(self):
        log.info("Signing in.")
        self.driver.get(
            f"https://store.nvidia.com/DRHM/store?Action=Logout&SiteID=nvidia&Locale={self.locale}&ThemeID=326200&Env=BASE&nextAction=help"
        )
        selenium_utils.wait_for_page(
            self.driver, PAGE_TITLES_BY_LOCALE[self.locale]["signed_in_help"])

        if not self.is_signed_in():
            email = selenium_utils.wait_for_element(self.driver, "loginEmail")
            pwd = selenium_utils.wait_for_element(self.driver, "loginPassword")
            try:
                email.send_keys(self.nvidia_login)
                pwd.send_keys(self.nvidia_password)
            except AttributeError as e:
                log.error("Missing 'nvidia_login' or 'nvidia_password'")
                raise e
            try:
                action = ActionChains(self.driver)
                button = self.driver.find_element_by_xpath(
                    '//*[@id="dr_siteButtons"]/input')

                action.move_to_element(button).click().perform()
                WebDriverWait(self.driver, 5).until(ec.staleness_of(button))
            except NoSuchElementException:
                log.error("Error signing in.")
Пример #10
0
 def handle_cart(self):
     self.start_time_atc = time.time()
     log.info("clicking checkout.")
     try:
         self.save_screenshot("ptc-page")
     except:
         pass
     try:
         self.driver.find_element_by_xpath(
             '//*[@id="hlb-ptc-btn-native"]').click()
     except exceptions.NoSuchElementException:
         try:
             self.driver.find_element_by_xpath(
                 '//*[@id="hlb-ptc-btn"]').click()
         except exceptions.NoSuchElementException:
             log.error("couldn't find buttons to proceed to checkout")
             self.save_page_source("ptc-error")
             self.send_notification(
                 "Proceed to Checkout Error Occurred",
                 "ptc-error",
                 self.take_screenshots,
             )
             log.info("Refreshing page to try again")
             self.driver.refresh()
             self.checkout_retry += 1
Пример #11
0
    def navigate_pages(self, test):
        # delay to wait for page load
        time.sleep(self.page_wait_delay())

        title = self.driver.title
        if title in SIGN_IN_TITLES:
            self.login()
        elif title in CAPTCHA_PAGE_TITLES:
            self.handle_captcha()
        elif title in SHOPING_CART_TITLES:
            self.handle_cart()
        elif title in CHECKOUT_TITLES:
            self.handle_checkout(test)
        elif title in ORDER_COMPLETE_TITLES:
            self.handle_order_complete()
        elif title in PRIME_TITLES:
            self.handle_prime_signup()
        elif title in HOME_PAGE_TITLES:
            # if home page, something went wrong
            self.handle_home_page()
        elif title in DOGGO_TITLES:
            self.handle_doggos()
        else:
            log.error(
                f"{title} is not a known title, please create issue indicating the title with a screenshot of page"
            )
            if self.no_screenshots:
                self.notification_handler.send_notification("unknown-title")
            else:
                self.save_screenshot("unknown-title")
            self.save_page_source("unknown-title")
Пример #12
0
def download_file(url, output_path, stream=True):
    output_dir = os.path.dirname(output_path)
    os.makedirs(output_dir, exist_ok=True)
    if not url:
        log.error("URL is empty")
        return
    try:
        log.info('downloading ' + os.path.basename(output_path))
        r = requests.get(
            url,
            stream=stream,
            headers=config.get("wget_headers"),
            proxies=config.get("proxies"),
        )
        if stream:
            # TODO: implement cache playing later
            total_size = int(r.headers["content-length"])
            with open(output_path, "wb") as f:
                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
                f.close()
        else:
            with open(output_path, "wb") as f:
                f.write(r.content)
                f.close()

        log.info(os.path.basename(output_path) + ' is downloaded')
    except Exception as e:
        log.error(e)
Пример #13
0
 def handle_prime_signup(self):
     log.info("Prime offer page popped up, attempting to click No Thanks")
     button = None
     try:
         button = self.driver.find_element_by_xpath(
             # '//*[@class="a-button a-button-base no-thanks-button"]'
             '//*[contains(@class, "no-thanks-button") or contains(@class, "prime-nothanks-button") or contains(@class, "prime-no-button")]'
         )
     except exceptions.NoSuchElementException:
         log.error("could not find button")
         # log.info("check if PYO button hidden")
         # try:
         #     button = self.driver.find_element_by_xpath(
         #         '//*[@id="placeYourOrder"]/span/input'
         #     )
         # except exceptions.NoSuchElementException:
         #     log.error("couldn't find PYO button")
         log.info("sign up for Prime and this won't happen anymore")
         self.save_page_source("prime-signup-error")
         self.send_notification(
             "Prime Sign-up Error occurred",
             "prime-signup-error",
             self.take_screenshots,
         )
     if button:
         button.click()
     else:
         log.error("Prime offer page popped up, user intervention required")
         self.notification_handler.send_notification(
             "Prime offer page popped up, user intervention required")
         time.sleep(DEFAULT_MAX_WEIRD_PAGE_DELAY)
         self.driver.refresh()
 def execute(self, query):
     try:
         self.cursor.execute(query)
         self.connection.commit()
     except Error as e:
         log.error(f"Error on query execution: {e}")
         raise e
 def query_one(self, query):
     try:
         self.cursor.execute(query)
         return self.cursor.fetchone()
     except Error as e:
         log.error(f"Error on query execution: {e}")
         raise e
Пример #16
0
def amazon(
    no_image,
    headless,
    test,
    delay,
    checkshipping,
    detailed,
    used,
    single_shot,
    no_screenshots,
    disable_presence,
    disable_sound,
    slow_mode,
    p,
    log_stock_check,
    shipping_bypass,
    clean_profile,
    clean_credentials,
    alt_offers,
    captcha_wait,
):
    notification_handler.sound_enabled = not disable_sound
    if not notification_handler.sound_enabled:
        log.info("Local sounds have been disabled.")

    if clean_profile and os.path.exists(global_config.get_browser_profile_path()):
        log.info(
            f"Removing existing profile at '{global_config.get_browser_profile_path()}'"
        )
        profile_size = get_folder_size(global_config.get_browser_profile_path())
        shutil.rmtree(global_config.get_browser_profile_path())
        log.info(f"Freed {profile_size}")

    if clean_credentials and os.path.exists(AMAZON_CREDENTIAL_FILE):
        log.info(f"Removing existing Amazon credentials from {AMAZON_CREDENTIAL_FILE}")
        os.remove(AMAZON_CREDENTIAL_FILE)

    amzn_obj = Amazon(
        headless=headless,
        notification_handler=notification_handler,
        checkshipping=checkshipping,
        detailed=detailed,
        used=used,
        single_shot=single_shot,
        no_screenshots=no_screenshots,
        disable_presence=disable_presence,
        slow_mode=slow_mode,
        no_image=no_image,
        encryption_pass=p,
        log_stock_check=log_stock_check,
        shipping_bypass=shipping_bypass,
        alt_offers=alt_offers,
        wait_on_captcha_fail=captcha_wait,
    )
    try:
        amzn_obj.run(delay=delay, test=test)
    except RuntimeError:
        del amzn_obj
        log.error("Exiting Program...")
        time.sleep(5)
Пример #17
0
    def diff_dir_file(self, srcPath, destPath):
        '''
        比较两个文件夹及子目录下的文件
        '''

        if os.path.isfile(diffFile):
            try:
                #                 删除文件前先备份文件
                shutil.copyfile(diffFile, backupDiffFile)
                os.remove(diffFile)
            except Exception as e:
                log.error("备份/删除文件:%s,失败!" % diffFile)
                raise e
        else:
            log.info("no such file:%s" % diffFile)

        #         获取目录下的所有文件,返回list
        srcfile = self.get_file_list(srcPath)
        destfile = self.get_file_list(destPath)

        for sf in srcfile:
            for df in destfile:
                if sf.split("\\")[len(sf.split("\\")) -
                                  1] == df.split("\\")[len(df.split("\\")) -
                                                       1]:
                    self.diff_json(sf, df)
Пример #18
0
def error(message_str, details=None, code=500):
    payload = {'error': message_str}
    if details:
        payload['details'] = details

    log.error(payload)
    return message(payload, code)
Пример #19
0
    def handle_prime_signup(self):
        log.info("Prime offer page popped up, attempting to click No Thanks")
        button = None
        try:
            button = self.driver.find_element_by_xpath(
                '//*[@class="a-button a-button-base no-thanks-button"]')
        except exceptions.NoSuchElementException:
            try:
                button = self.driver.find_element_by_xpath(
                    '//*[@class="a-button a-button-base prime-no-button"]')
            except exceptions.NoSuchElementException:
                try:
                    button = self.driver.find_element_by_partial_link_text(
                        "No Thanks")
                except exceptions.NoSuchElementException:
                    log.error("could not find button")
                    log.info("check if PYO button hidden")
                    try:
                        button = self.driver.find_element_by_xpath(
                            '//*[@id="placeYourOrder"]/span/input')
                    except exceptions.NoSuchElementException:
                        self.save_page_source("prime-signup-error")
                        if self.no_screenshots:
                            self.notification_handler.send_notification(
                                "prime-signup-error")
                        else:
                            self.save_screenshot("prime-signup-error")

        if button:
            button.click()
        else:
            self.notification_handler.send_notification(
                "Prime offer page popped up, user intervention required")
            time.sleep(DEFAULT_MAX_WEIRD_PAGE_DELAY)
Пример #20
0
    def run_item(self, item_url, price_limit=1000, delay=3):
        log.info(f"Loading page: {item_url}")
        self.driver.get(item_url)
        try:
            product_title = self.wait.until(
                presence_of_element_located((By.ID, "productTitle")))
            log.info(f"Loaded page for {product_title.text}")
        except:
            log.error(self.driver.current_url)

        availability = self.driver.find_element_by_xpath(
            '//*[@id="availability"]').text.replace("\n", " ")

        log.info(f"Initial availability message is: {availability}")

        while not self.driver.find_elements_by_xpath(
                '//*[@id="buy-now-button"]'):
            self.driver.refresh()
            log.info("Refreshing page.")
            availability = (WebDriverWait(self.driver, 2).until(
                presence_of_element_located(
                    (By.ID, "availability"))).text.replace("\n", " "))
            log.info(f"Current availability message is: {availability}")
            time.sleep(delay)

        log.info("Item in stock, buy now button found!")
        price_str = self.driver.find_element_by_id("price_inside_buybox").text
        price_int = int(round(float(price_str.strip("$"))))
        if price_int < price_limit:
            log.info(f"Attempting to buy item for {price_int}")
            self.buy_now()
        else:
            log.info(f"Price was too high {price_int}")
Пример #21
0
def show(w, c):
    show_file = "show_c.txt"
    if w and c:
        print("Choose one option. Program Quitting")
        exit(0)
    elif w:
        show_file = "show_w.txt"
    elif c:
        show_file = "show_c.txt"
    else:
        print(
            "Option missing, you must include w or c with show argument. Program Quitting"
        )
        exit(0)

    if os.path.exists(LICENSE_PATH):

        with open(os.path.join(LICENSE_PATH, show_file)) as file:
            try:
                print(file.read())
            except FileNotFoundError:
                log.error("License File Missing. Quitting Program")
                exit(0)
    else:
        log.error("License File Missing. Quitting Program.")
        exit(0)
Пример #22
0
 def get_page(self, url):
     check_cart_element = []
     current_page = []
     try:
         check_cart_element = self.driver.find_element_by_xpath(
             '//*[@id="nav-cart"]'
         )
     except exceptions.NoSuchElementException:
         current_page = self.driver.title
     try:
         self.driver.get(url=url)
     except exceptions.WebDriverException or exceptions.TimeoutException:
         log.error(f"failed to load page at url: {url}")
         return False
     if check_cart_element:
         timeout = self.get_timeout()
         while True:
             try:
                 check_cart_element.is_displayed()
             except exceptions.StaleElementReferenceException:
                 break
             if time.time() > timeout:
                 return False
         return True
     elif self.wait_for_page_change(current_page):
         return True
     else:
         log.error("page did not change")
         return False
Пример #23
0
    def __init__(self, debug=False):
        self.notification_handler = NotificationHandler()
        self.driver = webdriver.Chrome(executable_path=binary_path,
                                       options=options,
                                       chrome_options=chrome_options)
        self.credit_card = {}
        try:
            if path.exists(CONFIG_PATH):
                with open(CONFIG_PATH) as json_file:
                    config = json.load(json_file)
                    username = config["username"]
                    password = config["password"]
                    self.credit_card["name"] = config["credit_card"]["name"]
                    self.credit_card["number"] = config["credit_card"][
                        "number"]
                    self.credit_card["cvv"] = config["credit_card"]["cvv"]
                    self.credit_card["expiration_month"] = config[
                        "credit_card"]["expiration_month"]
                    self.credit_card["expiration_year"] = config[
                        "credit_card"]["expiration_year"]
        except Exception as e:
            log.error(
                f"This is most likely an error with your {CONFIG_PATH} file.")
            raise e

        self.login(username, password)
Пример #24
0
def load_encrypted_config(config_path, encrypted_pass=None):
    """Decrypts a previously encrypted credential file and returns the contents back
    to the calling thread."""
    log.info("Reading credentials from: " + config_path)
    with open(config_path, "r") as json_file:
        data = json_file.read()
    try:
        if "nonce" in data:
            if encrypted_pass is None:
                # password = stdiomask.getpass(
                #    prompt="Credential file password: "******"*"
                #)
                password = "******"
            else:
                password = encrypted_pass
            decrypted = decrypt(data, password)
            return json.loads(decrypted)
        else:
            log.info(
                "Your configuration file is unencrypted, it will now be encrypted."
            )
            create_encrypted_config(data, config_path)
            return json.loads(data)
    except Exception as e:
        log.error(e)
        log.error(
            f"Failed to decrypt the credential file. If you have forgotten the password, delete {config_path} and rerun the bot"
        )
Пример #25
0
 def in_stock(self):
     log.info("Checking stock")
     url = "https://www.bestbuy.com/api/tcfb/model.json?paths=%5B%5B%22shop%22%2C%22scds%22%2C%22v2%22%2C%22page%22%2C%22tenants%22%2C%22bbypres%22%2C%22pages%22%2C%22globalnavigationv5sv%22%2C%22header%22%5D%2C%5B%22shop%22%2C%22buttonstate%22%2C%22v5%22%2C%22item%22%2C%22skus%22%2C{}%2C%22conditions%22%2C%22NONE%22%2C%22destinationZipCode%22%2C%22%2520%22%2C%22storeId%22%2C%22%2520%22%2C%22context%22%2C%22cyp%22%2C%22addAll%22%2C%22false%22%5D%5D&method=get".format(
         self.sku_id)
     response = self.session.get(url, headers=DEFAULT_HEADERS)
     log.info(f"Stock check response code: {response.status_code}")
     try:
         response_json = response.json()
         item_json = find_values(json.dumps(response_json),
                                 "buttonStateResponseInfos")
         item_state = item_json[0][0]["buttonState"]
         log.info(f"Item state is: {item_state}")
         if item_json[0][0][
                 "skuId"] == self.sku_id and item_state == "ADD_TO_CART":
             return True
         else:
             return False
     except Exception as e:
         log.warning(
             "Error parsing json. Using string search to determine state.")
         log.info(response_json)
         log.error(e)
         if "ADD_TO_CART" in response.text:
             log.info("Item is in stock!")
             return True
         else:
             log.info("Item is out of stock")
             return False
Пример #26
0
async def on_command_error(error, ctx):
    if isinstance(error, commands.CommandNotFound):
        return
    if isinstance(error, commands.DisabledCommand):
        await bot.send_message(ctx.message.channel, "This command has been disabled")
        return
    if isinstance(error, checks.dev_only):
        await bot.send_message(ctx.message.channel, "This command can only be ran by the bot developers")
        return
    if isinstance(error, checks.owner_only):
        await bot.send_message(ctx.message.channel, "This command can only be ran by the bot owner")
        return
    if isinstance(error, checks.not_nsfw_channel):
        await bot.send_message(ctx.message.channel, "This command can only be ran in NSFW enabled channels. It must either be named `nsfw` or the name must start with `nsfw-`")
        return
    if isinstance(error, checks.not_server_owner):
        await bot.send_message(ctx.message.channel, "Only the server owner (`{}`) can use this command".format(ctx.message.server.owner))
        return
    if isinstance(error, checks.no_permission):
        await bot.send_message(ctx.message.channel, "You do not have permission to use this command".format(ctx.message.server.owner))
        return
    if ctx.message.channel.is_private:
        await bot.send_message(ctx.message.channel, "An error occured while trying to run this command, this is most likely because it was ran in a private message channel. Please try running this command on a server.")
        return

    # In case the bot failed to send a message to the channel, the try except pass statement is to prevent another error
    try:
        await bot.send_message(ctx.message.channel, error)
    except:
        pass
    log.error("An error occured while executing the {} command: {}".format(ctx.command.qualified_name, error))
Пример #27
0
    def __init__(self, headless=False):
        if headless:
            enable_headless()
        self.driver = webdriver.Chrome(executable_path=binary_path,
                                       options=options)
        self.credit_card = {}
        self.card_pn = ""
        self.card_series = ""
        try:
            if path.exists(CONFIG_PATH):
                with open(CONFIG_PATH) as json_file:
                    config = json.load(json_file)
                    username = config["username"]
                    password = config["password"]
                    self.card_pn = config.get("card_pn")
                    self.card_series = config["card_series"]
                    self.credit_card["name"] = config["credit_card"]["name"]
                    self.credit_card["number"] = config["credit_card"][
                        "number"]
                    self.credit_card["cvv"] = config["credit_card"]["cvv"]
                    self.credit_card["expiration_month"] = config[
                        "credit_card"]["expiration_month"]
                    self.credit_card["expiration_year"] = config[
                        "credit_card"]["expiration_year"]
        except Exception as e:
            log.error(
                f"This is most likely an error with your {CONFIG_PATH} file.")
            raise e

        self.login(username, password)
Пример #28
0
    def add_to_cart(self, product_id):
        try:
            success, token = self.get_session_token()
            if not success:
                return False
            log.info(f"Session token: {token}")

            data = {"products": [{"productId": product_id, "quantity": 1}]}
            headers = DEFAULT_HEADERS.copy()
            headers["locale"] = self.locale
            headers["nvidia_shop_id"] = token
            headers["Content-Type"] = "application/json"
            response = self.session.post(
                url=NVIDIA_ADD_TO_CART_API,
                headers=headers,
                data=json.dumps(data),
                cookies=self.cj,
            )
            if response.status_code == 200:
                response_json = response.json()
                print(response_json)
                if "successfully" in response_json["message"]:
                    return True
            else:
                log.error(response.text)
                log.error(
                    f"Add to cart failed with {response.status_code}. This is likely an error with nvidia's API."
                )
            return False
        except requests.exceptions.RequestException as e:
            log.info(e)
            log.info(
                f"Got an unexpected reply from the server, API may be down, nothing we can do but try again"
            )
            return False
Пример #29
0
 def buy(self, product_id):
     pass
     try:
         log.info(
             f"Stock Check {product_id} at {self.interval} second intervals."
         )
         while not self.is_in_stock(product_id):
             self.attempt = self.attempt + 1
             time_delta = str(datetime.now() -
                              self.started_at).split(".")[0]
             with Spinner.get(
                     f"Stock Check ({self.attempt}, have been running for {time_delta})..."
             ) as s:
                 sleep(self.interval)
         if self.enabled:
             cart_success, cart_url = self.get_cart_url(product_id)
             if cart_success:
                 log.info(f"{self.gpu_long_name} added to cart.")
                 self.enabled = False
                 webbrowser.open(cart_url)
                 self.notification_handler.send_notification(
                     f" {self.gpu_long_name} with product ID: {product_id} in "
                     f"stock: {cart_url}")
             else:
                 self.buy(product_id)
     except Timeout:
         log.error("Had a timeout error.")
         self.buy(product_id)
Пример #30
0
 def check_stock(self, asin, reserve):
     f = furl(AMAZON_URLS["OFFER_URL"] + asin + "/ref=olp_f_new?f_new=true")
     try:
         self.driver.get(f.url)
         elements = self.driver.find_elements_by_xpath(
             '//*[@name="submit.addToCart"]')
         prices = self.driver.find_elements_by_xpath(
             '//*[@class="a-size-large a-color-price olpOfferPrice a-text-bold"]'
         )
     except Exception as e:
         log.debug(e)
         return False
     x = 0
     for str_price in prices:
         price = parse_price(str_price.text)
         priceFloat = price.amount
         if priceFloat is None:
             log.error("Error reading price information on row.")
             x = x + 1
             continue
         elif priceFloat <= reserve:
             log.info("Item in stock and under reserve!")
             elements[x].click()
             log.info("clicking add to cart")
             return True
         else:
             x = x + 1
     return False
Пример #31
0
async def on_command_error(error, ctx):
    if isinstance(error, commands.CommandNotFound):
        return
    if ctx.message.channel.is_private:
        await bot.send_message(ctx.message.channel, "An error occured while trying to run this command, this is most likely because it was ran in this private message channel. Please try running this command on a server.")
        return

    # In case the bot failed to send a message to the channel, the try except pass statement is to prevent another error
    try:
        await bot.send_message(ctx.message.channel, error)
    except:
        pass
    log.error("An error occured while executing the command named {}: {}".format(ctx.command.qualified_name, error))
Пример #32
0
def check_call_args(_call_args, _response, _arg_prefix):
    splited_response = _response.split()
    for idx, line in enumerate(splited_response):
        if _arg_prefix in line:
            key = line[line.find(_arg_prefix+".")+len(_arg_prefix+"."):-1]
            #unifie to string
            call = unifie_to_string(_call_args[key])
            spli = unifie_to_string(splited_response[idx+1])

            if call in spli:
                _call_args.pop(key)
            else:
                log.error("Call arg `{0}` expected `{1}`".format(_call_args[key], str(splited_response[idx+1])))
                raise ArgsCheckException("Incossisten value for `{0}` key".format(key))
            if not _call_args:
                break
    if _call_args:
        raise ArgsCheckException("No all values checked, those `{0}` still remains. ".format(_call_args))
Пример #33
0
async def on_ready():
    print("Logged in as:\n{}/{}#{}\n----------".format(bot.user.id, bot.user.name, bot.user.discriminator))
    print("Bot version: {}\nAuthor(s): {}\nCode name: {}\nBuild date: {}".format(BUILD_VERSION, BUILD_AUTHORS, BUILD_CODENAME, BUILD_DATE))
    log.debug("Debugging enabled!")
    await set_default_status()
    for extension in extensions:
        try:
            bot.load_extension(extension)
        except Exception as e:
            log.error("Failed to load extension {}\n{}: {}".format(extension, type(e).__name__, e))
    if config.enableMal:
        try:
            bot.load_extension("commands.myanimelist")
            log.info("The MyAnimeList module has been enabled!")
        except Exception as e:
            log.error("Failed to load the MyAnimeList module\n{}: {}".format(type(e).__name__, e))
    if config.enableOsu:
        log.info("The osu! module has been enabled in the config!")
    if config._dbots_token:
        log.info("Updating DBots Statistics...")
        r = requests.post("https://bots.discord.pw/api/bots/{}/stats".format(bot.user.id), json={"server_count":len(bot.servers)}, headers={"Authorization":config._dbots_token})
        if r.status_code == "200":
            log.info("Discord Bots Server count updated.")
        elif r.status_code == "401":
            log.error("An error occurred while trying to update the server count!")
    load_opus_lib()
Пример #34
0
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return
    if isinstance(error, commands.DisabledCommand):
        await ctx.send(Language.get("bot.errors.disabled_command", ctx))
        return
    if isinstance(error, checks.owner_only):
        await ctx.send(Language.get("bot.errors.owner_only", ctx))
        return
    if isinstance(error, checks.dev_only):
        await ctx.send(Language.get("bot.errors.dev_only", ctx))
        return
    if isinstance(error, checks.support_only):
        await ctx.send(Language.get("bot.errors.support_only", ctx))
        return
    if isinstance(error, checks.not_nsfw_channel):
        await ctx.send(Language.get("bot.errors.not_nsfw_channel", ctx))
        return
    if isinstance(error, checks.not_guild_owner):
        await ctx.send(Language.get("bot.errors.not_guild_owner", ctx))
        return
    if isinstance(error, checks.no_permission):
        await ctx.send(Language.get("bot.errors.no_permission", ctx))
        return
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send(Language.get("bot.errors.no_private_message", ctx))
        return
    if isinstance(ctx.channel, discord.DMChannel):
        await ctx.send(Language.get("bot.errors.command_error_dm_channel", ctx))
        return

    #In case the bot failed to send a message to the channel, the try except pass statement is to prevent another error
    try:
        await ctx.send(Language.get("bot.errors.command_error", ctx).format(error))
    except:
        pass
    log.error("An error occured while executing the {} command: {}".format(ctx.command.qualified_name, error))
Пример #35
0
            for direct in  order_direction:
                for act in active:
                    if by == "creator":
                        start = ""
                    elif by == "start_date" or by == "end_date":
                        start = "2019-03-01T00:00:00"
                    else:
                        start = 0
                    call_args = OrderedDict()
                    call_args["start"]=start
                    call_args["order_by"]=by
                    call_args["order_direction"]=direct
                    call_args["limit"]=10
                    call_args["status"]=act
                    call_args["last_id"]=""
                    resp = last_message_as_json(call_and_check(wallet.list_proposals, call_args, "args"))
                    if not "result" in resp:
                        raise ArgsCheckException("No `result` in response")

    except Exception as _ex:
        log.exception(str(_ex))
        error = True
    finally:
        if error:
            log.error("TEST `{0}` failed".format(__file__))
            exit(1)
        else:
            log.info("TEST `{0}` passed".format(__file__))
            exit(0)

Пример #36
0
async def on_ready():
    print("Connected!\n")
    print("Logged in as:\n{}/{}#{}\n----------".format(bot.user.id, bot.user.name, bot.user.discriminator))
    print("Bot version: {}\nAuthor(s): {}\nCode name: {}\nBuild date: {}".format(BUILD_VERSION, BUILD_AUTHORS, BUILD_CODENAME, BUILD_DATE))
    log.debug("Debugging enabled!")
    if config.enable_default_status:
        await set_default_status()
    else:
        await bot.change_presence(activity=discord.Activity(name="Zwei", type=discord.ActivityType.watching), status=discord.Status.dnd)
    for extension in extensions:
        try:
            bot.load_extension(extension)
        except Exception as e:
            log.error("Failed to load extension {}\n{}: {}".format(extension, type(e).__name__, e))
    if os.path.isdir("data/music"):
        try:
            bot.cogs["Music"].clear_data()
            log.info("The music cache has been cleared!")
        except:
            log.warning("Failed to clear the music cache!")
    if config.enableMal:
        try:
            bot.load_extension("commands.myanimelist")
            log.info("The MyAnimeList module has been enabled!")
        except Exception as e:
            log.error("Failed to load the MyAnimeList module\n{}: {}".format(type(e).__name__, e))
    if config.enableOsu:
        log.info("The osu! module has been enabled in the config!")
    if config._dbots_token:
        log.info("Updating DBots Statistics...")
        try:
            r = requests.post("https://bots.discord.pw/api/bots/{}/stats".format(bot.user.id), json={
                "server_count": len(bot.guilds)}, headers={"Authorization": config._dbots_token}, timeout=5)
            if r.status_code == "200":
                log.info("Discord Bots guild count updated.")
            elif r.status_code == "401":
                log.error("An error occurred while trying to update the guild count!")
        except requests.exceptions.Timeout:
            log.error("Failed to update the guild count: request timed out.")
    if config._carbonitex_key:
        log.info("Updating Carbonitex Statistics...")
        payload = {"key": config._carbonitex_key, "guildcount": len(bot.guilds), "botname": bot.user.name,
                   "logoid": bot.user.avatar_url}
        owner = discord.utils.get(list(bot.get_all_members()), id=config.owner_id)
        if owner is not None:
            payload["ownername"] = owner.name
        try:
            r = requests.post("https://www.carbonitex.net/discord/data/botdata.php", json=payload, timeout=5)
            if r.text == "1 - Success":
                log.info("Carbonitex stats updated")
            else:
                log.error("Failed to update the carbonitex stats, double check the key in the config!")
        except requests.exceptions.Timeout:
            log.error("Failed to update the carbonitex stats: request timed out")

    if config.enableSteam:
        if not config._steamAPIKey:
            log.warning("The steam module was enabled but no steam web api key was specified, disabling...")
        else:
            bot.load_extension("commands.steam")
            log.info("The steam module has been enabled!")