예제 #1
0
    def Webhook(
        self: Any, comment: praw.reddit.Comment, flair: str, configuration: dict
    ) -> None:
        """Send the specified comment to Discord via Webhook."""

        embed: dict = {
            "username": configuration["name"],
            "avatar_url": configuration["avatarUrl"],
            "embeds": [
                {
                    "color": int("FF5700", base=16),
                    "author": {
                        "name": f"/u/{comment.author.name} ({flair})",
                        "url": f"https://reddit.com/user/{comment.author.name}",
                        "icon_url": comment.author.icon_img,
                    },
                    "title": f"Comment in /r/{comment.subreddit.display_name}",
                    "url": f"https://reddit.com{comment.permalink}?context=1000",
                    "description": Utility.Truncate(
                        self, Utility.Quote(self, comment.body), 2045
                    ),
                    "footer": {
                        "icon_url": "https://i.imgur.com/zbrkjFR.png",
                        "text": "Snoopy",
                    },
                    "timestamp": Utility.NowISO(self),
                }
            ],
        }

        res: httpx.Response = httpx.post(configuration["url"], json=embed)

        # HTTP 204 (Success: No Content)
        if (code := res.status_code) != 204:
            log.error(f"Failed to POST to Discord Webhook (HTTP {code}), {res.text}")
예제 #2
0
    def main(self):
        print("Athena - Fortnite Item Shop Generator")
        print("https://github.com/Liimiitz/Athena-FNAPI.io\n")

        initialized = Athena.LoadConfiguration(self)

        if initialized is True:
            if self.delay > 0:
                log.info(f"Delaying process start for {self.delay}s...")
                sleep(self.delay)

            itemShop = Utility.GET(
                self,
                "https://fortniteapi.io/v1/shop",
                {"Authorization": self.apiKey},
                {"lang": self.language},
            )

            if itemShop is not None:
                itemShop = json.loads(itemShop)

                # Strip time from the timestamp, we only need the date
                date = Utility.ISOtoHuman(self, today, self.language)
                log.info(f"Retrieved Item Shop for {date}")

                shopImage = Athena.GenerateImage(self, date, itemShop)

                if shopImage is True:
                    if self.twitterEnabled is True:
                        Athena.Tweet(self, date)
예제 #3
0
파일: itemshop.py 프로젝트: MinshuG/Athena
    def main(self):
        Log.Intro(self, "Athena - Fortnite Item Shop Generator")

        initialized = Athena.LoadConfiguration(self)

        if initialized is True:
            if self.delay > 0:
                Log.Info(self, f"Delaying process start for {self.delay}s...")
                sleep(self.delay)

            itemShop = Utility.GET(self,
                                   "https://fortnite-api.com/shop/br",
                                   parameters={'language': self.language})

            if itemShop is not None:
                itemShop = json.loads(itemShop)['data']

                # Strip time from the timestamp, we only need the date
                date = Utility.ISOtoHuman(self, itemShop["date"].split("T")[0])
                Log.Success(
                    self, f"Retrieved Item Shop for {date} in {self.language}")

                shopImage = Athena.GenerateImage(self, date, itemShop)

                if shopImage is True:
                    if self.twitterEnabled is True:
                        Athena.Tweet(self, date)
예제 #4
0
    def main(self):
        print("Athena - Fortnite Item Shop Generator")
        print("https://github.com/EthanC/Athena\n")

        initialized = Athena.LoadConfiguration(self)

        if initialized is True:
            if self.delay > 0:
                log.info(f"Delaying process start for {self.delay}s...")
                sleep(self.delay)

            itemShop = Utility.GET(
                self,
                "https://fortnite-api.com/v2/shop/br",
                {"x-api-key": self.apiKey},
                {"language": self.language},
            )

            if itemShop is not None:
                itemShop = json.loads(itemShop)["data"]

                # Strip time from the timestamp, we only need the date
                date = Utility.ISOtoHuman(self, itemShop["date"].split("T")[0],
                                          self.language)
                log.info(f"Retrieved Item Shop for {date}")

                shopImage = Athena.GenerateImage(self, date, itemShop)

                if shopImage is True:
                    if self.twitterEnabled is True:
                        Athena.Tweet(self, date)
예제 #5
0
 def two_d_anagram(self, rng):
     """
     :param rng: Take one input parameter as range
     Print the prime anagram between 2 to range
     """
     prime_number = Utility.get_prime_number(rng)
     b_value = True
     cnt = 0
     for i in range(len(prime_number)):
         for j in range(len(prime_number)):
             if i == j:
                 continue
             b_value = True
             if Utility.is_anagram(str(prime_number[i]),
                                   str(prime_number[j])):
                 self.arr[0][cnt] = prime_number[i]
                 # cnt += 1
                 # self.arr[0][cnt] = prime_number[j]
                 cnt += 1
                 b_value = False
                 break
         if b_value:
             self.arr[1][i] = prime_number[i]
     for x in range(2):
         for y in range(395):
             if self.arr[x][y] == 0:
                 continue
             print(int(self.arr[x][y]), end=" ")
         print()
예제 #6
0
class CannonEngine:
    def __init__(self):
        self.cannons = {}
        self.tactics = {}
        self.ips = []
        self.scaninfo = {}
        self.util = Utility()
        self.shells = {}

    def registerCannonPlug(self, plug: CannonPlug):
        tactics = plug.getSupportedAttackTactics()
        for tactic in tactics:
            if not (tactic in self.tactics):
                self.tactics[tactic] = []
            for mod in plug.getModulesForTactics(tactic):
                self.tactics[tactic].append([type(plug).__name__, mod])
        self.cannons[type(plug).__name__] = globals()[type(plug).__name__]

    def getAllRegisteredTechniques(self):
        return list(self.tactics.keys())

    def registerIP(self, ipaddr: str):
        u = Utility()
        if not u.isValidIP(ipaddr):
            raise ValueError("Invalid IP Address")
        if not (ipaddr in self.ips):
            self.ips.append(ipaddr)

    def gatherInformation(self, ipaddr: str):
        if not (ipaddr in self.ips):
            raise ValueError("IP Address must already be registered.")
        self.scaninfo[ipaddr] = SystemScan(ipaddr)
        self.scaninfo[ipaddr].startScan()

    def getSession(self, ipaddr: str):
        # TA0001 : Initial Access
        if not ("TA0001" in self.getAllRegisteredTechniques()):
            self.util.print_message(
                FAIL,
                "No Initial Access Modules are registered. Cannot Continue.")
            return False
        if not (self.scaninfo[ipaddr]):
            self.util.print_message(
                FAIL,
                "No Scan info for host: " + ipaddr + "! Cannot Continue.")
            return False

        tactics = self.tactics['TA0001']
        for t in tactics:
            cannon = self.cannons[t[0]]()
            targets = self.scaninfo[ipaddr].cpes
            print(targets)
            for target in targets:
                print(target)
                shell = cannon.fireModule(t[1], target['host'],
                                          int(target['port']))
                if (shell is not None):
                    self.shells[ipaddr] = shell
                    return True
        return False
    def main(self):
        print("Generador de Tienda de Objetos")
        print("Creado por: https://github.com/EthanC/Athena\n")
        print(
            "Modificado y Traducido por: https://github.com/PokeSantiTW/Spanish-Twitter-Item-Shop-Bot\n"
        )

        initialized = Athena.LoadConfiguration(self)

        if initialized is True:
            if self.delay > 0:
                log.info(f"Retrasando ejecución por {self.delay}s...")
                sleep(self.delay)

            itemShop = Utility.GET(
                self,
                "https://fortnite-api.com/v2/shop/br/combined",
                {"x-api-key": self.apiKey},
                {"language": self.language},
            )

            if itemShop is not None:
                itemShop = json.loads(itemShop)["data"]

                # Strip time from the timestamp, we only need the date
                date = Utility.ISOtoHuman(self, itemShop["date"].split("T")[0],
                                          self.language)
                log.info(f"Encontrado Tienda de Objetos del {date}")

                shopImage = Athena.GenerateImage(self, date, itemShop)

                if shopImage is True:
                    if self.twitterEnabled is True:
                        Athena.Tweet(self, date)
예제 #8
0
 def __init__(self):
     self.cannons = {}
     self.tactics = {}
     self.ips = []
     self.scaninfo = {}
     self.util = Utility()
     self.shells = {}
예제 #9
0
    def encrypt(self, s_box, random_numbers, im, result_queue, image_id):
        for i in range(len(im)):
            for j in range(len(im[0])):
                b, g, r = im[i][j]

                hex_r = Util.convert_dec_to_hex(r)
                hex_g = Util.convert_dec_to_hex(g)
                hex_b = Util.convert_dec_to_hex(b)

                row_r = int(hex_r[0], 16)
                column_r = int(hex_r[1], 16)

                row_g = int(hex_g[0], 16)
                column_g = int(hex_g[1], 16)

                row_b = int(hex_b[0], 16)
                column_b = int(hex_b[1], 16)

                new_r = int(
                    s_box[random_numbers[i][j][0], random_numbers[i][j][1]],
                    16) ^ int(s_box[row_r, column_r], 16)
                new_g = int(
                    s_box[random_numbers[i][j][2], random_numbers[i][j][3]],
                    16) ^ int(s_box[row_g, column_g], 16)
                new_b = int(
                    s_box[random_numbers[i][j][4], random_numbers[i][j][5]],
                    16) ^ int(s_box[row_b, column_b], 16)

                im[i, j] = new_b, new_g, new_r

        result_queue.put((im, image_id))
예제 #10
0
def test_util(fname):
    lines = Utility.file_len(fname)
    assert lines == 64
    lines, split_list = Utility.split_files(fname, lines, 4)
    assert len(split_list) == 4
    assert lines == 16
    return lines, split_list
 def getTangentStiffness(self, elemdat):
     n = self.dofCount()
     sData = getElemShapeData(elemdat.coords)
     elemdat.outlabel.append("stresses")
     elemdat.outdata = zeros(shape=(len(elemdat.nodes), 3))
     for iData in sData:
         kin = self.getKinematics(iData.dhdx, elemdat.state)
         firstPiola, K4tang = self.mat.getStress(kin)
         K4 = ut.transform_4thTensor_to_2ndTensor_inlargestrain(K4tang)
         firstPiola_vector = ut.transform_matrix_to_vector(firstPiola)
         Bnl = self.getBNLmatrix(iData.dhdx)
         elemdat.stiff += dot(Bnl.transpose(), dot(K4, Bnl)) * iData.weight
         elemdat.fint += dot(Bnl.transpose(),
                             firstPiola_vector) * iData.weight
         secondPiola = dot(np.linalg.inv(kin.F), firstPiola)
         secondPiola_vector = np.array(
             [secondPiola[0, 0], secondPiola[1, 1], secondPiola[0, 1]])
         elemdat.outdata += outer(ones(len(elemdat.nodes)),
                                  secondPiola_vector)
         # elemdat.stiff += dot(B.transpose(), dot(tang, B)) * iData.weight  # nonlinear material: dF : (F . DS) -> (dF.F) : C DE -> (dF.F) : C : (DF.F)
         # T = self.stress2matrix(sigma)
         # Bnl = self.getBNLmatrix(iData.dhdx)
         # elemdat.stiff += dot(Bnl.transpose(), dot(T, Bnl)) * iData.weight  # nonlinear geometry: dF : (DF . S)
         # elemdat.fint += dot(B.transpose(), sigma) * iData.weight  # power conjugate: chuyen tu F:P sang E:S -> 1/2(FT.F + F.FT):S -> FT.F : S (vi S symmetry)
         # elemdat.outdata += outer(ones(len(elemdat.nodes)), sigma)
     elemdat.outdata *= 1.0 / len(sData)
예제 #12
0
    def start(self) -> None:
        """Start generating and tweet the itemshop"""
        if self.delay > 0:
            log.info(f"Delaying process start for {self.delay}s...")
            sleep(self.delay)

        item_shop = Utility().get_url(
            "https://fortnite-api.com/v2/shop/br/combined",
            {"language": self.language},
        )

        if item_shop is not None:
            item_shop = item_shop["data"]

            # Strip time from the timestamp, we only need the date + translate
            # in every language from googletrans
            date = Translator().translate(Utility().iso_to_human(
                item_shop["date"].split("T")[0]),
                                          str='en',
                                          dest=self.date_language).text

            log.info(f"Retrieved Item Shop for {date}")

            shop_image = self.generate_image(date, item_shop)

            if shop_image is True:
                if self.twitter_enabled is True:
                    self.tweet(date)
예제 #13
0
    def Diff(self: Any, mode: str, newData: List[dict]):
        """
        Determine changes between local and remote news feeds, generate
        a Tweet for any new items.
        """

        if os.path.isfile(f"{mode}.json") is False:
            Utility.WriteFile(self, mode, "json", newData)

            log.info(f"Created {mode}.json")

            return

        oldData: Optional[dict] = Utility.ReadFile(self, mode, "json")
        oldMotds: List[Optional[str]] = []
        changed: bool = False

        motd: dict
        for motd in oldData:
            if motd.get("id") is not None:
                oldMotds.append(motd.get("id"))

        for motd in newData:
            if motd.get("id") in oldMotds:
                continue
            elif motd.get("id") is None:
                continue
            elif (_title := motd.get("title")) in self.ignoredTitles:
                log.info(
                    f'Ignoring news feed item "{_title}" due to ignored title configuration'
                )

                continue
            else:
                for _body in self.ignoredBodies:
                    if _body.lower() in motd["body"].lower():
                        log.info(
                            f'Ignoring news feed item "{_title}" due to ignored body configuration'
                        )

                        continue

                body = f"{motd['title']}\n{motd['body']}"

                for hashtag in self.hashtags:
                    # This allows for multi-word strings to be hashtagged
                    hashtagged = hashtag.replace(" ", "")
                    body = body.replace(hashtag, f"#{hashtagged}", 1)

                # Trim Tweet body to <280 characters (275 plus ellipses), as per
                # Twitter's requirements.
                body = body[:275] + (body[275:] and "...")

                log.info(body.replace("\n", " | "))

                if self.twitterEnabled is True:
                    Sleuth.Tweet(self, body, motd["image"])

                changed = True
예제 #14
0
    def login(self):
        inp = Utility.getInput("Machine or agent").lower()

        if (inp not in ["machine", "agent"]):
            Utility.error("Not a valid login type.")
        else:
            self.loginType = inp
            self.transactions.clear()
            print("Logged in as " + str(self.loginType))
예제 #15
0
    def deposit(self, number, amount):
        number = int(number)
        amount = int(amount)

        acct = self.getAccountByNumber(number)
        if acct is None:
            Utility.log('Aborting deposit, account does not exist: ' +
                        str(number))
            return
        acct.balance += amount
예제 #16
0
    def test1(self):
        utility = Utility()
        testNeighbors = [(1, 0), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0),
                         (2, 1), (2, 2), (3, 0), (4, 0), (5, 0), (6, 0),
                         (7, 0), (8, 0)]
        output = utility.getNeighboringCoordinates((0, 0))
        for neighbor in testNeighbors:
            self.assertIn(neighbor, output)

        self.assertEquals(len(output), len(testNeighbors))
예제 #17
0
    def WDR(self, account1, account2, amount, name):
        Utility.checkAccountNumber(account1)
        Utility.checkAmount(amount)

        if account2 != self.Unused['account']:
            self.fatalAccountNumber('WDR', account2)
        elif name != self.Unused['name']:
            self.fatalAccountName('WDR', name)
        else:
            self.accounts.withdraw(account1, amount)
예제 #18
0
    def DEL(self, account1, account2, amount, name):
        Utility.checkAccountNumber(account1)
        Utility.checkAccountName(name)

        if account2 != self.Unused['account']:
            self.fatalAccountNumber('DEL', account2)
        elif amount != self.Unused['amount']:
            self.fatalAmount('DEL', amount)
        else:
            self.accounts.deleteAccount(account1, name)
예제 #19
0
    def DEP(self, account1, account2, amount, name):
        Utility.checkAccountNumber(account1)
        Utility.checkAmount(amount)

        if account2 != self.Unused['account']:
            self.fatalAccountNumber('DEP', account2)
        elif name != self.Unused['name']:
            self.fatalAccountName('DEP', name)
        else:
            self.accounts.deposit(account1, amount)
예제 #20
0
    def transfer(self):
        fromAccount = Utility.getAccountNumber("From account #")
        if fromAccount is None:
            return
        if not fromAccount in self.accounts:
            Utility.error("Account does not exist")
            return

        toAccount = Utility.getAccountNumber("To account #")
        if toAccount is None:
            return
        if not toAccount in self.accounts:
            Utility.error("Account does not exist")
            return

        if (fromAccount == toAccount):
            Utility.error("Cannot transfer from and to the same account.")
            return

        amount = Utility.getAmount(self.loginType,
                                   "Amount to transfer in cents")
        if amount is None:
            return

        self.transactions.transfer(fromAccount, toAccount, amount)
예제 #21
0
 def data_process(self):
     """
     This method is to process the data. It will calculate the line count in file
     and split file based on line count. Now files are split to the number based on
     number of cores in machine.
     returns :Nothing
     """
     logging.info('Processing the data and split files')
     lines = Utility.file_len(self.fname)
     self.lines_to_be, self.split_files = Utility.split_files(self.fname, lines,
                                                              cpu_count().real)
 def prime_with_stack(self, rng):
     """
     :param rng : Take one input from user as range
     Print prime number between 2 to range
     """
     prime_number = Utility.get_prime_number(rng)
     anagram = Utility.get_anagram(prime_number)
     for i in anagram:
         self.stack.push(i)
     for i in range(self.stack.size()):
         print(self.stack.pop(), end=" ")
 def prime_anagram_with_queue(self, rng):
     """
     :param rng: take one parameter range for calculating prime anagram from 1 to range
     print prime anagram number on console
     """
     prime_number = Utility.get_prime_number(rng)
     anagram_number = Utility.get_anagram(prime_number)
     for i in anagram_number:
         self.queue.enqueue(i)
     for i in range(self.queue.size()):
         print(self.queue.dequeue(), end=" ")
예제 #24
0
    def test1(self):
        ptext = utl.toBitSet(0x2345, 16)
        sub1 = self.getSBoxGroup(ptext)
        print('substitution:', utl.toInteger(sub1, 16), '-', int(sub1))

        print('permutation: ', int(self.permuteBits(ptext)))

        sub1 = self.getSBoxGroup(utl.toBitSet(0x1234, 16))
        sub2 = self.getSBoxGroup(utl.toBitSet(0x5678, 16))
        subinv3 = self.getSBoxInvGroup(utl.toBitSet(0x9abc, 16))
        print('permutation: ', int(sub1), " - ", int(sub2))
        print('subinv: ', int(subinv3))
예제 #25
0
 def withdraw(self, number, amount):
     acct = self.getAccountByNumber(number)
     if acct is None:
         Utility.log('Aborting withdrawal, account does not exist: ' +
                     number)
         return
     if acct.balance < amount:
         Utility.log(
             'Aborting withdrawal, the account does not have enough funds: '
             + number)
     else:
         acct.balance -= amount
예제 #26
0
    def getDiffPair16(self, seed16, dp):
        X = utl.toBitSet(0xF000, 16)
        Y = utl.toBitSet(seed16, 16)
        Z = utl.toBitSet(0, 16)
        for i in range(4):
            sb = int(X & Y) >> (4 - 1 - i) * 4
            sb = int(dp[sb])
            sb = sb << (4 - 1 - i) * 4
            Xpm = utl.toBitSet(sb, 16)
            Z = Xpm | Z
            X = X >> 4

        return Z
예제 #27
0
    def deposit(self):
        account = Utility.getAccountNumber("Account #")
        if account is None:
            return
        if account not in self.accounts:
            Utility.error("Account does not exist")
            return

        amount = Utility.getAmount(self.loginType, "Amount in cents")
        if amount is None:
            return

        self.transactions.deposit(account, amount)
예제 #28
0
    def transfer(self, fromNumber, toNumber, amount):
        fromNumber = int(fromNumber)
        toNumber = int(toNumber)
        amount = int(amount)

        fromAcct = self.getAccountByNumber(fromNumber)
        toAcct = self.getAccountByNumber(toNumber)

        if fromAcct is None:
            Utility.log('Aborting transfer, account does not exist: ' +
                        str(fromNumber))
        elif toAcct is None:
            Utility.log('Aborting transfer, account does not exist: ' +
                        str(toNumber))
        elif fromNumber == toNumber:
            Utility.log(
                'Aborting transfer, cannot transfer between the same accounts: '
                + str(fromNumber) + '/' + str(toNumber))
        elif fromAcct.balance < amount:
            Utility.log(
                'Aborting transfer, not enough funds in the source account: ' +
                str(fromNumber))
        else:
            fromAcct.balance -= amount
            toAcct.balance += amount
        return
예제 #29
0
 def EOS(self, account1, account2, amount, name):
     if account1 != self.Unused['account'] or account2 != self.Unused[
             'account']:
         Utility.fatal('Invalid account number(s) in EOS command' +
                       account1 + ' / ' + account2)
     elif amount != self.Unused['amount']:
         self.fatalAmount('EOS', amount)
     elif name != self.Unused['name']:
         self.fatalAccountName('EOS', name)
     else:
         # If this is the second EOS in a row, exit
         if self.lastCommand is 'EOS':
             self.accounts.finish()
             sys.exit()
예제 #30
0
 def main(self):
     initialized = ShopBot.LoadConfig(ShopBot)
     if initialized:
         log.info("Fortnite-ShopBot")
         log.info("製作者: gomashio")
         log.info("参考: Athena")
         log.info("Getting ItemShop data...")
         data = json.loads(
             ShopBot.GET_ItemShop(self,
                                  api_key=self.api_key,
                                  language=self.language))
         date = Utility.ISOtoHuman(self,
                                   date=Utility.Now_ISO(self),
                                   dateformat=self.text_override['date'],
                                   hour=self.text_override['hour'],
                                   language=self.language)
         specialoffer = None
         if self.text_override['auto-specialoffer-convert']['enabled']:
             with requests.Session() as session:
                 specialoffer = AuthUtil.get_special_offer(
                     self,
                     session=session,
                     email=self.text_override['auto-specialoffer-convert']
                     ['email'],
                     password=self.
                     text_override['auto-specialoffer-convert']['password'],
                     user_agent=self.user_agent,
                     language=self.language)
         if specialoffer is None:
             specialoffer = self.text_override['auto-specialoffer-convert'][
                 'default']
         if data is not None and date is not None:
             log.info("Generating shop image...")
             Image = ShopBot.GenerateImage(self,
                                           data=data,
                                           date=date,
                                           text_override=self.text_override,
                                           specialoffer=specialoffer,
                                           namefont=self.namefont,
                                           categoryfont=self.categoryfont)
         else:
             log.error("Failed to get shop data")
         if Image:
             log.info("Success")
             if self.monitor_change_enabled:
                 ShopBot.MonitorChange(self)
             else:
                 exit()
    def LoadConfiguration(self):
        """
        Set the configuration values specified in configuration.json
        
        Return True if configuration sucessfully loaded.
        """

        configuration = json.loads(
            Utility.ReadFile(self, "configuration", "json"))

        try:
            self.delay = configuration["delayStart"]
            self.apiKey = configuration["fortniteAPI"]["apiKey"]
            self.language = configuration["language"]
            self.supportACreator = configuration["supportACreator"]
            self.twitterEnabled = configuration["twitter"]["enabled"]
            self.twitterAPIKey = configuration["twitter"]["apiKey"]
            self.twitterAPISecret = configuration["twitter"]["apiSecret"]
            self.twitterAccessToken = configuration["twitter"]["accessToken"]
            self.twitterAccessSecret = configuration["twitter"]["accessSecret"]

            log.info("Loaded configuration")

            return True
        except Exception as e:
            log.critical(f"Failed to load configuration, {e}")
예제 #32
0
    def LoadConfiguration(self: Any) -> Optional[bool]:
        """
        Set the configuration values specified in configuration.json
        
        Return True if configuration sucessfully loaded.
        """

        configuration: Optional[Union[dict, str]] = Utility.ReadFile(
            self, "configuration", "json")

        try:
            # self.saveTheWorld: bool = configuration["saveTheWorld"]
            self.battleRoyale: bool = configuration["battleRoyale"]
            self.creative: bool = configuration["creative"]
            self.language: str = configuration["language"]
            self.apiKey: str = configuration["fortniteAPI"]["apiKey"]
            self.twitterEnabled: bool = configuration["twitter"]["enabled"]
            self.twitterAPIKey: str = configuration["twitter"]["apiKey"]
            self.twitterAPISecret: str = configuration["twitter"]["apiSecret"]
            self.twitterAccessToken: str = configuration["twitter"][
                "accessToken"]
            self.twitterAccessSecret: str = configuration["twitter"][
                "accessSecret"]
            self.hashtags: List[str] = configuration["hashtags"]
            self.ignoredTitles: List[str] = configuration["ignoredTitles"]
            self.ignoredBodies: List[str] = configuration["ignoredBodies"]

            log.info("Loaded configuration")

            return True
        except Exception as e:
            log.critical(f"Failed to load configuration, {e}")
예제 #33
0
        opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
        input_file = None
        output_file = None
        for opt, arg in opts:
            if opt == '-h':
                print 'worker.py -i <inputfile> -o <outputfile>'
                sys.exit()
            elif opt in ("-i", "--ifile"):
                input_file = arg
            elif opt in ("-o", "--ofile"):
                output_file = arg
    except getopt.GetoptError, e:
        logging.info('worker.py -i <inputfile> -o <outputfile>')
        raise e
    if not input_file or not output_file:
        logging.info('worker.py -i <inputfile> -o <outputfile>')
        raise NoArgumentException("One of  Argument is not passed")

    if Utility.is_file_exists(input_file):
        try:
            ws = Worker(input_file, output_file)
            ws.data_process()
            ws.run()
        except Exception, e:
            raise e
    else:
        raise FileNotFound(" The specified file does not present")

if __name__ == "__main__":
    main(sys.argv[1:])