Ejemplo n.º 1
0
    def __get_driver(self) -> webdriver.Remote:
        try:
            return self.session(hashtag=self.hashtags.current_tag)
        except NoLongerValid:
            log.info("session expired, entering the wait period",
                     extra={"wait-time": self.config.wait_time})
            self.session.disconnect()
            time.sleep(self.config.wait_time)

            self.session = Session(account=config.Instagram(),
                                   selenium=config.Selenium(),
                                   initial_hashtag=self.hashtags.random())
            return self.session(hashtag=self.hashtags.current_tag)
        except CorruptedSession as e:
            log.error(
                "current session was corrupted, entering wait period and creating new session",
                extra={
                    "wait-time": self.config.wait_time,
                    "error": e
                })
            self.session.disconnect()
            time.sleep(self.config.wait_time)

            self.session = Session(account=config.Instagram(),
                                   selenium=config.Selenium(),
                                   initial_hashtag=self.hashtags.random())
            return self.session(hashtag=self.hashtags.current_tag)
Ejemplo n.º 2
0
def get_updates(last_id=0):
    updates = send_request(
        TelegramOutMessage(body={'offset': last_id + 1}, method='getUpdates'))
    updates = updates['result']
    new_last_id = last_id
    for update in updates:
        print('\nresponding to:\n', update)

        if update['update_id'] > new_last_id:
            new_last_id = update['update_id']

        if last_id == 0:
            continue

        m = telegram.parse_message(message=update, bot_name='beachranks_bot')
        if m.ids.user_id in sessions:
            s = sessions[m.ids.user_id]
        else:
            s = Session(search=EmptySearch(),
                        manage=EmptyManage(),
                        text=Texts(locale='ru'))
            sessions[m.ids.user_id] = s

        res = s.process_request(update)
        for response in res:
            send_request(response)

    return new_last_id
Ejemplo n.º 3
0
def get_updates(last_id=0):
    updates = send_request(
        TelegramOutMessage(body={'offset': last_id + 1}, method='getUpdates'))
    updates = updates['result']
    new_last_id = last_id
    for update in updates:
        logging.getLogger('Bot').debug(f'responding to {update}')

        if update['update_id'] > new_last_id:
            new_last_id = update['update_id']

        if last_id == 0:
            continue

        m = telegram.parse_message(message=update, bot_name='beachranks_bot')
        if m.ids.user_id in sessions:
            s = sessions[m.ids.user_id]
        else:
            s = Session(backend=RestClient(Config.bot.host,
                                           Config.rest_service.port),
                        text=Texts(locale=Config.bot.locale))  # '185.4.74.144'
            sessions[m.ids.user_id] = s

        res = s.process_request(update)
        for response in res:
            send_request(response)

    return new_last_id
Ejemplo n.º 4
0
 def __init__(self) -> None:
     self.hashtags = config.Tags()
     self.config = config.Config()
     self.session = Session(account=config.Instagram(),
                            selenium=config.Selenium(),
                            initial_hashtag=self.hashtags.random())
     self.day_likes = random.randint(int(self.config.max_likes / 2),
                                     self.config.max_likes)
     self.current_date = dt.today().date()
Ejemplo n.º 5
0
    async def post_beachranks_bot(self, args: typing.Dict):
        logger.debug(f'post_beachranks_bot {args}')
        update = args['body']
        if update is None:
            return 'no body'

        update = json.loads(update.decode('utf-8'))
        print('\nresponding to:\n', update)

        m = self.telegram.parse_message(message=update,
                                        bot_name='beachranks_bot')
        if m.ids.user_id in self.sessions:
            s = self.sessions[m.ids.user_id]
        else:
            s = Session()
            s.start(backend=RestClient(self.restHost, self.restPort),
                    text=Texts(locale='ru'))  # '185.4.74.144'
            self.sessions[m.ids.user_id] = s

        res = s.process_request(update)
        for response in res:
            send_request(response)
Ejemplo n.º 6
0
class Bot:
    def __init__(self) -> None:
        self.hashtags = config.Tags()
        self.config = config.Config()
        self.session = Session(account=config.Instagram(),
                               selenium=config.Selenium(),
                               initial_hashtag=self.hashtags.random())
        self.day_likes = random.randint(int(self.config.max_likes / 2),
                                        self.config.max_likes)
        self.current_date = dt.today().date()

    def __call__(self) -> None:
        while True:
            if self.day_likes > 0:
                self.like()
                self.goto_next()
                self.day_likes -= 1
                log.info("like given",
                         extra={"likes-remaining": self.day_likes})

            if self.day_likes <= 0 and self.current_date != dt.today().date():
                self.current_date == dt.today().date()
                self.day_likes = random.randint(int(self.config.max_likes / 2),
                                                self.config.max_likes)
            elif self.day_likes <= 0 and self.current_date == dt.today().date(
            ):
                log.info("out of likes, waiting for date change",
                         extra={"wait-time": "60m"})
                time.sleep(config.parse_time("1h"))
            elif self.day_likes > 0 and self.current_date != dt.today().date():
                self.current_date == dt.today().date()
                self.day_likes = random.randint(int(self.config.max_likes / 2),
                                                self.config.max_likes)

    def __get_driver(self) -> webdriver.Remote:
        try:
            return self.session(hashtag=self.hashtags.current_tag)
        except NoLongerValid:
            log.info("session expired, entering the wait period",
                     extra={"wait-time": self.config.wait_time})
            self.session.disconnect()
            time.sleep(self.config.wait_time)

            self.session = Session(account=config.Instagram(),
                                   selenium=config.Selenium(),
                                   initial_hashtag=self.hashtags.random())
            return self.session(hashtag=self.hashtags.current_tag)
        except CorruptedSession as e:
            log.error(
                "current session was corrupted, entering wait period and creating new session",
                extra={
                    "wait-time": self.config.wait_time,
                    "error": e
                })
            self.session.disconnect()
            time.sleep(self.config.wait_time)

            self.session = Session(account=config.Instagram(),
                                   selenium=config.Selenium(),
                                   initial_hashtag=self.hashtags.random())
            return self.session(hashtag=self.hashtags.current_tag)

    # self explanatory
    def like(self):
        try:
            like_btnSVG = self.__get_driver().find_element(
                by=By.XPATH,
                value=
                '/html/body/div[6]/div[3]/div/article/div/div[2]/div/div/div[2]/section[1]/span[1]/button/div/span//*[local-name() = "svg"]'
            )
        except Exception:
            log.warning('no svg elements')
            return

        label = like_btnSVG.get_attribute('aria-label')

        if str(label).upper() == 'Unlike'.upper():
            time.sleep(random.randint(2, 10))
            return

        like_btn = self.__get_driver().find_element(
            by=By.XPATH,
            value=
            '/html/body/div[6]/div[3]/div/article/div/div[2]/div/div/div[2]/section[1]/span[1]/button'
        )
        like_btn.click()
        time.sleep(random.randint(2, 10))

    # as on first photo on the Top Posts part, there is only next button,
    # thus there is difference between xpath on first and following photos
    def goto_second(self) -> None:
        next_btn = self.__get_driver().find_element(
            by=By.XPATH, value='/html/body/div[4]/div[1]/div/div/a')
        next_btn.click()
        time.sleep(2)

    # self explanatory
    def goto_next(self) -> None:
        next_btn = self.__get_driver().find_element(
            by=By.XPATH, value='/html/body/div[6]/div[2]/div/div[2]/button')
        next_btn.click()
        time.sleep(2)
Ejemplo n.º 7
0
def session():
    with mock.patch("bot.session.Redis"):
        return Session()
Ejemplo n.º 8
0
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from brain.brain import Brain
from bot.session import Session
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
from databaseImport.databaseUpdate import DbUpdate as dbUpdate
from dumpMessage.dump import Dump

#class PickMessage(object):


def pickAndProcess(dbUpdateObject, sessionObject, brainObject, dumpObject):
    l = dbUpdateObject.selectResponseMessageLastEntry()
    if (l != None):
        l = dbUpdateObject.selectReceiveMessageById(str(l[0]))
    else:
        l = dbUpdateObject.selectReceiveMessageAll()
    for item in l:
        brainObject.brain1(dbUpdateObject, sessionObject, item, dumpObject)


if __name__ == "__main__":
    dbUpdateObject = dbUpdate()
    sessionObject = Session()
    brainObject = Brain()
    dumpObject = Dump()
    #pickObject=PickMessage();
    sessionObject.learn()
    while (1):
        pickAndProcess(dbUpdateObject, sessionObject, brainObject, dumpObject)
        time.sleep(1)