Exemple #1
0
def get_code():
    app = Client(
        phone_number.strip('+'),
        api_id,
        api_hash,
        phone_number=phone_number,
        phone_code=phone_code_callback,
        workdir='tmp',
    )

    app.start()

    if DEBUG:
        for dialog in app.get_dialogs().dialogs:
            if dialog.chat.first_name == 'Telegram':
                print(dialog.chat.id, dialog.chat.type, [
                    dialog.chat.title, dialog.chat.username,
                    dialog.chat.first_name
                ])
                print('\t', dialog.top_message.message_id,
                      dialog.top_message.date, dialog.top_message.text)

    ret = app.get_history(777000, limit=10)

    for message in ret.messages:
        m = re.search(
            r'(?:Код подтверждения|Login code|Your login code): (\d+)',
            message.text)
        if m:
            code = m.group(1)
            ret = {
                'message_id': message.message_id,
                'date': message.date,
                'first_name': message.from_user.first_name,
                'text': message.text,
                'code': code,
            }
            print(str(ret))
            app.stop()

    print('---END---')
    os._exit(0)
Exemple #2
0
            _invitedByID = 0
            _invitedByFullName = ""
            _invitedByUsername = ""
        print("|-> Status: {}\n|-> Join date: {}".format(_status, _date))
        print("|-> Invited by id: {} | username: {} | Full name: {}".format(
            _invitedByID, _invitedByUsername, _invitedByFullName))


with app:
    while True:
        choice = input(Fore.CYAN +
                       "[1] => chats lookup\n[2] => users lookup\n" +
                       "[3] => search user in groups\n" +
                       "[anything else] => exit\n" + "[<] " + Style.RESET_ALL)
        if choice == "1":
            dialogs = app.get_dialogs()
            i = 0
            for d in dialogs:
                chatListPrint(d['chat'])
                i += 1
                if i >= 10:
                    cmd = input(Fore.CYAN + "[(c)/x]: " + Style.RESET_ALL)
                    i = 0
                    if cmd == 'x':
                        break
            chatID = input(Fore.CYAN + "[chat lookup]: " + Style.RESET_ALL)
            choice = input(
                Fore.CYAN +
                "[1] => Bulk search\n[2] => single user lookup\n[<]: " +
                Style.RESET_ALL)
            if choice == "1":
class ForecastBot(TelegramApi):
    def __init__(self, token, api_id, api_hash, img_urls: List[str], followers_file: str) -> None:
        super().__init__(token)
        self.api_id = api_id
        self.api_hash = api_hash
        self.telegram_client = Client('session', api_hash=self.api_hash, api_id=self.api_id)
        self.telegram_client.start()
        self.telegram_client.get_dialogs()
        self._bot_father_chat_id = 93372553
        self._current_temp = 0.0
        self.state = {}
        self.img_urls = img_urls
        self.followers_file = followers_file
        self.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9;'
                                      ' rv:45.0) Gecko/20100101 Firefox/45.0',
                        'Connection': 'close'}

    def check_forecast(self) -> bool:
        for img in self.img_urls:
            old_hash = self.state[f'{self._get_fname(img)}_md5']
            if old_hash == self.find_hash(self._request(img).content):
                return False
        return True

    def is_available(self) -> bool:
        for img in self.img_urls:
            if not os.path.isfile(self._get_fname(img)):
                return False
        return True

    def update_pic_temp(self):
        new_temp = self.get_current_temp()
        attempts = 0
        while new_temp is None and attempts < 5:
            attempts += 1
            new_temp = self.get_current_temp()
        if new_temp is None:
            image_name = create_empty_temp_image()
        else:
            image_name = create_temp_image(new_temp)
        self.telegram_client.send_message(text='/setuserpic', chat_id=self._bot_father_chat_id)
        time.sleep(3)
        self.telegram_client.send_message(text='@PogodaTheBot', chat_id=self._bot_father_chat_id)
        time.sleep(3)
        self.telegram_client.send_photo(photo=image_name, chat_id=self._bot_father_chat_id)

    @staticmethod
    def get_current_temp() -> Optional[str]:
        try:
            html_doc: bytes = requests.get('http://www.belmeteo.net/').content
        except requests.ConnectionError:
            return None
        soup = BeautifulSoup(html_doc, 'html.parser')
        left_panel = soup.find_all('div', class_='leftSideBar')
        try:
            current_temp_text = left_panel[0].ul.li.b.text
        except IndexError:
            return None
        current_temp_find = re.findall(r'.\d+[.]\d..', current_temp_text)
        assert len(current_temp_find) == 1
        current_temp = current_temp_find[0]
        if '-' not in current_temp:
            return f'+{current_temp[1:]}'
        else:
            return current_temp

    def send(self) -> None:
        with open(self.followers_file, 'r') as members:
            for member in members:
                member_id = member.strip()
                self.send_message(chat_id=member_id,
                                  text='Прогноз обновлен⬇️')
                for url in self.img_urls:
                    self.send_photo(chat_id=member_id,
                                    photo=self.state[self._get_fname(url)].content)

    def save(self) -> None:
        for img in self.img_urls:
            fname = self._get_fname(img)
            r = requests.get(img, headers=self.headers)
            if r.status_code == 200:
                with open(fname, 'wb') as file:
                    file.write(r.content)
                self.state[fname] = r
                self.state[f'{fname}_md5'] = self.find_hash(r.content)

    @delay
    def _request(self, url: str) -> Response:
        return requests.get(url, headers=self.headers)

    @staticmethod
    def _get_fname(url: str) -> str:
        return url.split('/')[-1]

    @staticmethod
    def find_hash(content: bytes) -> str:
        md5 = hashlib.md5()
        md5.update(content)
        return md5.hexdigest()

    def add_new_followers(self) -> None:
        response = self.get_updates()
        result = response.json().get('result')
        if result:
            senders = {str(x['message']['chat']['id']) for x in result}
            with open(self.followers_file, 'r') as old_file:
                old_followers = {x.strip() for x in old_file}

            new_followers = senders.difference(old_followers)
            if new_followers:
                print(f'new followers: {new_followers}')
                with open(self.followers_file, 'w') as new_file:
                    for follower_id in {*old_followers, *new_followers}:
                        new_file.write(f'{follower_id}\n')
                for follower in new_followers:
                    self.send_message(chat_id=follower,
                                      text='Прогноз обновлен⬇️')
                    for url in self.img_urls:
                        self.send_photo(chat_id=follower,
                                        photo=self.state[self._get_fname(url)].content)
Exemple #4
0
            except KeyError:
                _invitedByFullName = _invitedByFirstName
        else:
            _invitedByID = 0
            _invitedByFullName = ""
            _invitedByUsername = ""
        print("|-> Status: {}\n|-> Join date: {}".format(_status, _date))
        print("|-> Invited by id: {} | username: {} | Full name: {}".format(_invitedByID, _invitedByUsername, _invitedByFullName))


while True:
    with app:
        choice = input(Fore.CYAN + "[1] => chats lookup\n[2] => users lookup\n" + 
                                   "[3] => search user in groups\n[<] " + Style.RESET_ALL)
        if choice == "1":
            dialogs = app.get_dialogs()
            i = 0
            for d in dialogs:
                chatListPrint(d['chat'])
                i += 1
                if i >= 10:
                    cmd = input(Fore.CYAN + "[(c)/x]: " + Style.RESET_ALL)
                    i = 0
                    if cmd == 'x':
                        break
            chatID = input(Fore.CYAN + "[chat lookup]: " + Style.RESET_ALL)
            choice = input(Fore.CYAN + "[1] => Bulk search\n[2] => single user lookup\n[<]: " + Style.RESET_ALL)
            if choice == "1":
                limit = input(Fore.CYAN + "[# of users]: " + Style.RESET_ALL)
                members = app.get_chat_members(chat_id=int(chatID), limit=int(limit))
                chatMembersInfoPrint(members)