Esempio n. 1
0
 def _new_proxy(self):
     ip = ProxyStack().get_random()
     self.proxies = {
         'http': 'http://' + ip,
         'https': 'https://' + ip,
     }
     log.warning(('set new proxy', ip))
Esempio n. 2
0
async def restart(ctx):
    """Restarts the bot"""
    await bot.say(
        "I'm gonna leave because I'm mad at you, and then I'll come back. See you."
    )
    log.warning("{} has restarted the bot!".format(ctx.message.author))
    await _restart_bot()
Esempio n. 3
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_cache()
            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.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!")
Esempio n. 4
0
    def add_to_cart(self, product_id):
        try:
            log.debug(f"Checking if item ({product_id}) in stock")
            params = {
                "apiKey": DIGITAL_RIVER_API_KEY,
                "token": self.access_token,
                "productId": product_id,
                "format": "json",
            }
            response = self.session.post(
                DIGITAL_RIVER_ADD_TO_CART_API_URL,
                headers=DEFAULT_HEADERS,
                params=params,
            )

            if response.status_code == 200:
                log.info(f"{self.gpu_long_name} ({product_id}) in stock!")
                return True
            elif response.status_code == 409:
                try:
                    response_json = response.json()
                    log.debug(f"Error: {response_json['errors']['error']}")
                    for error in response_json["errors"]["error"]:
                        if error["code"] == "invalid-product-id":
                            raise ProductIDChangedException()
                except json.decoder.JSONDecodeError as er:
                    log.warning(f"Failed to decode json: {response.text}")
            else:
                log.debug("item not in stock")
                return False
        except Exception as ex:
            log.debug(str(ex))
            log.debug("The connection has been reset.")
            return False
Esempio n. 5
0
    def show_config(self):
        log.info(f"{'=' * 50}")
        log.info(f"Starting Amazon ASIN Hunt for {len(self.asin_list)} Products with:")
        log.info(f"--Delay of {self.refresh_delay} seconds")
        if self.used:
            log.info(f"--Used items are considered for purchase")
        if self.checkshipping:
            log.info(f"--Shipping costs are included in price calculations")
        else:
            log.info(f"--Free Shipping items only")
        if self.single_shot:
            log.info("\tSingle Shot purchase enabled")
        if not self.take_screenshots:
            log.info(
                f"--Screenshotting is Disabled, DO NOT ASK FOR HELP IN TECH SUPPORT IF YOU HAVE NO SCREENSHOTS!"
            )
        if self.detailed:
            log.info(f"--Detailed screenshots/notifications is enabled")
        if self.testing:
            log.warning(f"--Testing Mode.  NO Purchases will be made.")
        if self.slow_mode:
            log.warning(f"--Slow-mode enabled. Pages will fully load before execution")

        for idx, asins in enumerate(self.asin_list):
            log.info(
                f"--Looking for {len(asins)} ASINs between {self.reserve_min[idx]:.2f} and {self.reserve_max[idx]:.2f}"
            )
        log.info(f"{'=' * 50}")
Esempio n. 6
0
def parse_arguments() -> Tuple[Dict, torch.device]:
    path = osp.join('data', 'biogrid')
    parser = argparse.ArgumentParser(description="Config file parser")
    parser.add_argument("-c", "--config", help="json config file", type=str)
    parser.add_argument("-s", "--scheme", help="json scheme file", type=str)
    args = parser.parse_args()

    json_data: dict = json.load(open(args.config))
    set_file_logger(json_data)
    # DGL Overrides torch.tensor.to() and implements it's own to() method for its graph objects
    device = torch.device(
        "cuda" if json_data["cuda"] and torch.cuda.is_available() else "cpu")
    log.info(f"Using {device} for compute")

    # See htttps://discuss.pytorch.org/t/what-does-torch-backends-cudnn-benchmark-do/5936
    # benchmark mode is good whenever your input sizes for your network do not vary
    torch.backends.cudnn.benchmark = True if not json_data.get(
        "cuda", False) and torch.cuda.is_available() else False

    git_hash = subprocess.check_output(["git", "describe",
                                        "--always"]).strip().decode()
    git_branch = subprocess.check_output(
        ["git", "rev-parse", "--abbrev-ref", "HEAD"]).strip().decode()
    log.info(f"Git hash: {git_hash}, branch: {git_branch}")

    if json_data["validate"]:
        try:
            json_scheme: dict = json.load(open(args.scheme))
            jsonschema.validate(json_data, json_scheme)
        except jsonschema.ValidationError:
            log.warning("Tried to validate but failed, continuing run anyway")

    return json_data, device
Esempio n. 7
0
def solve_captcha(session, form_element, pdp_url: str):
    log.warning("Encountered CAPTCHA. Attempting to solve.")
    # Starting from the form, get the inputs and image
    captcha_images = form_element.xpath(
        '//img[contains(@src, "amazon.com/captcha/")]')
    if captcha_images:
        link = captcha_images[0].attrib["src"]
        # link = 'https://images-na.ssl-images-amazon.com/captcha/usvmgloq/Captcha_kwrrnqwkph.jpg'
        captcha = AmazonCaptcha.fromlink(link)
        solution = captcha.solve()

        if solution:
            form_inputs = form_element.xpath(".//input")
            input_dict = {}
            for form_input in form_inputs:
                if form_input.type == "text":
                    input_dict[form_input.name] = solution
                else:
                    input_dict[form_input.name] = form_input.value
            f = furl(
                pdp_url)  # Use the original URL to get the schema and host
            f = f.set(path=form_element.attrib["action"])
            f.add(args=input_dict)
            response = session.get(f.furl)
            log.debug(f"Captcha response was {response.status_code}")
            return response.text, response.status_code

    return html.fromstring(""), 404
Esempio n. 8
0
async def shutdown(ctx):
    """Shuts down the bot"""
    await bot.say(
        "I'm leaving you, it's over. See me in magistrate court tomorrow for our divorce."
    )
    log.warning("{} has shut down the bot!".format(ctx.message.author))
    await _shutdown_bot()
Esempio n. 9
0
 def buy(self, product_id):
     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 = self.add_to_cart(product_id)
             if cart_success:
                 log.info(f"{self.gpu_long_name} added to cart.")
                 self.enabled = False
                 webbrowser.open(NVIDIA_CART_URL)
                 self.notification_handler.send_notification(
                     f" {self.gpu_long_name} with product ID: {product_id} in "
                     f"stock: {NVIDIA_CART_URL}")
             else:
                 self.notification_handler.send_notification(
                     f" ERROR: Attempted to add {self.gpu_long_name} to cart but couldn't, check manually!"
                 )
                 self.buy(product_id)
     except requests.exceptions.RequestException as e:
         log.warning(
             "Connection error while calling Nvidia API. API may be down.")
         log.info(
             f"Got an unexpected reply from the server, API may be down, nothing we can do but try again"
         )
         self.buy(product_id)
Esempio n. 10
0
    def check(self):
        if not self._token:
            log.critical(
                "No token was specified in the config, please put your bot's token in the config."
            )
            os._exit(1)

        if not self.owner_id:
            log.critical(
                "No owner ID was specified in the config, please put your ID for the owner ID in the config"
            )
            os._exit(1)

        if len(self.dev_ids) is not 0:
            try:
                ids = self.dev_ids.split()
                self.dev_ids = []
                for id in ids:
                    self.dev_ids.append(int(id))
            except:
                log.warning(
                    "Developer IDs are invalid, all developer IDs have been ignored!"
                )
                self.dev_ids = Defaults.dev_ids

        if len(self.support_ids) is not 0:
            try:
                ids = self.support_ids.split()
                self.support_ids = []
                for id in ids:
                    self.support_ids.append(int(id))
            except:
                log.warning(
                    "Support IDs are invalid, all support member IDs have been ignored!"
                )
                self.support_ids = Defaults.support_ids

        if self.enableMal:
            if not self._malUsername and not self._malPassword:
                log.critical(
                    "The MyAnimeList module was enabled, but no MAL credinals were specified!"
                )

            if not self._malUsername:
                log.critical(
                    "The MyAnimeList module was enabled, but no MAL username was specified!"
                )
                os._exit(1)

            if not self._malPassword:
                log.critical(
                    "The MyAnimeList module was enabled, but no MAL password was specified!"
                )
                os._exit(1)

        if self.enableOsu and not self._osuKey:
            log.critical(
                "The osu! module was enabled but no osu! api key was specified!"
            )
            os._exit(1)
Esempio n. 11
0
def resolve_domain(domain):
    import dns.resolver

    public_dns_servers = global_config.get_fairgame_config().get(
        "public_dns_servers")
    resolutions = 0
    endpoints = set()

    # Resolve the domain for each DNS server to find out how many end points we have
    for provider in public_dns_servers:
        # Provider is Google, Verisign, etc.
        log.info(f"Testing {provider}")
        for server in public_dns_servers[provider]:
            # Server is 8.8.8.8 or 1.1.1.1
            my_resolver = dns.resolver.Resolver()
            my_resolver.nameservers = [server]

            try:
                resolved = my_resolver.resolve(domain)
            except Exception as e:
                log.warning(
                    f"Unable to resolve using {provider} server {server} due to: {e}"
                )
                continue
            for rdata in resolved:
                ipv4_address = rdata.address
                endpoints.add(ipv4_address)
                resolutions += 1
                log.debug(f"{domain} resolves to {ipv4_address} via {server}")
    return endpoints, resolutions
Esempio n. 12
0
async def shutdown(ctx):
    """Logs out and shuts down the bot"""
    await bot.say("Shutting down...")
    log.warning("{} has shut down the bot!".format(
        format_user(ctx.message.author)))
    await bot.cogs["Music"].disconnect_all_voice_clients()
    await bot.logout()
Esempio n. 13
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
Esempio n. 14
0
 async def restart(self, ctx):
     """Restarts the bot"""
     await ctx.send("Restarting...")
     log.warning("{} has restarted the bot!".format(ctx.author))
     try:
         await aiosession.close()
     except:
         pass
     await self.bot.close()
     subprocess.call([sys.executable, "bot.py"])
Esempio n. 15
0
 async def log_to_channel(self, msg):
     if config.channel_logger_id:
         channel = self.bot.get_channel(int(config.channel_logger_id))
         if not channel:
             log.warning("Can't find logging channel")
         else:
             try:
                 await channel.send(":stopwatch: `{}` {}".format(time.strftime(config.log_time_format), msg))
             except discord.errors.Forbidden:
                 log.warning("Could not log to the channel log channel because I do not have permission to send messages in it!")
Esempio n. 16
0
    def run_checks():
        if not os.path.isdir("data"):
            log.warning('No folder named "data" was found, creating one... (This message is harmless)')
            os.makedirs("data")

        if not os.path.isdir("assets"):
            log.critical(
                'There is no folder named "assets"! Please go to the github repo and download the assets folder!'
            )
            os._exit(1)
Esempio n. 17
0
 async def log_to_channel(self, msg):
     if config.channel_logger_id:
         channel = self.bot.get_channel(config.channel_logger_id)
         if not channel:
             log.warning("Can't find logging channel")
         else:
             try:
                 await self.bot.send_message(channel, ":stopwatch: `{}` {}".format(time.strftime(config.log_timeformat), msg))
             except discord.errors.Forbidden:
                 log.warning("Could not log to the channel log channel because I do not have permission to send messages in it!")
Esempio n. 18
0
def area_screenshot(locator, path):
    """区域截图"""
    log.warning("需要截图的元素坐标%s" % locator.location)
    log.warning("需要截图的元素大小%s" % locator.size)
    shot = (locator.location['x'], locator.location['y'],
            locator.location['x'] + locator.size['width'],
            locator.location['y'] + locator.size['height'])
    im = Image.open(path)
    im = im.crop(shot)
    im.save(path)
    sleep()
Esempio n. 19
0
    def run_checks():
        if not os.path.isdir("data"):
            log.warning(
                "No folder named \"data\" was found, creating one... (This message is harmless)"
            )
            os.makedirs("data")

        if not os.path.isdir("assets"):
            log.critical(
                "There is no folder named \"assets\"! Please go to the github repo and download the assets folder!"
            )
            os._exit(1)
Esempio n. 20
0
    def run_checks():
        if not os.path.isdir("data"):
            log.warning("No folder named \"data\" was found, creating one... (This message is harmless)")
            os.makedirs("data")

        if not os.path.isfile("data/languages.json"):
            log.warning("The file \"languages.json\" in the \"data\" folder was not found, creating one... (This message is harmless)")
            with open("data/languages.json", "w+") as file:
                file.write("{}")

        if not os.path.isdir("assets"):
            log.critical("There is no folder named \"assets\"! Please go to the github repo and download the assets folder!")
            os._exit(1)
Esempio n. 21
0
    def create_driver(self):
        if self.setup_driver:

            if self.headless:
                enable_headless()

            # profile_amz = ".profile-amz"
            # # keep profile bloat in check
            # if os.path.isdir(profile_amz):
            #     os.remove(profile_amz)
            prefs = {
                "profile.password_manager_enabled": False,
                "credentials_enable_service": False,
            }
            if self.no_image:
                prefs["profile.managed_default_content_settings.images"] = 2
            else:
                prefs["profile.managed_default_content_settings.images"] = 0
            options.add_experimental_option("prefs", prefs)
            options.add_argument(f"user-data-dir=.profile-amz")
            if not self.slow_mode:
                options.set_capability("pageLoadStrategy", "none")

            self.setup_driver = False

        # Delete crashed, so restore pop-up doesn't happen
        path_to_prefs = os.path.join(
            os.path.dirname(os.path.abspath("__file__")),
            ".profile-amz",
            "Default",
            "Preferences",
        )
        try:
            with fileinput.FileInput(path_to_prefs, inplace=True) as file:
                for line in file:
                    print(line.replace("Crashed", "none"), end="")
        except FileNotFoundError:
            pass
        try:
            self.driver = webdriver.Chrome(executable_path=binary_path, options=options)
            self.wait = WebDriverWait(self.driver, 10)
            self.get_webdriver_pids()
        except Exception as e:
            log.error(e)
            log.warning(
                "You probably have a previous Chrome window open. You should close it"
            )
            return False

        return True
Esempio n. 22
0
    def __init__(self):

        if not os.path.isfile("config/config.ini"):
            if not os.path.isfile("config/config.ini.example"):
                log.critical("There is no \"config.ini.example\" file in the \"config\" folder! Please go to the github repo and download it and then put it in the \"config\" folder!")
                os._exit(1)
            else:
                shutil.copy("config/config.ini.example", "config/config.ini")
                log.warning("Created the \"config.ini\" file in the config folder! Please edit the config and then run the bot again!")
                os._exit(1)

        self.config_file = "config/config.ini"

        config = configparser.ConfigParser(interpolation=None)
        config.read(self.config_file, encoding="utf-8")

        sections = {"Credentials", "Bot", "Status", "Logging", "MyAnimeList", "Osu", "Steam"}.difference(config.sections())
        if sections:
            log.critical("Could not load a section in the config file, please obtain a new config file from the github repo if regenerating the config doesn't work!")
            os._exit(1)
        self._token = config.get("Credentials", "Token", fallback=Defaults.token)
        self._dbots_token = config.get("Credentials", "Dbots_Token", fallback=Defaults.dbots_token)
        self._carbonitex_key = config.get("Credentials", "Carbonitex_Key", fallback=Defaults.carbonitex_key)
        self.owner_id = config.getint("Bot", "Owner_ID", fallback=Defaults.owner_id)
        self.command_prefix = config.get("Bot", "Command_Prefix", fallback=Defaults.command_prefix)
        self.max_nsfw_count = config.getint("Bot", "Max_NSFW_Count", fallback=Defaults.max_nsfw_count)
        self.dev_ids = config.get("Bot", "Developer_IDs", fallback=Defaults.dev_ids)
        self.support_ids = config.get("Bot", "Support_IDs", fallback=Defaults.support_ids)
        self.skip_votes_needed = config.getint("Bot", "Skip_Votes_Needed", fallback=Defaults.skip_votes_needed)
        self.lock_status = config.getboolean("Status", "Lock_Status", fallback=Defaults.lock_status)
        self.enable_default_status = config.getboolean("Status", "Enable_Default_Status", fallback=Defaults.enable_default_status)
        self.default_status_name = config.get("Status", "Default_Status_Name", fallback=Defaults.default_status_name)
        self.default_status_type = config.get("Status", "Default_Status_Type", fallback=Defaults.default_status_type)
        self.debug = config.getboolean("Logging", "Debug", fallback=Defaults.debug)
        self.channel_logger_id = config.get("Logging", "Channel_Logger_ID", fallback=Defaults.channel_logger_id)
        self.log_time_format = config.get("Logging", "Time_Format", fallback=Defaults.log_time_format)
        self.log_date_format = config.get("Logging", "Date_Format", fallback=Defaults.log_date_format)
        self.enableMal = config.getboolean("MyAnimeList", "enable", fallback=Defaults.enableMal)
        self._malUsername = config.get("MyAnimeList", "username", fallback=Defaults.malUsername)
        self._malPassword = config.get("MyAnimeList", "password", fallback=Defaults.malPassword)
        self.enableOsu = config.getboolean("Osu", "enable", fallback=Defaults.enableOsu)
        self._osuKey = config.get("Osu", "key", fallback=Defaults.osuKey)
        self.enableSteam = config.get("Steam", "enable", fallback=Defaults.osuKey)
        self._steamAPIKey = config.get("Steam", "key", fallback=Defaults.osuKey)
        self._twitchClientID = config.get("Twitch", "client_id", fallback=Defaults.twitchClientID)
        self._googleAPIKey = config.get("Google", "api_key", fallback=Defaults.googleAPIKey)
        self._catAPIKey = config.get("Cats", "api_key", fallback=Defaults.googleAPIKey)

        self.check()
Esempio n. 23
0
def check_version():
    try:
        r = requests.get(LATEST_URL)
        data = r.json()
        remote_version = str(data["tag_name"])

        if version < remote_version:
            log.warning(
                f"You are running FairGame v{version}, but the most recent version is v{remote_version}... Consider upgrading"
            )
        else:
            log.info(f"FairGame v{version}")
    except:
        log.error("Failed version check.  Continuing execution with mystery code.")
        pass
Esempio n. 24
0
    def __init__(self):

        if not os.path.isfile("config/config.ini"):
            if not os.path.isfile("config/config.ini.example"):
                log.critical("There is no \"config.ini.example\" file in the \"config\" folder! Please go to the github repo and download it and then put it in the \"config\" folder!")
                os._exit(1)
            else:
                shutil.copy("config/config.ini.example", "config/config.ini")
                log.warning("Created the \"config.ini\" file in the config folder! Please edit the config and then run the bot again!")
                os._exit(1)

        self.config_file = "config/config.ini"

        config = configparser.ConfigParser(interpolation=None)
        config.read(self.config_file, encoding="utf-8")

        sections = {"Credentials", "Bot", "Status", "Logging", "MyAnimeList", "Osu", "Steam"}.difference(config.sections())
        if sections:
            log.critical("Could not load a section in the config file, please obtain a new config file from the github repo if regenerating the config doesn't work!")
            os._exit(1)
        self._token = config.get("Credentials", "Token", fallback=Defaults.token)
        self._dbots_token = config.get("Credentials", "Dbots_Token", fallback=Defaults.dbots_token)
        self._carbonitex_key = config.get("Credentials", "Carbonitex_Key", fallback=Defaults.carbonitex_key)
        self.owner_id = config.getint("Bot", "Owner_ID", fallback=Defaults.owner_id)
        self.command_prefix = config.get("Bot", "Command_Prefix", fallback=Defaults.command_prefix)
        self.max_nsfw_count = config.getint("Bot", "Max_NSFW_Count", fallback=Defaults.max_nsfw_count)
        self.dev_ids = config.get("Bot", "Developer_IDs", fallback=Defaults.dev_ids)
        self.support_ids = config.get("Bot", "Support_IDs", fallback=Defaults.support_ids)
        self.skip_votes_needed = config.getint("Bot", "Skip_Votes_Needed", fallback=Defaults.skip_votes_needed)
        self.lock_status = config.getboolean("Status", "Lock_Status", fallback=Defaults.lock_status)
        self.enable_default_status = config.getboolean("Status", "Enable_Default_Status", fallback=Defaults.enable_default_status)
        self.default_status_name = config.get("Status", "Default_Status_Name", fallback=Defaults.default_status_name)
        self.default_status_type = config.get("Status", "Default_Status_Type", fallback=Defaults.default_status_type)
        self.debug = config.getboolean("Logging", "Debug", fallback=Defaults.debug)
        self.channel_logger_id = config.get("Logging", "Channel_Logger_ID", fallback=Defaults.channel_logger_id)
        self.log_time_format = config.get("Logging", "Time_Format", fallback=Defaults.log_time_format)
        self.log_date_format = config.get("Logging", "Date_Format", fallback=Defaults.log_date_format)
        self.enableMal = config.getboolean("MyAnimeList", "enable", fallback=Defaults.enableMal)
        self._malUsername = config.get("MyAnimeList", "username", fallback=Defaults.malUsername)
        self._malPassword = config.get("MyAnimeList", "password", fallback=Defaults.malPassword)
        self.enableOsu = config.getboolean("Osu", "enable", fallback=Defaults.enableOsu)
        self._osuKey = config.get("Osu", "key", fallback=Defaults.osuKey)
        self.enableSteam = config.get("Steam", "enable", fallback=Defaults.osuKey)
        self._steamAPIKey = config.get("Steam", "key", fallback=Defaults.osuKey)
        self._twitchClientID = config.get("Twitch", "client_id", fallback=Defaults.twitchClientID)
        self._googleAPIKey = config.get("Google", "api_key", fallback=Defaults.googleAPIKey)

        self.check()
Esempio n. 25
0
 async def audio_change_task(self):
     while True:
         log.debug("Change task ran")
         if self.current is not None:
             try:
                 os.remove(self.current.file_url)
             except:
                 log.warning("Failed to remove {}".format(self.current.file_url))
         self.play_next_song.clear()
         self.current = await self.songs.get()
         self.queue.remove(self.current)
         await self.bot.send_message(self.current.channel, "Now playing {}".format(self.current))
         self.current.player.volume = self.volume
         self.current.player.start()
         log.debug("\"{}\" is now playing in \"{}\" on \"{}\"".format(self.current.data["title"], self.voice.channel.name, self.current.channel.server.name))
         await self.play_next_song.wait()
Esempio n. 26
0
 def produce_data(_num: int, _batch: int = 50):
     """
     模拟数据产生,向管道写入50条数据
     :return:
     """
     log.info('produce_data %f', time.time())
     for _ in range(_batch):
         try:
             _num += 1
             val: str = str(_num)  # str(int(sin(num/30.0) * 50 + 50))
             _data = data.replace('99', val)
             SERIAL_QUEUE.put_nowait(_data.format(time.time()))
             time.sleep(0.015)
             log.info('val = %s', val)
         except Full:
             log.warning('Write Failed to SERIAL_QUEUE [Full]')
Esempio n. 27
0
def send_report():
    """发送报告"""
    with open(cm.REPORT_FILE, encoding='utf-8') as f:
        content_html = f.read()
    try:
        mail = {
            'from': cm.EMAIL_INFO['username'],
            'subject': '新测试报告',
            'content_html': content_html,
            'attachments': [cm.REPORT_FILE]
        }
        server = zmail.server(*cm.EMAIL_INFO.values())
        server.send_mail(cm.ADDRESSEE, mail)
        log.info('测试邮件发送成功!')
    except Exception as e:
        log.warning(f'邮件发送失败{e}')
Esempio n. 28
0
    def run_checks():
        if not os.path.isdir("data"):
            log.warning(
                "No folder named \"data\" was found, creating one... (This message is harmless)"
            )
            os.makedirs("data")

        if not os.path.isfile("data/languages.json"):
            log.warning(
                "The file \"languages.json\" in the \"data\" folder was not found, creating one... (This message is harmless)"
            )
            with open("data/languages.json", "w+") as file:
                file.write("{}")

        if not os.path.isdir("assets"):
            log.critical("You need an assets folder")
            os._exit(1)
Esempio n. 29
0
    def check(self):
        if not self._token:
            log.critical("No token was specified in the config, please put your bot's token in the config.")
            os._exit(1)

        if not self.owner_id:
            log.critical("No owner ID was specified in the config, please put your ID for the owner ID in the config")
            os._exit(1)

        if len(self.dev_ids) is not 0:
            try:
                ids = self.dev_ids.split()
                self.dev_ids = []
                for id in ids:
                    self.dev_ids.append(int(id))
            except:
                log.warning("Developer IDs are invalid, all developer IDs have been ignored!")
                self.dev_ids = Defaults.dev_ids

        if len(self.support_ids) is not 0:
            try:
                ids = self.support_ids.split()
                self.support_ids = []
                for id in ids:
                    self.support_ids.append(int(id))
            except:
                log.warning("Support IDs are invalid, all support member IDs have been ignored!")
                self.support_ids = Defaults.support_ids

        if self.enableMal:
            if not self._malUsername and not self._malPassword:
                log.critical("The MyAnimeList module was enabled, but no MAL credinals were specified!")

            if not self._malUsername:
                log.critical("The MyAnimeList module was enabled, but no MAL username was specified!")
                os._exit(1)

            if not self._malPassword:
                log.critical("The MyAnimeList module was enabled, but no MAL password was specified!")
                os._exit(1)

        if self.enableOsu and not self._osuKey:
            log.critical("The osu! module was enabled but no osu! api key was specified!")
            os._exit(1)
Esempio n. 30
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_cache()
            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.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!")
    if config._carbonitex_key:
        log.info("Updating Carbonitex Statistics...")
        payload = {"key":config._carbonitex_key, "servercount":len(bot.servers), "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!")
Esempio n. 31
0
 def run_items(self):
     log.info(
         f"We have {len(self.product_ids)} product IDs for {self.gpu_long_name}"
     )
     log.info(f"Product IDs: {self.product_ids}")
     try:
         with ThreadPoolExecutor(max_workers=len(self.product_ids)) as executor:
             product_futures = [
                 executor.submit(self.buy, product_id)
                 for product_id in self.product_ids
             ]
             concurrent.futures.wait(product_futures)
             for fut in product_futures:
                 log.debug(f"Future Result: {fut.result()}")
     except ProductIDChangedException as ex:
         log.warning("Product IDs changed.")
         self.product_ids = set([])
         self.get_product_ids()
         self.run_items()
Esempio n. 32
0
async def on_ready():
    log.info("\n")
    log.info("Logged in as:\n{}/{}#{}\n----------".format(
        bot.user.id, bot.user.name, bot.user.discriminator))
    log.info(
        "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))
            traceback.print_exc()
    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://discord.bots.gg/api/v1/bots/:{}/stats".format(bot.user.id),
        #    	              json={"server_count": len(bot.guilds)},
        #        	          headers={"Authorization": config._dbots_token}, timeout=3)
        #    if r.status_code == 200:
        #        log.info("Discord Bots Server count updated.")
        #    elif r.status_code == 401:
        #        log.error("Woah, unauthorized?")
        #except requests.exceptions.Timeout:
        #    log.error("The server failed to respond in time. Unable to update the bot statistics.")
        pass
    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!")
    #await bot.cogs["Music"].disconnect_all_voice_clients()
    #log.info("Disconnected all voice clients!")
    load_opus_lib()
Esempio n. 33
0
 def assembly_serial_data(self):
     """
     按行组装串口数据并发送至管道
     :return:
     """
     self.__connect()
     if self.serial_pipe_sender is None:
         while True:
             serial_data = self.__read_serial_data()
             if serial_data == '' or not serial_data.startswith('CSI_DATA'):
                 continue
             assert serial_data.endswith('\n')
             try:
                 SERIAL_QUEUE.put_nowait(serial_data)
             except Full:
                 log.warning('Write Failed to SERIAL_QUEUE [Full]')
     else:
         while True:
             serial_data = self.__read_serial_data()
             # assert serial_data.endswith('\n')
             self.serial_pipe_sender.send(serial_data)
Esempio n. 34
0
 def send_serial_data(self):
     """
     从队列中读取组装好的串口数据并通过TCP socket 发送给服务端
     :return:
     """
     _s = self.__try_connect()
     i = 0
     while True:
         i += 1
         serial_data = SERIAL_QUEUE.get()
         assert isinstance(serial_data, str), 'wrong type of data read from SERIAL_QUEUE'
         _data: bytes = serial_data.encode('utf-8')
         assert _data.endswith(b'\n')
         if i % 2 == 0:
             continue
         try:
             _s.sendall(_data)
         except BrokenPipeError:
             log.warning('BrokenPipeError when sending to server SERIAL_QUEUE.qsize() = %d',
                         SERIAL_QUEUE.qsize())
             _s = self.__try_connect()
Esempio n. 35
0
async def restart(ctx):
    """Restarts the bot"""
    await ctx.send("Restarting...")
    log.warning("{} has restarted the bot!".format(ctx.author))
    await _restart_bot()
Esempio n. 36
0
async def restart(ctx):
    """Restarts the bot"""
    await ctx.send("Restarting...")
    log.warning("{} has restarted the bot!".format(ctx.author))
    await _restart_bot()
Esempio n. 37
0
async def shutdown(ctx):
    """Shuts down the bot"""
    await ctx.send("Shutting down...")
    log.warning("{} has shut down the bot!".format(ctx.author))
    await _shutdown_bot()
Esempio n. 38
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!")
Esempio n. 39
0
async def shutdown(ctx):
    """Shuts down the bot"""
    await bot.say("Shutting down...")
    log.warning("{} has shut down the bot!".format(ctx.message.author))
    await _shutdown_bot()
Esempio n. 40
0
async def restart(ctx):
    """Restarts the bot"""
    await bot.say("Restarting...")
    log.warning("{} has restarted the bot!".format(ctx.message.author))
    await _restart_bot()