Пример #1
0
def connect_user(creds):
    # try connecting with session_id, otherwise authenticate
    try:
        session = StringSession(creds['session_id'])
        client = TelegramClient(session, creds['api_id'], creds['api_hash'])
        client.start()

        if client.is_connected():
            logger.info('Client is connected using session.')
            return (client, False)
        else:
            logger.error('Client failed to connect using existing session')
            raise Exception('Error occured - client is not connected')

    except KeyError:
        logger.info('Session is not found. Trying to authenticate user.')
        start_params = (creds['phone'], ) if creds.get('phone') else tuple()
        client = TelegramClient(StringSession(), creds['api_id'],
                                creds['api_hash'])
        client.start(*start_params)

        if client.is_connected():
            logger.info('Client is authenticated and connected.')
            return (client, True)
        else:
            logger.error('Client failed to connect using authentication')
            raise Exception('Error occured - client is not connected')
Пример #2
0
    class ProcessUpload(Thread):
        def __init__(self, name, client, q_request=None):
            Thread.__init__(self)
            self.name = name
            self.client = TelegramClient(client._session_name, client.api_id, client.api_hash, update_workers=None,
                                         spawn_read_thread=False)
            self.q_request = q_request
            self.result = None

        def run(self):
            # print('Thread %s started' % self.name)
            time.sleep(random.randrange(20, 200, 10) * 0.001)
            if not self.client.is_connected():
                self.client.connect()
            while True:
                request = self.q_request.get()
                if request is None:
                    break
                self.result = None
                # time.sleep(random.randrange(20, 100, 1) * 0.001)
                self.result = self.client.invoke(request)
                if self.result is False:
                    break
                self.q_request.task_done()
            self.client.disconnect()
            # print('Thread {0} stopped result {1}'.format(self.name, self.result))
            return
Пример #3
0
async def get_sign_in_results(api_id, api_hash, code, phone_number, password, session_name, loop=None):
    """Tries to sign-in in Telegram with given parameters.

    Notes: Automatically creates .session file for further sign-ins.

    Args:
        api_id (str/int): Telegram API id.
        api_hash (str): Telegram API hash.
        code (str/int): A confirmation code.
        phone_number (str): A phone number connected to such id/hash pair.
        password (str): 2FA password (if needed).
        session_name (str): A name of the current session.
        loop (asyncio.windows_events._WindowsSelectorEventLoop, optional): An event loop.

    Returns:
        A string describing the results of sign-in.
    """
    try:
        client = TelegramClient(session_name, api_id, api_hash, loop=loop)
        await client.connect()
    except (ApiIdInvalidError, ValueError):
        log_line("Unsuccessful sign-in! Wrong API.")
        return "wrong api"
    except OSError:
        log_line("No Internet connection.")
        return "no internet"
    try:
        if not await client.is_user_authorized():
            await client.send_code_request(phone_number)
            try:
                await client.sign_in(phone_number, code)
            except SessionPasswordNeededError:
                await client.sign_in(phone_number, password=password)
        if not await client.is_user_authorized():
            raise PhoneCodeInvalidError(request=None)
    except ApiIdInvalidError:
        log_line("Unsuccessful sign-in! Wrong API.")
        return "wrong api"
    except PhoneCodeInvalidError:
        log_line("Unsuccessful sign-in! Need code.")
        return "need code"
    except PasswordHashInvalidError:
        log_line("Unsuccessful sign-in! Need password.")
        return "need password"
    except (PhoneNumberInvalidError, TypeError):
        log_line("Unsuccessful sign-in! Need phone.")
        return "need phone"
    except FloodWaitError as err:
        log_line(f'Unsuccessful sign-in! {err.message}')
        return f'need wait for {err.seconds}'
    finally:
        if client.is_connected():
            await client.disconnect()
    log_line("Successful sign-in.")
    return "success"
Пример #4
0
async def auth_phone():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    phone = request.json['phone']

    #telegram auth
    try:
        client = TelegramClient(
            f'{telegram_sessions_path}/phone_{phone}.session',
            os.environ.get('TELEGRAM_API_ID'),
            os.environ.get('TELEGRAM_API_HASH'),
            loop=loop)

        if client.is_connected() is False:
            await client.connect()

        if await client.is_user_authorized() is False:
            code = await client.send_code_request(phone, force_sms=True)
            await client.disconnect()

            return jsonify(
                status=True,
                phone_code_hash=code.phone_code_hash,
                message=
                f'Berhasil mengirimkan kode OTP verifikasi ke nomor {phone}')
        else:
            user = await client.get_me()
            await client.disconnect()

            return jsonify(status=True,
                           user={
                               'id': user.id,
                               'username': user.username,
                               'first_name': user.first_name,
                               'last_name': user.last_name,
                               'phone': user.phone,
                               'access_hash': user.access_hash
                           },
                           message='Berhasil mendapatkan data user Telegram')
    except (PhoneNumberInvalidError, FloodWaitError) as ex:
        await client.disconnect()

        if isinstance(ex, PhoneNumberInvalidError):
            return jsonify(status=False,
                           message=f'Format nomor HP tidak valid'), 500
        elif isinstance(ex, FloodWaitError):
            return jsonify(
                status=False,
                message=
                f'Kode verifikasi OTP menunggu {ex.seconds} detik untuk pengiriman selanjutnya'
            ), 500
        else:
            return jsonify(status=False, message=str(ex)), 500
Пример #5
0
class TelegramDriver:
    def __init__(self, config, bot_dialog_config):
        self.config = config
        self.bot_dialog_config = bot_dialog_config
        self.client = None
        self.logger = logging.getLogger()
        self.updater_telegram_channel = Updater(
            self.config["crypto-bot"]["token"])

    def log_started(self):
        self.send_to_channel(self.config["crypto-bot"]["channel_id"],
                             self.bot_dialog_config["Start"])
        self.send_to_channel(self.config["crypto-bot"]["channel_id"],
                             self.bot_dialog_config["Ready"])

    def first_connection(self):
        self.client.send_code_request(
            self.config["telegram-api"]["phone_number"])
        myself = self.client.sign_in(
            self.config["telegram-api"]["phone_number"], input('Enter code: '))
        self.logger.info(myself.stringify())

    def connect(self):
        self.client = TelegramClient("User",
                                     self.config["telegram-api"]["api_id"],
                                     self.config["telegram-api"]["api_hash"],
                                     update_workers=1,
                                     spawn_read_thread=False)

        self.client.connect()
        if self.client.is_connected():

            if not self.client.is_user_authorized():
                self.first_connection()

            self.logger.info("Client connected to Telegram.")
        else:
            self.logger.error("Client not connected")

    def send_to_channel(self, channel_id, msg):
        self.updater_telegram_channel.bot.send_message(chat_id=channel_id,
                                                       text=msg)

    def add_handler_update(self, callback):
        self.client.add_update_handler(callback)

    def call_idle(self):
        self.client.idle()
        self.send_to_channel(self.config["crypto-bot"]["channel_id"],
                             self.bot_dialog_config["Stop"])

    def disconnect(self):
        self.client.disconnect()
Пример #6
0
async def update_user_photo(photo):
    client = TelegramClient(
        'upd phototemp',
        TELEGRAM_API_ID,
        TELEGRAM_API_HASH,
    )

    if not client.is_connected():
        await client.start(PHONE)

    await client(DeletePhotosRequest(await client.get_profile_photos('me')))
    await client(UploadProfilePhotoRequest(await client.upload_file(photo)))

    await client.disconnect()

    print('finish')
Пример #7
0
async def logout():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    if 'user_id' not in request.json or ObjectId.is_valid(
            request.json['user_id']) is False:
        return jsonify(status=False, message='Object Id tidak valid'), 500

    user_id = request.json['user_id']
    phone = request.json['phone']

    chat_emotion = mongo.db.telegram_chat_emotions.find_one({
        'user_id':
        ObjectId(user_id),
        'phone':
        phone
    })
    if chat_emotion is None:
        return jsonify(status=False,
                       is_authorized=False,
                       message='Belum melakukan login ke dalam Telegram'), 401

    try:
        client = TelegramClient(
            f'{telegram_sessions_path}/phone_{chat_emotion["phone"]}.session',
            os.environ.get('TELEGRAM_API_ID'),
            os.environ.get('TELEGRAM_API_HASH'),
            loop=loop)

        if client.is_connected() is False:
            await client.connect()

        if await client.is_user_authorized() is True:
            await client.log_out()
            await client.disconnect()

            return jsonify(status=True,
                           message='Berhasil melakukan logout dari Telegram')

        return jsonify(
            status=True,
            message='Pengguna belum melakukan login ke dalam Telegram')
    except Exception as ex:
        return jsonify(status=False, message=str(ex)), 500
Пример #8
0
async def update_channel_photo(photo, channel_link):
    client = TelegramClient(
        'upd phototemp',
        TELEGRAM_API_ID,
        TELEGRAM_API_HASH,
    )

    if not client.is_connected():
        await client.start(PHONE)

    dialogs = await client.get_dialogs()
    channel_entity = await client.get_entity(channel_link)
    upload_file_result = await client.upload_file(file=photo)

    try:
        result = await client(
            EditPhotoRequest(channel=channel_entity, photo=upload_file_result))
    except BaseException as e:
        print(e)

    await client.disconnect()

    print('finish')
Пример #9
0
async def two_step_verification():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    user_id = request.json['user_id']
    phone = request.json['phone']
    #phone_code_hash= request.json['phone_code_hash']
    password = request.json['password']
    is_chat_emotions_exist = mongo.db.telegram_chat_emotions.find_one({
        'user_id':
        ObjectId(user_id),
        'phone':
        phone
    })

    try:
        client = TelegramClient(
            f'{telegram_sessions_path}/phone_{phone}.session',
            os.environ.get('TELEGRAM_API_ID'),
            os.environ.get('TELEGRAM_API_HASH'),
            loop=loop)

        if client.is_connected() is False:
            await client.connect()

        if await client.is_user_authorized() is False:
            await client.sign_in(phone, password=password)
            await client.disconnect()

            #mongo check phone exist
            if is_chat_emotions_exist is None:
                result = mongo.db.telegram_chat_emotions.insert_one({
                    'user_id':
                    ObjectId(user_id),
                    'phone':
                    phone,
                    'emotions':
                    None
                })

                if result.inserted_id is None:
                    return jsonify(
                        status=False,
                        message=
                        f'Terjadi kesalahan pada server, gagal login menggunakan Telegram dengan nomor {phone}'
                    ), 500

            return jsonify(
                status=True,
                verify_success=True,
                message=
                f'Berhasil melakukan login ke dalam Telegram dengan nomor {phone}'
            )
        else:
            await client.disconnect()

            return jsonify(status=False,
                           verify_success=False,
                           message=f'Nomor {phone} sudah terverifikasi')
    except:
        await client.disconnect()

        return jsonify(status=False, message='Password anda tidak valid'), 500
Пример #10
0
class Telegram:
    def __init__(self, connect_on_start=True):
        try:
            # Load config file
            filepath = os.path.realpath(
                os.path.join(os.getcwd(), os.path.dirname(__file__)))
            configFile = filepath + "/telegram_config.json"

            #Parse details from config file
            with open(configFile) as f:
                self.config = json.load(f)
                self.username = self.config["USERNAME"]
                self.app_id = int(self.config["APP_API_ID"])
                self.api_hash = self.config["APP_API_HASH"]
                self.phone = self.config["PHONE"]
        except:
            print(
                "You must provide a telegram_config.json file with proper credentials."
            )

        # Create the client
        self.client = TelegramClient(self.username, self.app_id, self.api_hash)
        if connect_on_start:
            self.connect()

    async def connect(self):
        self.client.start()
        print("Client Created")
        # Ensure you're authorized
        if not await self.client.is_user_authorized():
            self.client.send_code_request(self.phone)
            try:
                self.client.sign_in(self.phone, input('Enter the code: '))
            except SessionPasswordNeededError:
                self.client.sign_in(password=input('Password: '******'with' destroys the client after the code block
        with self.client:
            #I don't know async lol, this just runs once
            self.client.loop.run_until_complete(self.connect())
            #This contains a loop to poll for messages
            self.client.loop.run_until_complete(
                self.scrape_channel(telegram_url))

    async def scrape_channel(self, telegram_url):
        self.channel = await self.client.get_entity(telegram_url)
        offset_id = 0
        limit = 100
        all_messages = []
        total_messages = 0
        total_count_limit = 1000

        while True:
            print("Current Offset ID is:", offset_id, "; Total Messages:",
                  total_messages)
            history = await self.client(
                GetHistoryRequest(peer=self.channel,
                                  offset_id=offset_id,
                                  offset_date=None,
                                  add_offset=0,
                                  limit=limit,
                                  max_id=0,
                                  min_id=0,
                                  hash=0))
            if not history.messages:
                break
            messages = history.messages
            for message in messages:
                all_messages.append(message.to_dict())
            offset_id = messages[len(messages) - 1].id
            total_messages = len(all_messages)
            if total_count_limit != 0 and total_messages >= total_count_limit:
                break

        with open('channel_messages.json', 'w') as outfile:
            json.dump(all_messages,
                      outfile,
                      indent=4,
                      sort_keys=True,
                      default=str)
Пример #11
0
async def get_chat_emotions(user_id, phone):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    if ObjectId.is_valid(user_id) is False:
        return jsonify(message='Object Id tidak valid'), 500

    chat_emotions = mongo.db.telegram_chat_emotions.find_one({
        'user_id':
        ObjectId(user_id),
        'phone':
        phone
    })

    if chat_emotions is None:
        return jsonify(status=False,
                       is_authorized=False,
                       message='Belum melakukan login ke dalam Telegram')

    try:
        client = TelegramClient(
            f'{telegram_sessions_path}/phone_{chat_emotions["phone"]}.session',
            os.environ.get('TELEGRAM_API_ID'),
            os.environ.get('TELEGRAM_API_HASH'),
            loop=loop)

        if client.is_connected() is False:
            await client.connect()

        if await client.is_user_authorized() is False:
            return jsonify(status=False,
                           is_authorized=False,
                           message='Belum melakukan login ke dalam Telegram')
        else:
            entities = await client.get_dialogs()
            messages = []

            for entity in entities:
                sender = await client.get_entity(entity)

                if (isinstance(sender, User) and sender.bot is False
                        and sender.first_name != 'Telegram'):
                    message_container = client.iter_messages(entity)

                    async for message_object in message_container:
                        if (message_object.out is True
                                and message_object.message is not None
                                and message_object.message != ''):
                            chat_with = await client.get_entity(
                                message_object.peer_id)

                            messages.append({
                                'chat_with': {
                                    'user_id': chat_with.id,
                                    'first_name': chat_with.first_name,
                                    'phone': '+' + str(chat_with.phone)
                                },
                                'data': {
                                    'message_id': message_object.id,
                                    'text': message_object.message,
                                    'timestamps': message_object.date,
                                    'is_out_message': message_object.out
                                },
                                'emotions': {}
                            })

            await client.disconnect()

            translator = Translator()
            for message in messages:
                translated = translator.translate(message['data']['text'],
                                                  src='id')
                emotions = te.get_emotion(translated.text)
                message['emotions'] = {
                    'angry': emotions['Angry'],
                    'fear': emotions['Fear'],
                    'happy': emotions['Happy'],
                    'sad': emotions['Sad'],
                    'surprise': emotions['Surprise'],
                }

            emotions_total = {
                'angry': 0,
                'fear': 0,
                'happy': 0,
                'sad': 0,
                'surprise': 0
            }
            for message in messages:
                for key in message['emotions']:
                    if message['emotions'][key] > 0:
                        emotions_total[key] += 1

            # if chat_emotions['emotions'] != emotions_total:
            #     result= mongo.db.telegram_chat_emotions.find_one_and_update(
            #         { 'user_id': ObjectId(user_id) },
            #         { '$set': { 'emotions': dict(emotions_total) } }
            #     )

            #     if result is None:
            #         return jsonify(status= False, message= 'Terjadi kesalahan pada server, gagal menyimpan data emosi teks pengguna'), 500

            return jsonify(
                status=True,
                chat_emotions={
                    'emotions_total': emotions_total,
                    'messages': messages
                },
                message='Berhasil mendapatkan riwayat pesan telegram')
    except (FloodWaitError, Exception) as ex:
        await client.disconnect()

        if isinstance(ex, FloodWaitError):
            return jsonify(
                status=False,
                message=
                f'Kode verifikasi OTP menunggu {ex.seconds} detik untuk pengiriman selanjutnya'
            ), 500
        else:
            return jsonify(status=False, message=str(ex)), 500
Пример #12
0
    def post(self):
        phone = parse_phone(self.request.data.get('phone'))

        if phone == self.user['phone_number']:
            user = self.get()
            if user.get('authorized', True):
                return user

        code = self.request.data.get('code')
        password = self.request.data.get('password')
        phone_code_hash = None

        if not phone:
            raise HTTP_400('Invalid `phone` value')

        msg = None
        is_authorized = False
        try:
            client = TelegramClient(
                os.path.join(config.get('paths', 'sessions'),
                             parse_phone(phone)),
                config.get('telegram', 'api_id'),
                config.get('telegram', 'api_hash'))
            if not client.is_connected():
                client.connect()

            # check if already authorized
            if client.is_user_authorized():
                self._set_authorized(phone)
                is_authorized = True
                raise AuthorizedSuccessfully()

            # 2nd step
            if code:
                t = db.get_interim_state(phone)
                if not t:
                    raise HTTP_400('Invalid `phone` value')
                phone_code_hash = t['phone_code_hash']

            resp = client.sign_in(phone,
                                  code,
                                  password=password,
                                  phone_code_hash=phone_code_hash)

            # 2nd/3rd step success
            if code and client.is_user_authorized():
                self._set_authorized(phone)
                is_authorized = True
                raise AuthorizedSuccessfully()

            # 1st step
            if not resp.phone_registered:
                db.del_interim_state(phone)
                raise HTTP_400('Phone number is not registered')

            db.set_interim_state(phone, {
                'provider': 'Telegram',
                'phone_code_hash': resp.phone_code_hash
            })
            return {'authorized': False, 'code': True}
        except AuthorizedSuccessfully:
            pass
        except SessionPasswordNeededError:
            return {'authorized': False, '2fa': True}
        except (PhoneNumberBannedError, PhoneNumberInvalidError,
                PhoneCodeExpiredError, PhoneCodeInvalidError,
                PhoneCodeEmptyError, PhonePasswordProtectedError) as e:
            db.del_interim_state(phone)
            client.log_out()
            raise HTTP_400(str(e))
        except (FloodWaitError, FloodError, PhonePasswordFloodError) as e:
            db.del_interim_state(phone)
            raise HTTP_400(str(e))
        except HTTPError:  # passthru
            raise
        except Exception as e:
            self.logger.error('Telegram communication error %s', e)
            msg = str(e)
            raise
        finally:
            client.disconnect()

        if is_authorized:
            return self.get()

        raise HTTP_500('Internal error', msg)
Пример #13
0
def messages_task(limit,
                  user_id,
                  group_id,
                  message_id,
                  numbers_list=None,
                  use_system_numbers=False):
    user = User.objects.get(pk=user_id)
    group = TelegramGroup.objects.get(pk=group_id)
    message = Message.objects.get(pk=message_id)

    if use_system_numbers:
        price = settings.PRICE_USING_SYSTEM_NUMBERS
        active_accounts = TelegramAccount.objects.filter(system=True,
                                                         confirmed=True,
                                                         active=True,
                                                         is_used_now=False)
    else:
        price = settings.PRICE_USING_OWN_NUMBERS
        # active_accounts = TelegramAccount.objects.filter(id__in=numbers_list,
        #                                                  user=user,
        #                                                  system=False,
        #                                                  confirmed=True,
        #                                                  active=True,
        #                                                  is_used_now=False)
        active_accounts = TelegramAccount.objects.filter(user=user,
                                                         system=False,
                                                         confirmed=True,
                                                         active=True,
                                                         is_used_now=False)
    if not active_accounts:
        return {'success': False, 'error': _('No active accounts left.')}

    messaged = 0

    try:
        for account in active_accounts:
            # mark being used now, so account won't be used in other tasks
            account.set_is_used(True)

            proxy_settings = (
                socks.HTTP, settings.PROXY_HOST, settings.PROXY_PORT, True,
                settings.PROXY_USERNAME +
                '-session-{}'.format(random.randint(9999, 9999999)),
                settings.PROXY_PASSWORD)
            client = TelegramClient(StringSession(account.session),
                                    account.api_id,
                                    account.api_hash,
                                    proxy=proxy_settings)
            # connect to Telegram
            try:
                client.connect()
            except Exception as e:
                logger.exception(e)
                account.set_is_used(False)
                continue

            # find not messaged contacts or with errors
            message_events = MessageEvent.objects.filter(
                Q(success=True) | Q(error__isnull=False),
                user=user,
                telegram_group=group,
                message=message)
            processed_contacts = [i.contact for i in message_events]
            contacts = [
                c for c in TelegramContact.objects.filter(
                    user=user, group=group).order_by('priority')
                if c not in processed_contacts
            ]

            # send messages to contacts
            for contact in contacts:
                if messaged >= limit:
                    client.disconnect()
                    account.set_is_used(False)
                    return {'success': True, 'error': None}
                if user.balance <= 0:
                    client.disconnect()
                    account.set_is_used(False)
                    return {
                        'success':
                        False,
                        'error':
                        _('Not enough funds. Please, '
                          'refill your balance.')
                    }
                try:
                    if message.file:
                        client.send_message(contact.username,
                                            message.text,
                                            file=message.file.path,
                                            link_preview=message.link_preview,
                                            parse_mode='html')
                    else:
                        client.send_message(contact.username,
                                            message.text,
                                            link_preview=message.link_preview,
                                            parse_mode='html')
                    messaged += 1
                    user.update_balance(-price)
                    MessageEvent.objects.create(user=user,
                                                telegram_group=group,
                                                telegram_account=account,
                                                contact=contact,
                                                success=True,
                                                message=message,
                                                price=price)

                # errors with account
                except (PeerFloodError, AuthKeyUnregisteredError,
                        UserDeactivatedError, ChatWriteForbiddenError,
                        UserBannedInChannelError, ChannelsTooMuchError) as e:
                    client.disconnect()
                    account.set_is_used(False)
                    account.deactivate(e.__class__.__name__)
                    break
                except Exception as e:
                    MessageEvent.objects.create(user=user,
                                                telegram_group=group,
                                                contact=contact,
                                                telegram_account=account,
                                                message=message,
                                                error=e.__class__.__name__)
                    account.update_last_used()

            account.set_is_used(False)

            if client.is_connected():
                client.disconnect()

        return {'success': True, 'error': None}
    except Exception as e:
        logger.exception(e)
        return {'success': True, 'error': _('Error sending message.')}
Пример #14
0
def invites_task(limit,
                 user_id,
                 source_group_id,
                 target_group_id,
                 numbers_list=None,
                 use_system_numbers=False):
    user = User.objects.get(pk=user_id)
    source_group = TelegramGroup.objects.get(pk=source_group_id)
    target_group = TelegramGroup.objects.get(pk=target_group_id)

    if use_system_numbers:
        price = settings.PRICE_USING_SYSTEM_NUMBERS
        active_accounts = TelegramAccount.objects.filter(system=True,
                                                         confirmed=True,
                                                         active=True,
                                                         is_used_now=False)
    else:
        price = settings.PRICE_USING_OWN_NUMBERS
        # active_accounts = TelegramAccount.objects.filter(id__in=numbers_list,
        #                                                  user=user,
        #                                                  system=False,
        #                                                  confirmed=True,
        #                                                  active=True,
        #                                                  is_used_now=False)
        active_accounts = TelegramAccount.objects.filter(user=user,
                                                         system=False,
                                                         confirmed=True,
                                                         active=True,
                                                         is_used_now=False)
    if not active_accounts:
        return {'success': False, 'error': _('No active accounts left.')}

    invited = 0
    try:
        for account in active_accounts:
            # mark being used now, so account won't be used in other tasks
            account.set_is_used(True)

            proxy_settings = (
                socks.HTTP, settings.PROXY_HOST, settings.PROXY_PORT, True,
                settings.PROXY_USERNAME +
                '-session-{}'.format(random.randint(9999, 9999999)),
                settings.PROXY_PASSWORD)
            client = TelegramClient(StringSession(account.session),
                                    account.api_id,
                                    account.api_hash,
                                    proxy=proxy_settings)
            # connect to Telegram
            try:
                client.connect()
            except Exception as e:
                logger.exception(e)
                account.set_is_used(False)
                continue

            # get target group entity
            try:
                target_group_entity = client.get_input_entity(
                    target_group.username if target_group.
                    username else target_group.join_link)
            except Exception as e:
                logger.exception(e)
                client.disconnect()
                account.set_is_used(False)
                return {'success': False, 'error': _('Target Group invalid.')}

            # join channel
            joined = join_group(client, account, target_group_entity)
            if not joined:
                account.set_is_used(False)
                client.disconnect()
                continue
            elif isinstance(joined, dict):  # means there was an error
                client.disconnect()
                return joined

            # find not invited contacts or with errors
            invites = InviteEvent.objects.filter(Q(success=True)
                                                 | Q(error__isnull=False),
                                                 user=user,
                                                 source_group=source_group,
                                                 target_group=target_group)
            processed_contacts = [i.contact for i in invites]
            contacts = [
                c for c in TelegramContact.objects.filter(
                    user=user, group=source_group).order_by('priority')
                if c not in processed_contacts
            ]

            # invite contacts
            for contact in contacts:
                if invited >= limit:
                    account.set_is_used(False)
                    client.disconnect()
                    return {'success': True, 'error': None}
                if user.balance <= 0:
                    account.set_is_used(False)
                    client.disconnect()
                    return {
                        'success':
                        False,
                        'error':
                        _('Not enough funds. Please, '
                          'refill your balance.')
                    }
                try:
                    client(
                        InviteToChannelRequest(target_group_entity,
                                               [contact.username]))
                    invited += 1
                    user.update_balance(-price)
                    InviteEvent.objects.create(user=user,
                                               source_group=source_group,
                                               target_group=target_group,
                                               telegram_account=account,
                                               contact=contact,
                                               success=True,
                                               price=price)

                # errors with account
                except (PeerFloodError, AuthKeyUnregisteredError,
                        UserDeactivatedError, ChatWriteForbiddenError,
                        UserBannedInChannelError, ChannelsTooMuchError) as e:
                    logger.exception(e)
                    account.deactivate(e.__class__.__name__)
                    account.set_is_used(False)
                    client.disconnect()
                    break

                # critical errors, when we need to stop inviting
                except ChannelPrivateError as e:
                    InviteEvent.objects.create(user=user,
                                               source_group=source_group,
                                               target_group=target_group,
                                               telegram_account=account,
                                               error=e.__class__.__name__)
                    account.update_last_used()
                    account.set_is_used(False)
                    client.disconnect()
                    return {
                        'success':
                        False,
                        'error':
                        _('Cannot invite to Channel, '
                          'since it is private.')
                    }
                except ChatIdInvalidError as e:
                    InviteEvent.objects.create(user=user,
                                               source_group=source_group,
                                               target_group=target_group,
                                               telegram_account=account,
                                               error=e.__class__.__name__)
                    account.update_last_used()
                    account.set_is_used(False)
                    client.disconnect()
                    return {
                        'success':
                        False,
                        'error':
                        _('Cannot invite to Channel, '
                          'since it is private.')
                    }
                except ChatAdminRequiredError as e:
                    InviteEvent.objects.create(user=user,
                                               source_group=source_group,
                                               target_group=target_group,
                                               telegram_account=account,
                                               error=e.__class__.__name__)
                    account.update_last_used()
                    account.set_is_used(False)
                    client.disconnect()
                    return {
                        'success':
                        False,
                        'error':
                        _('Cannot invite to Channel, '
                          'since it admin rights are required.')
                    }

                except InputUserDeactivatedError as e:
                    InviteEvent.objects.create(user=user,
                                               source_group=source_group,
                                               target_group=target_group,
                                               telegram_account=account,
                                               contact=contact,
                                               error=e.__class__.__name__)
                    account.update_last_used()
                except UsersTooMuchError as e:
                    InviteEvent.objects.create(user=user,
                                               source_group=source_group,
                                               target_group=target_group,
                                               telegram_account=account,
                                               error=e.__class__.__name__)
                    account.update_last_used()
                    client.disconnect()
                    return {
                        'success':
                        False,
                        'error':
                        _('Cannot invite to Channel, '
                          'since it has already reached the '
                          'maximum number of users.')
                    }
                # other errors
                except Exception as e:
                    InviteEvent.objects.create(user=user,
                                               source_group=source_group,
                                               target_group=target_group,
                                               telegram_account=account,
                                               contact=contact,
                                               error=e.__class__.__name__)
                    account.update_last_used()

            account.set_is_used(False)

            if client.is_connected():
                client.disconnect()

        return {'success': True, 'error': None}
    except Exception as e:
        logger.exception(e)
        return {'success': True, 'error': None}
Пример #15
0
def register_accounts(limit):
    registered_count = 0
    fails_count = 0
    while registered_count < limit:
        summary = get_summary()
        if summary is None or summary['balance'] < 0.12:
            fails_count += 1
            continue
        number = get_mobile_number()
        if number is None:
            fails_count += 1
            continue
        proxy = session.query(Proxy).first()
        client = TelegramClient(os.path.join(config.TELETHON_SESSIONS_DIR,
                                             '+' + str(number)),
                                config.TELEGRAM_API_ID,
                                config.TELEGRAM_API_HASH,
                                proxy=(socks.HTTP, proxy.ip, proxy.port, True,
                                       proxy.username, proxy.password))
        try:
            client.connect()
            client.send_code_request('+' + str(number), force_sms=True)
            send_code_time = datetime.datetime.now()
            sms = None
            while (datetime.datetime.now() -
                   send_code_time).total_seconds() < 65:
                sms = get_sms(number)
                if sms:
                    break
                else:
                    time.sleep(10)
            if sms is None:
                fails_count += 1
                blacklist_mobile_number(number)
                client.disconnect()
                continue

            try:
                name = get_random_first_last_names()
                myself = None
                try:
                    myself = client.sign_up(sms,
                                            first_name=name['first'],
                                            last_name=name['last'])
                except PhoneNumberOccupiedError:
                    config.logger.error(
                        'PhoneNumberOccupiedError, trying to login instead.')
                    try:
                        myself = client.sign_in('+' + str(number), sms)
                    except Exception as e:
                        config.logger.exception(e)
                        fails_count += 1
                if myself:
                    registered_count += 1
                    client.send_message(
                        'llelloboss', 'Hello! This account ({}) is'
                        ' active.'.format('+' + str(number)))
                    account = TelegramAccount(phone_number='+' + str(number))
                    session.add(account)
                    session.commit()

                client.disconnect()
            except Exception as e:
                config.logger.exception(e)
                fails_count += 1
                client.disconnect()
                continue
        except Exception as e:
            config.logger.exception(e)
            if client.is_connected():
                client.disconnect()
            fails_count += 1

    for adm in config.ADMIN_IDS:
        bot.send_message(
            adm, f'Registration finished.\n'
            f'Registered: {registered_count}\n'
            f'Failed: {fails_count}')
Пример #16
0
def invite_contact(task_id):
    task = session.query(Task).filter(Task.id == task_id).first()
    accounts = session.query(TelegramAccount).filter(
        TelegramAccount.active == True, TelegramAccount.task == task).order_by(
            TelegramAccount.last_used).all()
    if not accounts:
        session.delete(task)
        session.commit()
        for adm in config.ADMIN_IDS:
            bot.send_message(adm, f'<code>Inviting to {task.target_group} '
                             f'from {task.source_group}</code> stopped.\n'
                             f'No active accounts left.',
                             parse_mode=ParseMode.HTML)
        return
    account = random.choice(accounts)
    contacts = session.query(Contact).filter(
        Contact.source_group == task.source_group).order_by(
            desc(Contact.priority)).all()
    invite_errors = session.query(InviteError).filter(
        InviteError.task == task).all()
    contacts_with_errors_ids = [i.contact_id for i in invite_errors]
    invited_contacts_ids = [c.id for c in task.invited_contacts]
    contacts = [
        c for c in contacts if c.id not in invited_contacts_ids
        and c.id not in contacts_with_errors_ids
    ]
    proxy = session.query(Proxy).first()
    client = TelegramClient(os.path.join(config.TELETHON_SESSIONS_DIR,
                                         account.phone_number),
                            config.TELEGRAM_API_ID,
                            config.TELEGRAM_API_HASH,
                            proxy=(socks.HTTP, proxy.ip, proxy.port, True,
                                   proxy.username, proxy.password))
    try:
        client.connect()
        target_participants = client.get_participants(task.target_group,
                                                      aggressive=True)
        target_participants_ids = [i.id for i in target_participants]
        if int(contacts[0].tg_id) not in target_participants_ids:
            target = int(task.target_group) if task.target_group.startswith('-') \
                else task.target_group.lower()
            if int(client.get_me().id) not in target_participants_ids:
                client(JoinChannelRequest(target))
            client(InviteToChannelRequest(target, [contacts[0].username]))
            task.invited_contacts.append(contacts[0])
            account.last_used = datetime.datetime.now()
            session.commit()
        else:
            error = InviteError(task=task, contact=contacts[0])
            session.add(error)
            account.last_used = datetime.datetime.now()
            session.commit()
    except PeerFloodError as e:
        config.logger.exception(e)
        account.active = False
        account.task = None
        account.error_time = datetime.datetime.now()
        session.commit()
    except UserKickedError as e:
        config.logger.exception(e)
        account.active = False
        account.task = None
        account.error_time = datetime.datetime.now()
        session.commit()
    except (AuthKeyUnregisteredError, UserDeactivatedError) as e:
        config.logger.exception(e)
        session.delete(account)
        session.commit()
        path = os.path.join(config.TELETHON_SESSIONS_DIR,
                            '{}.session'.format(account.phone_number))
        if os.path.exists(path):
            os.remove(path)
        for adm in config.ADMIN_IDS:
            bot.send_message(
                adm,
                f'Account {account.phone_number} had {e.__class__.__name__} '
                f'and was removed.')
    except (UserNotMutualContactError, UserPrivacyRestrictedError) as e:
        config.logger.exception(e)
        error = InviteError(task=task, contact=contacts[0])
        session.add(error)
        session.commit()
    except Exception as e:
        config.logger.exception(e)

    if client.is_connected():
        client.disconnect()
Пример #17
0
async def auth_code():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    if 'user_id' not in request.json or ObjectId.is_valid(
            request.json['user_id']) is False:
        return jsonify(message='Object Id tidak valid'), 500

    user_id = request.json['user_id']
    phone = request.json['phone']
    phone_code_hash = request.json['phone_code_hash']
    otp_code = request.json['otp_code']
    is_chat_emotions_exist = mongo.db.telegram_chat_emotions.find_one({
        'user_id':
        ObjectId(user_id),
        'phone':
        phone
    })

    try:
        client = TelegramClient(
            f'{telegram_sessions_path}/phone_{phone}.session',
            os.environ.get('TELEGRAM_API_ID'),
            os.environ.get('TELEGRAM_API_HASH'),
            loop=loop)

        if client.is_connected() is False:
            await client.connect()

        if await client.is_user_authorized() is False:
            await client.sign_in(phone,
                                 otp_code,
                                 phone_code_hash=phone_code_hash)
            await client.disconnect()

            #mongo check phone exist
            if is_chat_emotions_exist is None:
                result = mongo.db.telegram_chat_emotions.insert_one({
                    'user_id':
                    ObjectId(user_id),
                    'phone':
                    phone,
                    'emotions':
                    None
                })

                if result.inserted_id is None:
                    return jsonify(
                        status=False,
                        message=
                        f'Terjadi kesalahan pada server, gagal login menggunakan Telegram dengan nomor {phone}'
                    ), 500

            return jsonify(
                status=True,
                verify_success=True,
                message=
                f'Berhasil melakukan login ke dalam Telegram dengan nomor {phone}'
            )
        else:
            await client.disconnect()

            return jsonify(status=False,
                           verify_success=False,
                           message=f'Nomor {phone} sudah terverifikasi')
    except (SessionPasswordNeededError, PhoneCodeExpiredError,
            PhoneCodeInvalidError) as ex:
        await client.disconnect()

        if isinstance(ex, SessionPasswordNeededError):
            return jsonify(
                status=False,
                is_two_step_verification=True,
                message=
                'Two-step verification akun milik anda dalam keadaan aktif, harap lakukan login disini'
            )
        elif isinstance(ex, PhoneCodeExpiredError):
            return jsonify(
                status=False,
                message='Kode verifikasi OTP sudah tidak berlaku'), 500
        elif isinstance(ex, PhoneCodeInvalidError):
            return jsonify(status=False,
                           message='Kode verifikasi OTP tidak valid'), 500
        else:
            return jsonify(status=False, message=str(ex)), 500