Пример #1
0
def callback(result):
    if isinstance(result, list):
        print("\n".join(result))
    elif result is not None:
        print(result)
    else:
        root_command.execute(*["help"], callback=callback)
Пример #2
0
    def on_pubmsg(self, c, e):
        sender = e.source.nick
        my_nickname = irc.strings.lower(self.connection.get_nickname())
        message = e.arguments[0]
        nick_msg_split = message.split(":")
        respond = irc.strings.lower(nick_msg_split[0]) in [
            my_nickname, "{} (irc)".format(my_nickname)
        ] and len(nick_msg_split) == 2

        if respond:
            commands = [
                irc.strings.lower(x) for x in nick_msg_split[1].split(" ")
                if len(x) > 0
            ]
            try:
                root_command.execute(*commands,
                                     command_args={
                                         "service_factory":
                                         self.quote_service_factory,
                                         "instance": self,
                                         "sender": sender
                                     },
                                     callback=self.command_callback,
                                     callback_args={"sender": sender})
            except Exception as e:
                LOGGER.exception("something failed", e)
                self.command_callback("something failed", sender=sender)
Пример #3
0
 def on_privmsg(self, c, e):
     sender = e.source.nick
     message = e.arguments[0]
     commands = [irc.strings.lower(x) for x in message.split(" ")]
     root_command.execute(*commands,
                          command_args={
                              "service_factory": self.quote_service_factory,
                              "instance": self,
                              "sender": sender
                          },
                          callback=self.command_callback_priv,
                          callback_args={"sender": sender})
Пример #4
0
    def test_lucky_quote_and_quick_get_command(self):
        class FakeQuote(object):
            def __init__(self, data={}):
                self.data = data

            def is_empty(self):
                return len(self.data.items()) == 0

            def __str__(self):
                return "Ticker: {}".format(self.data.get("ticker"))

        class FakeQuoteServiceLocal(object):
            def get_quote(self, ticker):
                if ticker == "fancyticker":
                    return FakeQuote()
                else:
                    return FakeQuote(data={"ticker": "AWESOMO"})

            def search(self, query):
                return GoogleFinanceSearchResult(
                    result={
                        "matches": [{
                            "t": "AWESOMO",
                            "e": "Foo Market",
                            "n": "Foo Company"
                        }]
                    })

        factory = QuoteServiceFactory()
        factory.providers = {"fakeprovider": FakeQuoteServiceLocal}
        command = ["q", "gl", "fakeprovider", "fancyticker"]
        res = root_command.execute(*command,
                                   command_args={
                                       "service_factory": factory,
                                       "instance": self.ircbot
                                   })
        self.assertEquals("Ticker: AWESOMO", str(res))

        factory.providers = {"avanza": FakeQuoteServiceLocal}
        command = ["qq", "fancyticker"]
        res = root_command.execute(*command,
                                   command_args={
                                       "service_factory": factory,
                                       "instance": self.ircbot
                                   })
        self.assertEquals("Ticker: AWESOMO", str(res))
Пример #5
0
 def __cmd_wrap(self, *args):
     """ test helper """
     factory = QuoteServiceFactory()
     factory.providers = {"fakeprovider": FakeQuoteService}
     return root_command.execute(*args,
                                 command_args={
                                     "service_factory": factory,
                                     "instance": self.ircbot
                                 })
Пример #6
0
    def test_execute_nonblocking_scrape_stocks(self, sleep_mock):

        # Mock sleep in the scrape task
        sleep_mock.return_value = False

        companies = [
            NasdaqCompany(name="AAK",
                          ticker="AAK",
                          currency="SEK",
                          category="bla",
                          segment="nordic large cap"),
            NasdaqCompany(name="ABB Ltd",
                          ticker="ABB",
                          currency="SEK",
                          category="bla",
                          segment="nordic large cap")
        ]
        self.session.add_all(companies)
        self.session.commit()

        command = ["scrape", "stocks", "sek", "nordic", "large", "cap"]
        root_command.execute(
            *command,
            command_args={'service': GoogleFinanceQueryService()},
            callback=self.ircbot.callback)

        self.assertEquals("Task started", self.ircbot.callback_args[0])

        for t in threading.enumerate():
            if t.name == "thread-sek_nordic_large_cap":
                t.join()

        self.assertEquals(
            "Done scraping segment 'nordic large cap' currency 'SEK' - scraped 2 companies",
            self.ircbot.callback_args[0])

        for c in companies:
            row = self.session.query(StockDomain).filter(
                StockDomain.ticker == c.ticker).first()
            self.assertNotEquals(None, row)
Пример #7
0
    def stock_check_scheduler(self):

        if not self.scheduler:
            LOGGER.debug("Scheduler is disabled")
            return

        if not self.connection.is_connected():
            LOGGER.debug("Not connected yet, hold off")
            return

        now = datetime.now()

        if self.last_check is not None:
            if int(now.timestamp()
                   ) - self.last_check < self.scheduler_interval:
                return

        # TODO: not so configurable, fix
        if not self.timer_should_execute(now):
            return

        for command in self.commands:
            try:
                root_command.execute(*command.split(" "),
                                     command_args={
                                         "service_factory":
                                         self.quote_service_factory,
                                         "instance": self
                                     },
                                     callback=self.command_callback,
                                     callback_args={})
            except Exception as e:
                LOGGER.exception(
                    "failed to execute scheduled command '{}'".format(command))

        self.last_check = int(now.timestamp())
Пример #8
0
    def test_quote_get_fresh_command(self):
        class FakeQuoteIsNotFresh(object):
            def is_fresh(self):
                return False

        class FakeQuoteIsFresh(object):
            def is_fresh(self):
                return True

            def __str__(self):
                return "I'm fresh"

        class FakeQuoteServiceLocal(object):
            def get_quote(self, ticker):
                if ticker == "not_fresh":
                    return FakeQuoteIsNotFresh()
                else:
                    return FakeQuoteIsFresh()

        factory = QuoteServiceFactory()
        factory.providers = {"fakeprovider": FakeQuoteServiceLocal}
        command = ["quote", "get_fresh", "fakeprovider", "not_fresh"]
        res = root_command.execute(*command,
                                   command_args={
                                       "service_factory": factory,
                                       "instance": self.ircbot
                                   })
        self.assertIsNone(res)

        command = ["quote", "get_fresh", "fakeprovider", "fresh"]
        res = root_command.execute(*command,
                                   command_args={
                                       "service_factory": factory,
                                       "instance": self.ircbot
                                   })
        self.assertEquals("I'm fresh", str(res))
Пример #9
0
 def cmd_wrap(*command):
     return root_command.execute(
         *command,
         command_args={'service_factory': QuoteServiceFactory()})
Пример #10
0
import sys
import logging

#logging.disable(logging.ERROR)

from stockbot.provider import QuoteServiceFactory
from stockbot.command import root_command


def callback(result):
    if isinstance(result, list):
        print("\n".join(result))
    elif result is not None:
        print(result)
    else:
        root_command.execute(*["help"], callback=callback)


root_command.execute(*sys.argv[1:], command_args={"service_factory": QuoteServiceFactory()}, callback=callback)