Exemplo n.º 1
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()
Exemplo n.º 2
0
        wallet = CliWallet(args.path, args.server_rpc_endpoint, args.cert_auth,
                           args.rpc_tls_endpoint, args.rpc_tls_cert,
                           args.rpc_http_endpoint, args.deamon,
                           args.rpc_allowip, args.wallet_file, args.chain_id,
                           args.wif)
        wallet.set_and_run_wallet()

        creator, receiver = make_user_for_tests(wallet)

        proposals_before = len(
            find_creator_proposals(
                creator,
                last_message_as_json(
                    wallet.list_proposals(creator, "creator", "asc", 50, "all",
                                          ""))))
        log.info("proposals_before {0}".format(proposals_before))

        wallet.post_comment(creator, "lorem", "", "ipsum", "Lorem Ipsum",
                            "body", "{}", "true")
        create_prop = wallet.create_proposal(creator, receiver,
                                             "2029-06-02T00:00:00",
                                             "2029-08-01T00:00:00",
                                             "1.000 TBD", "this is subject",
                                             "lorem", "true")

        proposals_after = len(
            find_creator_proposals(
                creator,
                last_message_as_json(
                    wallet.list_proposals(creator, "creator", "asc", 50, "all",
                                          ""))))
Exemplo n.º 3
0
 def test_002(self, drivers):
     """test_002 测试算法页面"""
     # 打开算法管理页面
     page = Page(drivers)
     page.click_ele('侧边栏', '算法')
     sleep(2)
     text = page.get_ele_text('通用', '页面名称')
     result = re.search('算法管理', text)
     log.info(result)
     pytest.assume(result)
     # 新建算法-取消
     page.click_ele('算法', '新建')
     page.input_ele('算法', '规格参数', 'test')
     page.click_ele('通用', '确定')
     result = page.is_exist('通用', '错误信息')
     pytest.assume(result)
     page.click_ele('通用', '取消')
     # 表单校验
     page.click_ele('算法', '新建')
     text = page.get_ele_text('通用', '对话页面')
     result = re.search('算法信息', text)
     log.info(result)
     pytest.assume(result)
     page.input_ele('算法', '算法标识', 'zmjtest')
     page.input_ele('算法', '算法名称', 'zmjtest')
     page.click_ele('算法', '算法框架')
     page.click_ele('算法', 'tensorflow')
     page.click_ele('算法', '算法分类')
     page.click_next('算法', '机器学习算法')
     page.click_ele('算法', '模型评估')
     page.ele_input_file('算法', '算法包',
                         'C:\\Users\\wangzhaoxian\\Downloads\\1.csv')
     page.input_ele('算法', '算法主类', 'zmjtest')
     page.input_ele('算法', '规格参数', '[]')
     page.input_ele('算法', '算法描述', 'zmjtest')
     page.click_ele('通用', '确定')
     # 查询-重置
     page.input_ele('算法', '查询算法名称', 'zmjtest')
     page.click_ele('算法', '重置')
     text = page.get_ele_text('算法', '查询算法名称')
     log.info(text)
     result = len(text) == 0
     pytest.assume(result)
     # 查询-无结果
     page.input_ele('算法', '查询算法名称', '1')
     page.click_ele('算法', '所属分类')
     page.click_ele('算法', '机器学习算法')
     page.click_ele('算法', '模型评估')
     page.click_ele('算法', '查询')
     sleep(3)
     text = page.get_search_table_result('算法', '结果表')
     result = re.search('暂无数据', text)
     pytest.assume(result)
     # 查询-有结果-编辑
     page.input_ele('算法', '查询算法名称', 'zmjtest')
     page.click_ele('算法', '所属分类')
     page.click_ele('算法', '机器学习算法')
     page.click_ele('算法', '模型评估')
     page.click_ele('算法', '查询')
     sleep(3)
     text = page.get_search_table_result('算法', '结果表')
     pytest.assume(text == 1)
     page.click_ele('算法', '编辑')
     page.click_ele('通用', '取消')
     page.click_ele('算法', '编辑')
     page.input_ele('算法', '算法标识', 'zmjtestupdate')
     page.click_ele('通用', '确定')
     # 删除
     page.click_ele('算法', '查询')
     sleep(3)
     page.click_ele('通用', '删除')
     page.click_ele('通用', '撤销')
     page.click_ele('通用', '删除')
     page.click_ele('通用', '确认')
     page.click_ele('算法', '查询')
     text = page.get_search_table_result('算法', '结果表')
     result = re.search('暂无数据', text)
     pytest.assume(result)
Exemplo n.º 4
0
    def __init__(self,
                 notification_handler,
                 headless=False,
                 checkshipping=False):
        self.notification_handler = notification_handler
        self.asin_list = []
        self.reserve = []
        self.checkshipping = checkshipping
        if os.path.exists(AUTOBUY_CONFIG_PATH):
            with open(AUTOBUY_CONFIG_PATH) as json_file:
                try:
                    config = json.load(json_file)
                    self.username = config["username"]
                    self.password = config["password"]
                    self.asin_groups = int(config["asin_groups"])
                    self.amazon_website = config.get("amazon_website",
                                                     "smile.amazon.com")
                    for x in range(self.asin_groups):
                        self.asin_list.append(config[f"asin_list_{x + 1}"])
                        self.reserve.append(float(config[f"reserve_{x + 1}"]))
                    # assert isinstance(self.asin_list, list)
                except Exception:
                    log.error(
                        "amazon_config.json file not formatted properly: https://github.com/Hari-Nagarajan/nvidia-bot/wiki/Usage#json-configuration"
                    )
                    exit(0)
        else:
            log.error(
                "No config file found, see here on how to fix this: https://github.com/Hari-Nagarajan/nvidia-bot/wiki/Usage#json-configuration"
            )
            exit(0)

        if headless:
            enable_headless()

        # profile_amz = ".profile-amz"
        # # keep profile bloat in check
        # if os.path.isdir(profile_amz):
        #     os.remove(profile_amz)
        options.add_argument(f"user-data-dir=.profile-amz")
        try:
            self.driver = webdriver.Chrome(executable_path=binary_path,
                                           options=options)
            self.wait = WebDriverWait(self.driver, 10)
        except Exception as e:
            log.error(e)
            exit(1)

        for key in AMAZON_URLS.keys():
            AMAZON_URLS[key] = AMAZON_URLS[key].format(
                domain=self.amazon_website)
        self.driver.get(AMAZON_URLS["BASE_URL"])
        log.info("Waiting for home page.")
        self.check_if_captcha(self.wait_for_pages, HOME_PAGE_TITLES)
        if self.is_logged_in():
            log.info("Already logged in")
        else:
            log.info("Lets log in.")

            is_smile = "smile" in AMAZON_URLS["BASE_URL"]
            xpath = ('//*[@id="ge-hello"]/div/span/a' if is_smile else
                     '//*[@id="nav-link-accountList"]/div/span')
            selenium_utils.button_click_using_xpath(self.driver, xpath)
            log.info("Wait for Sign In page")
            self.check_if_captcha(self.wait_for_pages, SIGN_IN_TITLES)
            self.login()
            log.info("Waiting 15 seconds.")
            time.sleep(
                15
            )  # We can remove this once I get more info on the phone verification page.
Exemplo n.º 5
0
from steam import WebAPI
from steam import SteamID
from steam.enums import EPersonaState
from utils.config import Config
from utils.logger import log
from utils.tools import *
from utils import checks
config = Config()

steamAPI = WebAPI(config._steam_key)

steamapikey = config._steam_key

try:
    api = WebAPI(key=steamapikey)
    log.info("Logged in to Steam via API Key")
except Exception as e:
    log.error("Error!\n" + e)


class Steam(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def steamprofile(self, ctx, communityid: str):
        """Gets steam profile information on a user with the specified community ID"""
        await ctx.channel.trigger_typing()
        steamID = SteamID.from_url(
            "http://steamcommunity.com/id/{}".format(communityid))
        if steamID is None:
Exemplo n.º 6
0
def interrupt_handler(signal_num, frame):
    log.info(f"Caught the interrupt signal.  Exiting.")
    exit(0)
Exemplo n.º 7
0
        trace_command = "tracert -d "
    else:
        trace_command = "traceroute -n "

    # Spitball test routes via Python's traceroute
    for endpoint in endpoints:
        log.info(f" {trace_command}{endpoint}")


# Register Signal Handler for Interrupt
signal(SIGINT, interrupt_handler)

main.add_command(amazon)
main.add_command(test_notifications)
main.add_command(show)
main.add_command(find_endpoints)
main.add_command(show_traceroutes)

# Global scope stuff here
if is_latest():
    log.info(f"FairGame v{version}")
elif version.is_prerelease:
    log.warning(f"FairGame PRE-RELEASE v{version}")
else:
    log.warning(
        f"You are running FairGame v{version}, but the most recent version is v{get_latest_version()}. "
        f"Consider upgrading ")

global_config = GlobalConfig()
notification_handler = NotificationHandler()
Exemplo n.º 8
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!")
Exemplo n.º 9
0
async def on_resumed():
    log.info("Reconnected to discord!")
Exemplo n.º 10
0
    def check_stock(self, asin, reserve_min, reserve_max, retry=0):
        if retry > DEFAULT_MAX_ATC_TRIES:
            log.info("max add to cart retries hit, returning to asin check")
            return False
        if self.checkshipping:
            if self.used:
                f = furl(AMAZON_URLS["OFFER_URL"] + asin)
            else:
                f = furl(AMAZON_URLS["OFFER_URL"] + asin +
                         "/ref=olp_f_new&f_new=true")
        else:
            if self.used:
                f = furl(AMAZON_URLS["OFFER_URL"] + asin +
                         "/f_freeShipping=on")
            else:
                f = furl(AMAZON_URLS["OFFER_URL"] + asin +
                         "/ref=olp_f_new&f_new=true&f_freeShipping=on")

        if not self.disable_presence:
            try:
                searching_update()
            except:
                pass

        try:
            while True:
                try:
                    self.driver.get(f.url)
                    break
                except Exception:
                    log.error(
                        "Failed to get the URL, were in the exception now.")
                    time.sleep(3)
                    pass
            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.error(e)
            return None

        in_stock = False
        for i in range(len(elements)):
            price = parse_price(prices[i].text)
            if SHIPPING_ONLY_IF in shipping[i].text:
                ship_price = parse_price("0")
            else:
                ship_price = parse_price(shipping[i].text)
            ship_float = ship_price.amount
            price_float = price.amount
            if price_float is None:
                return False
            if ship_float is None or not self.checkshipping:
                ship_float = 0

            if ((ship_float + price_float) <= reserve_max or math.isclose(
                (price_float + ship_float), reserve_max, abs_tol=0.01)) and (
                    (ship_float + price_float) >= reserve_min or math.isclose(
                        (price_float + ship_float), reserve_min,
                        abs_tol=0.01)):
                log.info("Item in stock and in reserve range!")
                log.info("clicking add to cart")

                if not self.disable_presence:
                    try:
                        buy_update()
                    except:
                        pass

                elements[i].click()
                time.sleep(self.page_wait_delay())
                if self.driver.title in SHOPING_CART_TITLES:
                    return True
                else:
                    log.info("did not add to cart, trying again")
                    log.debug(f"failed title was {self.driver.title}")
                    self.send_notification("Failed Add to Cart", "failed-atc",
                                           self.take_screenshots)
                    self.save_page_source("failed-atc")
                    in_stock = self.check_stock(
                        asin=asin,
                        reserve_max=reserve_max,
                        reserve_min=reserve_min,
                        retry=retry + 1,
                    )
        return in_stock
Exemplo n.º 11
0
    def login(self):

        try:
            log.info("Email")
            self.driver.find_element_by_xpath('//*[@id="ap_email"]').send_keys(
                self.username + Keys.RETURN)
        except exceptions.NoSuchElementException:
            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")
        try:
            self.driver.find_element_by_xpath(
                '//*[@name="rememberMe"]').click()
        except exceptions.NoSuchElementException:
            log.error("Remember me checkbox did not exist")

        log.info("Password")
        try:
            self.driver.find_element_by_xpath(
                '//*[@id="ap_password"]').send_keys(self.password +
                                                    Keys.RETURN)
        except exceptions.NoSuchElementException:
            log.error("Password entry box did not exist")

        time.sleep(self.page_wait_delay())
        if self.driver.title in TWOFA_TITLES:
            log.info("enter in your two-step verification code in browser")
            while self.driver.title in TWOFA_TITLES:
                time.sleep(DEFAULT_MAX_WEIRD_PAGE_DELAY)
        log.info(f"Logged in as {self.username}")
Exemplo n.º 12
0
    def __init__(
        self,
        notification_handler,
        headless=False,
        checkshipping=False,
        random_delay=False,
        detailed=False,
        used=False,
        single_shot=False,
        no_screenshots=False,
        disable_presence=False,
    ):
        self.notification_handler = notification_handler
        self.asin_list = []
        self.reserve_min = []
        self.reserve_max = []
        self.checkshipping = checkshipping
        self.button_xpaths = BUTTON_XPATHS
        self.random_delay = random_delay
        self.detailed = detailed
        self.used = used
        self.single_shot = single_shot
        self.disable_presence = disable_presence
        self.take_screenshots = not no_screenshots
        self.start_time = time.time()
        self.start_time_atc = 0

        if not self.disable_presence:
            start_presence("Spinning up")

        # Create necessary sub-directories if they don't exist
        if not os.path.exists("screenshots"):
            try:
                os.makedirs("screenshots")
            except:
                raise

        if not os.path.exists("html_saves"):
            try:
                os.makedirs("html_saves")
            except:
                raise

        if os.path.exists(CREDENTIAL_FILE):
            credential = load_encrypted_config(CREDENTIAL_FILE)
            self.username = credential["username"]
            self.password = credential["password"]
        else:
            log.info("No credential file found, let's make one")
            credential = self.await_credential_input()
            create_encrypted_config(credential, CREDENTIAL_FILE)
            self.username = credential["username"]
            self.password = credential["password"]

        if os.path.exists(AUTOBUY_CONFIG_PATH):
            with open(AUTOBUY_CONFIG_PATH) as json_file:
                try:
                    config = json.load(json_file)
                    self.asin_groups = int(config["asin_groups"])
                    self.amazon_website = config.get("amazon_website",
                                                     "smile.amazon.com")
                    for x in range(self.asin_groups):
                        self.asin_list.append(config[f"asin_list_{x + 1}"])
                        self.reserve_min.append(
                            float(config[f"reserve_min_{x + 1}"]))
                        self.reserve_max.append(
                            float(config[f"reserve_max_{x + 1}"]))
                    # assert isinstance(self.asin_list, list)
                except Exception as e:
                    log.error(f"{e} is missing")
                    log.error(
                        "amazon_config.json file not formatted properly: https://github.com/Hari-Nagarajan/fairgame/wiki/Usage#json-configuration"
                    )
                    exit(0)
        else:
            log.error(
                "No config file found, see here on how to fix this: https://github.com/Hari-Nagarajan/fairgame/wiki/Usage#json-configuration"
            )
            exit(0)

        if headless:
            enable_headless()

        # profile_amz = ".profile-amz"
        # # keep profile bloat in check
        # if os.path.isdir(profile_amz):
        #     os.remove(profile_amz)
        options.add_argument(f"user-data-dir=.profile-amz")

        try:
            self.driver = webdriver.Chrome(executable_path=binary_path,
                                           options=options)
            self.wait = WebDriverWait(self.driver, 10)
        except Exception as e:
            log.info("you probably have chrome open, you should close it")
            log.error(e)
            exit(1)

        for key in AMAZON_URLS.keys():
            AMAZON_URLS[key] = AMAZON_URLS[key].format(
                domain=self.amazon_website)
Exemplo n.º 13
0
def amazonajax(
    headless,
    test,
    delay,
    checkshipping,
    detailed,
    single_shot,
    no_screenshots,
    disable_presence,
    disable_sound,
    slow_mode,
    p,
    log_stock_check,
    shipping_bypass,
    clean_profile,
    clean_credentials,
    captcha_wait,
):
    log.warning(
        "Experimental test balloon.  Do not attempt to use.  Your computer could catch fire."
    )
    log.warning(
        "Do not ask for help running this in Discord. Code is work in progress and is likely broken in many places."
    )
    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)
    amazon_ajax_obj = AmazonStoreHandler(
        headless=headless,
        notification_handler=notification_handler,
        checkshipping=checkshipping,
        detailed=detailed,
        single_shot=single_shot,
        no_screenshots=no_screenshots,
        disable_presence=disable_presence,
        slow_mode=slow_mode,
        encryption_pass=p,
        log_stock_check=log_stock_check,
        shipping_bypass=shipping_bypass,
        wait_on_captcha_fail=captcha_wait,
    )

    try:

        amazon_ajax_obj.run(delay=delay, test=test)
    except RuntimeError:
        del amazon_ajax_obj
        log.error("Exiting Program...")
        time.sleep(5)
Exemplo n.º 14
0
def amazon(
    no_image,
    headless,
    disable_gpu,
    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,
    captcha_wait,
    offerid,
):
    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,
        disable_gpu=disable_gpu,
        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,
        wait_on_captcha_fail=captcha_wait,
    )

    try:
        amzn_obj.run(delay=delay, test=test, offerid=offerid)
    except RuntimeError:
        #del amzn_obj
        log.error("Exiting Program...")
        time.sleep(5)
Exemplo n.º 15
0
def train(data_loader, model, optimizer, scheduler, total_epochs,
          save_interval, save_folder, sets):
    # settings
    batches_per_epoch = len(data_loader)
    log.info('{} epochs in total, {} batches per epoch'.format(
        total_epochs, batches_per_epoch))
    loss_seg = nn.CrossEntropyLoss(ignore_index=-1)

    print("Current setting is:")
    print(sets)
    print("\n\n")
    if not sets.no_cuda:
        loss_seg = loss_seg.cuda()

    model.train()
    train_time_sp = time.time()
    for epoch in range(total_epochs):
        log.info('Start epoch {}'.format(epoch))

        scheduler.step()
        log.info('lr = {}'.format(scheduler.get_lr()))

        for batch_id, batch_data in enumerate(data_loader):
            # getting data batch
            batch_id_sp = epoch * batches_per_epoch
            volumes, label_masks = batch_data

            if not sets.no_cuda:
                volumes = volumes.cuda()

            optimizer.zero_grad()
            out_masks = model(volumes)
            # resize label
            [n, _, d, h, w] = out_masks.shape
            new_label_masks = np.zeros([n, d, h, w])
            for label_id in range(n):
                label_mask = label_masks[label_id]
                [ori_c, ori_d, ori_h, ori_w] = label_mask.shape
                label_mask = np.reshape(label_mask, [ori_d, ori_h, ori_w])
                scale = [d * 1.0 / ori_d, h * 1.0 / ori_h, w * 1.0 / ori_w]
                label_mask = ndimage.interpolation.zoom(label_mask,
                                                        scale,
                                                        order=0)
                new_label_masks[label_id] = label_mask

            new_label_masks = torch.tensor(new_label_masks).to(torch.int64)
            if not sets.no_cuda:
                new_label_masks = new_label_masks.cuda()

            # calculating loss
            loss_value_seg = loss_seg(out_masks, new_label_masks)
            loss = loss_value_seg
            loss.backward()
            optimizer.step()

            avg_batch_time = (time.time() - train_time_sp) / (1 + batch_id_sp)
            log.info(
                    'Batch: {}-{} ({}), loss = {:.3f}, loss_seg = {:.3f}, avg_batch_time = {:.3f}'\
                    .format(epoch, batch_id, batch_id_sp, loss.item(), loss_value_seg.item(), avg_batch_time))

            if not sets.ci_test:
                # save model
                if batch_id == 0 and batch_id_sp != 0 and batch_id_sp % save_interval == 0:
                    #if batch_id_sp != 0 and batch_id_sp % save_interval == 0:
                    model_save_path = '{}_epoch_{}_batch_{}.pth.tar'.format(
                        save_folder, epoch, batch_id)
                    model_save_dir = os.path.dirname(model_save_path)
                    if not os.path.exists(model_save_dir):
                        os.makedirs(model_save_dir)

                    log.info(
                        'Save checkpoints: epoch = {}, batch_id = {}'.format(
                            epoch, batch_id))
                    torch.save(
                        {
                            'ecpoch': epoch,
                            'batch_id': batch_id,
                            'state_dict': model.state_dict(),
                            'optimeizer': optimizer.state_dict()
                        }, model_save_path)

    print('Finished training')
    if sets.ci_test:
        exit()
Exemplo n.º 16
0
                            args.server_rpc_endpoint,
                            args.cert_auth,
                            #args.rpc_endpoint,
                            args.rpc_tls_endpoint,
                            args.rpc_tls_cert,
                            args.rpc_http_endpoint,
                            args.deamon, 
                            args.rpc_allowip,
                            args.wallet_file,
                            args.chain_id  )
        wallet.set_and_run_wallet()

        creator, receiver = make_user_for_tests(wallet)

        proposals_before = len(find_voter_proposals(creator, last_message_as_json( wallet.list_voter_proposals(creator, "creator", "asc", 20, "all", "") )))
        log.info("proposals_before {0}".format(proposals_before))

        wallet.post_comment(creator, "lorem", "", "ipsum", "Lorem Ipsum", "body", "{}", "true")
        wallet.create_proposal(creator, receiver, "2029-06-02T00:00:00", "2029-08-01T00:00:00", "1.000 TBD", "this is subject", "lorem", "true")
        
        resp = find_creator_proposals(creator, last_message_as_json(wallet.list_proposals(creator, "creator", "asc", 50, "all", "")))
        new_proposal_id = 0
        for r in resp:
            if r["id"] > new_proposal_id:
                new_proposal_id = r["id"]

        proposals_middle = len(find_voter_proposals(creator, last_message_as_json( wallet.list_voter_proposals(creator, "creator", "asc", 20, "all", ""))))
        log.info("proposals_middle {0}".format(proposals_middle))

        wallet.update_proposal_votes(creator, [new_proposal_id], "true", "true")
        proposals_after = len(find_voter_proposals(creator, last_message_as_json( wallet.list_voter_proposals(creator, "creator", "asc", 20, "all", "") )))
Exemplo n.º 17
0
def call_and_check(_func, _call_args, _arg_prefix):
    response = _func(*_call_args.values())
    log.info("Call response: {0}".format(response))
    check_call_args(_call_args, response, _arg_prefix)
    return response
Exemplo n.º 18
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!")
    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 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...")
        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})
        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!")
    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
        r = requests.post(
            "https://www.carbonitex.net/discord/data/botdata.php",
            json=payload)
        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!"
            )
Exemplo n.º 19
0
 def onWorkFinished(self):
     log.info('[onFinishedScan] %s' % display_name)
     self.setWorkerStatus(2)
     return True
Exemplo n.º 20
0
def call_and_check(_func, _call_args, _arg_prefix):
    response = _func(*_call_args.values())
    log.info("Call response: {0}".format(response))
    check_call_args(_call_args, response, _arg_prefix)
    return response
Exemplo n.º 21
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,
    )

    signal(SIGUSR1, amzn_obj.start)

    while True:
        if amzn_obj.wait:
            time.sleep(1)
            continue
        else:
            amzn_obj.wait = True
            signal(SIGALRM, amzn_obj.stop)
            alarm(300)  # 5 minutes

        try:
            amzn_obj.configure()
            amzn_obj.run(delay=delay, test=test)
            amzn_obj.wait = True
        except:
            log.error("Exiting AmazonBot...")
Exemplo n.º 22
0
def handler(signal, frame):
    log.info("Caught the stop, exiting.")
    exit(0)
Exemplo n.º 23
0
    def buy(self, delay=5, test=False):
        if test:
            log.info("Refreshing Page Until Title Matches ...")
            selenium_utils.wait_for_title(
                self.driver,
                "EVGA - Products - Graphics - GeForce 16 Series Family - GTX 1660",
                "https://www.evga.com/products/ProductList.aspx?type=0&family=GeForce+16+Series+Family&chipset=GTX+1660",
            )
        else:
            log.info("Refreshing Page Until Title Matches ...")
            selenium_utils.wait_for_title(
                self.driver,
                "EVGA - Products - Graphics - GeForce 30 Series Family - RTX "
                + self.card_series,
                "https://www.evga.com/products/productlist.aspx?type=0&family=GeForce+30+Series+Family&chipset=RTX+"
                + self.card_series,
            )

        log.info("matched chipset=RTX+" + self.card_series + "!")

        if self.card_pn and not test:
            # check for card
            log.info("On GPU list Page")
            card_btn = self.driver.find_elements_by_xpath(
                "//a[@href='/products/product.aspx?pn=" + self.card_pn + "']")
            while not card_btn:
                log.debug("Refreshing page for GPU")
                self.driver.refresh()
                card_btn = self.driver.find_elements_by_xpath(
                    "//a[@href='/products/product.aspx?pn=" + self.card_pn +
                    "']")
                sleep(delay)

            card_btn[0].click()

        #  Check for stock
        log.info("On GPU Page")
        atc_buttons = self.driver.find_elements_by_xpath(
            '//input[@class="btnBigAddCart"]')
        while not atc_buttons:
            log.debug("Refreshing page for GPU")
            self.driver.refresh()
            atc_buttons = self.driver.find_elements_by_xpath(
                '//input[@class="btnBigAddCart"]')
            sleep(delay)

        #  Add to cart
        atc_buttons[0].click()

        # Send notification that product is available
        self.notification_handler.send_notification(
            f"📦 Card found in stock at EVGA (P/N {self.card_pn})…")

        #  Go to checkout
        selenium_utils.wait_for_page(self.driver, "EVGA - Checkout")
        selenium_utils.button_click_using_xpath(
            self.driver, '//*[@id="LFrame_CheckoutButton"]')

        # Shipping Address screen
        selenium_utils.wait_for_page(self.driver, "Shopping")

        log.info("Skip that page.")
        self.driver.get("https://secure.evga.com/Cart/Checkout_Payment.aspx")

        selenium_utils.wait_for_page(self.driver,
                                     "EVGA - Checkout - Billing Options")

        log.info("Ensure that we are paying with credit card")
        sleep(3)
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH, './/input[@value="rdoCreditCard"]'))).click()
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH, '//*[@id="ctl00_LFrame_btncontinue"]'))).click()

        selenium_utils.wait_for_element(self.driver,
                                        "ctl00_LFrame_txtNameOnCard")

        log.info("Populate credit card fields")

        selenium_utils.field_send_keys(self.driver,
                                       "ctl00$LFrame$txtNameOnCard",
                                       self.credit_card["name"])
        selenium_utils.field_send_keys(self.driver,
                                       "ctl00$LFrame$txtCardNumber",
                                       self.credit_card["number"])
        selenium_utils.field_send_keys(self.driver, "ctl00$LFrame$txtCvv",
                                       self.credit_card["cvv"])
        Select(self.driver.find_element_by_id(
            "ctl00_LFrame_ddlMonth")).select_by_value(
                self.credit_card["expiration_month"])
        Select(self.driver.find_element_by_id(
            "ctl00_LFrame_ddlYear")).select_by_value(
                self.credit_card["expiration_year"])
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((
                By.XPATH,
                "/html/body/form/div[3]/div[3]/div/div[1]/div[5]/div[3]/div/div[1]/div/div[@id='checkoutButtons']/input[2]",
            ))).click()

        try:
            WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((
                    By.XPATH,
                    "/html/body/form/div[3]/div[3]/div/div[1]/div[5]/div[3]/div/div[1]/div/div[@id='checkoutButtons']/input[2]",
                ))).click()
        except:
            pass

        log.info("Finalize Order Page")
        selenium_utils.wait_for_page(self.driver,
                                     "EVGA - Checkout - Finalize Order")

        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(
                (By.ID, "ctl00_LFrame_cbAgree"))).click()

        if not test:
            WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable(
                    (By.ID, "ctl00_LFrame_btncontinue"))).click()

        log.info("Finalized Order!")

        # Send extra notification alerting user that we've successfully ordered.
        self.notification_handler.send_notification(
            f"🎉 Order submitted at EVGA for {self.card_pn}",
            audio_file="purchase.mp3",
        )
Exemplo n.º 24
0
 def __init__(self):
     log.info("Initializing notification handlers")
     self.twilio_handler = TwilioHandler()
     self.discord_handler = DiscordHandler()
     self.telegram_handler = TelegramHandler()
Exemplo n.º 25
0
    def checkout(self, test):
        log.info("Waiting for Cart Page")
        self.notification_handler.send_notification("Attempting to checkout")
        self.check_if_captcha(self.wait_for_pages, SHOPING_CART_TITLES)
        # self.take_screenshot("waiting-for-cart")

        try:  # This is fast.
            log.info("Quick redirect to checkout page")
            cart_initiate_id = self.driver.find_element_by_name(
                "cartInitiateId")
            cart_initiate_id = cart_initiate_id.get_attribute("value")
            self.driver.get(
                CHECKOUT_URL.format(domain=self.amazon_website,
                                    cart_id=cart_initiate_id))
        except:
            log.info("clicking checkout.")
            try:
                self.driver.find_element_by_xpath(
                    '//*[@id="hlb-ptc-btn-native"]').click()
            except:
                self.take_screenshot("start-checkout-fail")
                log.info("Failed to checkout. Returning to stock check.")
                return False

        log.info("Waiting for Place Your Order Page")
        self.wait_for_pyo_page()

        log.info("Attempting to Finish checkout")
        # self.take_screenshot("finish-checkout")

        if not self.finalize_order_button(test):
            log.info("Failed to click finalize the order")
            # self.take_screenshot("finalize-fail")
            return False

        log.info("Waiting for Order completed page.")
        if not self.wait_for_order_completed(test):
            log.info("order not completed, going back to stock check")
            return False

        log.info("Order Placed.")
        self.take_screenshot("order-placed")
        return True
from utils.logger import log, init_logger

if __name__ == "__main__":
    try:
        init_logger(__file__)
        error = False
        wallet = CliWallet(args.path, args.server_rpc_endpoint, args.cert_auth,
                           args.rpc_tls_endpoint, args.rpc_tls_cert,
                           args.rpc_http_endpoint, args.deamon,
                           args.rpc_allowip, args.wallet_file, args.chain_id)
        wallet.set_and_run_wallet()

        error_msg_x = "The value `x` for `_last_id` argument is invalid, it should be integer type."
        resp_error_x = wallet.list_proposals(args.creator, "creator", "asc",
                                             50, "all", "x")
        log.info(resp_error_x)
        if resp_error_x.find(error_msg_x) == -1:
            raise ArgsCheckException(
                "Assertion `{0}` is required.".format(error_msg_x))

        error_msg_y = "The value `y` for `_last_id` argument is invalid, it should be integer type."
        resp_error_y = wallet.list_proposals(args.creator, "creator", "asc",
                                             50, "all", "y")
        log.info(resp_error_y)
        if resp_error_y.find(error_msg_y) == -1:
            raise ArgsCheckException(
                "Assertion `{0}` is required.".format(error_msg_y))

        error_msg_10 = "The value `10` for `_last_id` argument is invalid, it should be integer type."
        resp_10 = wallet.list_proposals(args.creator, "creator", "asc", 50,
                                        "all", "10")
Exemplo n.º 27
0
 def test_001(self, drivers):
     """test_001 测试实验页面"""
     # 打开实验管理页面
     page = Page(drivers)
     page.input_ele('登录', '用户名', 'wangzhaoxian')
     page.input_ele('登录', '密码', '123456')
     page.click_ele('登录', '登录')
     page.click_ele('侧边栏', '实验')
     text = page.get_ele_text('通用', '页面名称')
     result = re.search('实验列表', text)
     log.info(result)
     pytest.assume(result)
     # 测试新增页面取消按键
     page.click_ele('实验', '新增实验')
     text = page.get_ele_text('通用', '对话页面')
     result = re.search('实验信息', text)
     log.info(result)
     pytest.assume(result)
     page.click_ele('通用', '取消')
     # 表单校验
     page.click_ele('实验', '新增实验')
     page.click_ele('通用', '确定')
     text = page.get_ele_text('通用', '错误信息')
     result = re.search('必须', text)
     log.info(result)
     pytest.assume(result)
     # 测试实验页面新增实验
     page.input_ele('实验', '实验命名', 'Ctest')
     page.input_ele('实验', '模型描述', '测试')
     page.click_ele('通用', '确定')
     page.click_ele('翻页', '第4页')
     result = page.exist_ele('实验', '测试')
     pytest.assume(result)
     # 测试实验页面修改-取消
     page.click_ele('翻页', '第4页')
     page.click_ele('实验', '测试')
     page.click_ele('通用', '取消')
     # 测试实验页面修改-编辑
     page.click_ele('翻页', '第4页')
     page.click_ele('实验', '测试')
     result = page.enable_ele('实验', '实验命名')
     pytest.assume(result is False)
     result = page.enable_ele('实验', '模型描述')
     pytest.assume(result is False)
     # 修改
     page.click_ele('实验', '编辑')
     page.input_ele('实验', '实验命名', 'testupdate')
     page.input_ele('实验', '模型描述', '测试修改')
     page.click_ele('通用', '确定')
     page.click_ele('翻页', '第4页')
     result = page.exist_ele('实验', '修改后')
     pytest.assume(result)
     # 测试打开
     page.click_ele('翻页', '第4页')
     page.click_ele('实验', '实验打开')
     page.click_ele('关闭', '编排')
     # 测试删除-取消
     sleep(1)
     page.click_ele('翻页', '第4页')
     page.click_ele('实验', '删除')
     page.click_ele('通用', '撤销')
     result = page.exist_ele('实验', '修改后')
     pytest.assume(result)
     # 测试删除-确认
     page.click_ele('实验', '删除')
     page.click_ele('通用', '确认')
     sleep(1)
     page.click_ele('翻页', '第4页')
     result_text = page.imagine
     log.info("实验名称:{}".format(result_text))
     if "testupdate" in result_text:
         result = False
     else:
         result = True
     pytest.assume(result)
Exemplo n.º 28
0
def pytest_runtest_setup(item):
    test_id, _ = get_test_meta(item)
    log.info("Setup for test: '%s'", test_id)
Exemplo n.º 29
0
def pytest_runtest_call(item):
    test_id, test_summary = get_test_meta(item)
    log.info("Start test: '%s'", test_id)
    if test_summary:
        log.info("Test summary: '%s'", test_summary)
Exemplo n.º 30
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 in [
                 "ADD_TO_CART",
                 "PRE_ORDER",
         ]:
             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
        error = False
        wallet = CliWallet( args.path,
                            args.server_rpc_endpoint,
                            args.cert_auth,
                            args.rpc_tls_endpoint,
                            args.rpc_tls_cert,
                            args.rpc_http_endpoint,
                            args.deamon, 
                            args.rpc_allowip,
                            args.wallet_file,
                            args.chain_id  )
        wallet.set_and_run_wallet()

        error_msg_x  = "The value `x` for `_last_id` argument is invalid, it should be integer type."
        resp_error_x = wallet.list_proposals(args.creator, "creator", "asc", 50, "all", "x")
        log.info(resp_error_x)
        if resp_error_x.find(error_msg_x) == -1:
            raise ArgsCheckException("Assertion `{0}` is required.".format(error_msg_x))

        error_msg_y  = "The value `y` for `_last_id` argument is invalid, it should be integer type."
        resp_error_y = wallet.list_proposals(args.creator, "creator", "asc", 50, "all", "y")
        log.info(resp_error_y)
        if resp_error_y.find(error_msg_y) == -1:
            raise ArgsCheckException("Assertion `{0}` is required.".format(error_msg_y))

        error_msg_10 = "The value `10` for `_last_id` argument is invalid, it should be integer type."
        resp_10      = wallet.list_proposals(args.creator, "creator", "asc", 50, "all", "10")
        log.info(resp_10)
        if resp_10.find(error_msg_10) != -1:
            raise ArgsCheckException("There should be no assertion `{0}`.".format(error_msg_10))
        if not "result" in last_message_as_json(resp_10):
Exemplo n.º 32
0
    def auto_add_to_cart(self):
        log.info("Attempting to auto add to cart...")

        body = {"items": [{"skuId": self.sku_id}]}
        headers = {
            "Accept": "application/json",
            "authority": "www.bestbuy.com",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36",
            "Content-Type": "application/json; charset=UTF-8",
            "Sec-Fetch-Site": "same-origin",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "origin": "https://www.bestbuy.com",
            "referer": self.product_url,
            "Content-Length": str(len(json.dumps(body))),
        }
        # [
        #     log.info({'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path})
        #     for c in self.session.cookies
        # ]
        log.info("Making request")
        response = self.session.post(BEST_BUY_ADD_TO_CART_API_URL,
                                     json=body,
                                     headers=headers,
                                     timeout=5)
        log.info(response.status_code)
        if (response.status_code == 200 and response.json()["cartCount"] > 0
                and self.sku_id in response.text):
            log.info(f"Added {self.sku_id} to cart!")
            log.info(response.json())
        else:
            log.info(response.status_code)
            log.info(response.json())
Exemplo n.º 33
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)

Exemplo n.º 34
0
 def submit_shipping(self):
     log.info("Starting Checkout")
     headers = {
         "accept": "application/json, text/javascript, */*; q=0.01",
         "accept-encoding": "gzip, deflate, br",
         "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
         "content-type": "application/json",
         "origin": "https://www.bestbuy.com",
         "referer": "https://www.bestbuy.com/cart",
         "user-agent":
         "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36",
         "x-user-interface": "DotCom-Optimized",
         "x-order-id": self.order_id,
     }
     while True:
         log.info("Submitting Shipping")
         body = {"selected": "SHIPPING"}
         response = self.session.put(
             "https://www.bestbuy.com/cart/item/{item_id}/fulfillment".
             format(item_id=self.item_id),
             headers=headers,
             json=body,
         )
         response_json = response.json()
         log.info(response.status_code)
         log.info(response_json)
         if (response.status_code == 200
                 and response_json["order"]["id"] == self.order_id):
             log.info("Submitted Shipping")
             return True
         else:
             log.info("Error Submitting Shipping")
Exemplo n.º 35
0
async def on_resumed():
    log.info("Reconnected to discord!")
Exemplo n.º 36
0
    def __init__(self, sku_id, notification_handler, headless=False):
        self.notification_handler = notification_handler
        self.sku_id = sku_id
        self.session = requests.Session()
        self.auto_buy = False
        self.account = {"username": "", "password": ""}

        adapter = HTTPAdapter(max_retries=Retry(
            total=3,
            backoff_factor=1,
            status_forcelist=[429, 500, 502, 503, 504],
            method_whitelist=["HEAD", "GET", "OPTIONS", "POST"],
        ))
        self.session.mount("https://", adapter)
        self.session.mount("http://", adapter)

        response = self.session.get(BEST_BUY_PDP_URL.format(sku=self.sku_id),
                                    headers=DEFAULT_HEADERS)
        log.info(f"PDP Request: {response.status_code}")
        self.product_url = response.url
        log.info(f"Product URL: {self.product_url}")

        self.session.get(self.product_url)
        log.info(f"Product URL Request: {response.status_code}")

        if self.auto_buy:
            log.info("Loading headless driver.")
            if headless:
                enable_headless(
                )  # TODO - check if this still messes up the cookies.
            options.add_argument(
                "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"
            )

            self.driver = webdriver.Chrome(
                executable_path=binary_path,
                options=options,
            )
            log.info("Loading https://www.bestbuy.com.")
            self.login()

            self.driver.get(self.product_url)
            cookies = self.driver.get_cookies()

            [
                self.session.cookies.set_cookie(
                    requests.cookies.create_cookie(
                        domain=cookie["domain"],
                        name=cookie["name"],
                        value=cookie["value"],
                    )) for cookie in cookies
            ]

            # self.driver.quit()

            log.info("Calling location/v1/US/approximate")
            log.info(
                self.session.get(
                    "https://www.bestbuy.com/location/v1/US/approximate",
                    headers=DEFAULT_HEADERS,
                ).status_code)

            log.info("Calling basket/v1/basketCount")
            log.info(
                self.session.get(
                    "https://www.bestbuy.com/basket/v1/basketCount",
                    headers={
                        "x-client-id": "browse",
                        "User-Agent":
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36",
                        "Accept": "application/json",
                    },
                ).status_code)
Exemplo n.º 37
0
async def on_command_preprocess(ctx):
    if isinstance(ctx.channel, discord.DMChannel):
        guild = "Private Message"
    else:
        guild = "{}/{}".format(ctx.guild.id, ctx.guild.name)
    log.info("[Command] [{}] [{}/{}]: {}".format(guild, ctx.author.id, ctx.author, ctx.message.content))
Exemplo n.º 38
0
 def open_cart_url(self):
     log.info("Opening cart.")
     params = {"token": self.access_token}
     url = furl(DIGITAL_RIVER_CHECKOUT_URL).set(params)
     webbrowser.open_new_tab(url.url)
     return url.url